答:
First and foremost, on the theoretical side, the case you describe (A & B never in the panel at the same time) won't give you a null correlation but a negative correlation. Indeed, whenever A = 1, B = 0 and whenever B = 1, A = 0, so an anti-correlation appears. The correlation won't necessarily equal -1 though, because you will obviously encounter cases where A = B = 0 (unless customers always buy A and B which is unrealistic).

On the other hand, you may encounter nearly null correlation in the case A and B are seldom bought (which means numerous occurrences of A = B = 0).

As for how to code it, you can use model.matrix to transform your data into dummy variables and aggregate to gather panel contents by WOrderId. Here is an example using your structure.

```<code>mydf <- data.frame(WOrderId = c(c(1:8),c(1:8)),
                   OtherLangDescription = c(rep("Water",4),rep("Milk",4),
                     rep("Apple",2), rep("Beef",2), rep("Candy",2), rep("Apple",2)))
mydf$OtherLangDescription <- as.factor(mydf$OtherLangDescription)
dummydf <- model.matrix(WOrderId ~ OtherLangDescription, mydf,
                             contrasts.arg = list(OtherLangDescription = contrasts(mydf$OtherLangDescription,
                                                      contrasts = F)))
fulldf <- data.frame(mydf$WOrderId, dummydf[,2:ncol(dummydf)])
agregdf <- aggregate(. ~ mydf.WOrderId, fulldf, sum)
cor(agregdf[,2:ncol(agregdf)])
</code>```

Which gives the following output.

```<code>                          OtherLangDescriptionApple OtherLangDescriptionBeef OtherLangDescriptionCandy
OtherLangDescriptionApple                 1.0000000               -0.5773503                -0.5773503
OtherLangDescriptionBeef                 -0.5773503                1.0000000                -0.3333333
OtherLangDescriptionCandy                -0.5773503               -0.3333333                 1.0000000
OtherLangDescriptionMilk                  0.0000000               -0.5773503                 0.5773503
OtherLangDescriptionWater                 0.0000000                0.5773503                -0.5773503
                          OtherLangDescriptionMilk OtherLangDescriptionWater
OtherLangDescriptionApple                0.0000000                 0.0000000
OtherLangDescriptionBeef                -0.5773503                 0.5773503
OtherLangDescriptionCandy                0.5773503                -0.5773503
OtherLangDescriptionMilk                 1.0000000                -1.0000000
OtherLangDescriptionWater               -1.0000000                 1.0000000
</code>```

As you can see, since apples are never in the same panel as beef or candies, the correlation is negative. Beef has "great" correlation with water because water is always present whenever you get beef.

Note that apples and milk have a null correlation (same for apple and water), because half of the time apples are bought, water is also bought. Hence a null correlation does not imply that products are anti-correlated (they are just uncorrelated).

EDIT as per comments, you are not calculating correlation, but conditional probabilities per product.

Here is a way to achieve this calculation.

```<code>prodList <- unique(mydf$OtherLangDescription) # get distinct list of products
prodListId <- lapply(prodList, function(x) subset(mydf, OtherLangDescription == x)$WOrderId) # get list of orders in which each product appears
prodListProduct <- lapply(prodListId, function(x) subset(mydf, WOrderId %in% x)$OtherLangDescription) # get products appearing in those orders
prodListTable <- mapply(function(Product, ID) table(Product)/length(ID),
                         prodListProduct, prodListId) # divide occurrences of products by number of orders to get conditional probabilities
colnames(prodListTable) <- prodList
</code>```

Title: How to Calculate Multiple Correlation Between Several Products using Boolean values With R

Body:
I  want to compute the multiple correlation between several products depending on the frequency of getting them together (i.e as EX: product A has a large correlation coefficient with product B because the most orders of A were with product B at the same order) OR (If there's no order has A & B at the same time then the correlation between them = 0)
and i want to do that to create a recommendation model for every new order (recommend the products depending on the degree of the correlation between the selected product and others).
and this's a sample from my data :

structure(list(WHWorkOrderHeaderId = c(137413L, 137413L, 137413L,
137413L, 137413L, 137413L, 137413L, 137413L, 137413L, 137413L,
137413L, 137413L, 136729L, 136729L, 136729L, 136729L, 136729L,
136729L, 136729L, 136729L, 136729L, 136729L, 136729L, 136729L,
136729L, 137260L, 137260L, 137260L, 137260L, 137260L, 137260L,
137260L, 137260L, 137260L, 137260L, 137429L, 137429L, 137429L,
137429L, 137429L, 137429L, 137429L, 137429L, 137429L, 137974L,
137974L, 137902L, 137902L, 137902L, 137902L, 137902L, 137902L,
137902L, 138837L, 138837L, 138837L, 138837L, 138837L, 138837L,
140938L, 140938L, 140938L, 140938L, 140938L, 140938L, 140938L,
140938L, 140938L, 140938L, 139642L, 139642L, 139642L, 139642L,
139642L, 139642L, 139642L, 140676L, 140676L, 140676L, 140676L,
140676L, 140676L, 139424L, 139424L, 139424L, 139424L, 139424L,
139424L, 139424L, 139424L, 139424L, 141302L, 141302L, 141302L,
141302L, 141302L, 141302L, 138297L, 138297L, 138297L, 138297L,
138297L, 138297L, 138297L, 138297L, 138297L, 138297L, 138297L,
138297L, 138297L, 137302L, 137302L, 137302L, 137302L, 134444L,
134444L, 134444L, 141134L, 141134L, 141134L, 141134L, 134468L,
134468L, 131965L, 131965L, 131965L, 131965L, 131965L, 131965L,
131965L, 131965L, 131965L, 135722L, 135722L, 135722L, 135722L,
135722L, 135722L, 135722L, 135722L, 135722L, 135722L, 135722L,
135722L, 135722L, 135722L, 139444L, 139444L, 139444L, 139444L,
139444L, 139444L, 137419L, 137419L, 137419L, 137419L, 137419L,
137419L, 137419L, 137419L, 137419L, 137419L, 137419L, 137419L,
136078L, 136078L, 136078L, 136078L, 136078L, 136078L, 136078L,
136078L, 136078L, 136078L, 136078L, 136078L, 136078L, 131866L,
131866L, 131866L, 131866L, 131866L, 131866L, 131866L, 139214L,
139214L, 139214L, 139214L, 139214L, 139214L, 131997L, 131997L,
131997L, 131997L, 139482L, 139482L, 139482L, 139482L, 139482L,
139482L, 139482L, 137352L, 137352L, 137352L, 137352L, 137352L,
137352L, 137352L, 137352L, 136610L, 136610L, 136610L, 136610L,
136610L, 136066L, 136066L, 136066L, 136066L, 136066L, 136066L,
136066L, 133358L, 133358L, 133358L, 134522L, 134522L, 134522L,
134522L, 134522L, 134522L, 134522L, 134522L, 131481L, 131481L,
131481L, 131918L, 131918L, 131918L, 131918L, 135758L, 135758L,
135758L, 135758L, 135678L, 135678L, 135678L, 135678L, 135678L,
135678L, 135678L, 135678L, 135678L, 131986L, 131986L, 131986L,
131986L, 131986L, 131986L, 131986L, 139468L, 139468L, 139468L,
139468L, 139468L, 139468L, 139468L, 139468L, 139468L, 139468L,
139533L, 139533L, 139533L, 139533L, 139533L, 139533L, 139533L,
139533L, 139533L, 131950L, 137540L, 137540L, 137540L, 137540L,
137540L, 137540L, 137540L, 138021L, 138021L, 138021L, 138021L,
138021L, 138021L, 138021L, 138021L, 138021L, 139280L, 139280L,
139280L, 139280L, 139280L, 139280L, 139280L, 139280L, 139280L,
139280L, 139280L, 139280L, 139280L, 139280L, 139280L, 139280L,
134490L, 134490L, 134490L, 134490L, 134490L, 134490L, 134490L,
134490L, 134490L, 134490L, 135747L, 135747L, 135747L, 135747L,
135747L, 135747L, 135747L, 135747L, 135747L, 135747L, 135747L,
141057L, 141057L, 141057L, 141057L, 141057L, 141057L, 141057L,
141057L, 141057L, 141057L, 141057L, 141057L, 141057L, 141057L,
141057L, 141057L, 141057L, 141057L, 141057L, 141057L, 141057L,
136233L, 136233L, 136233L, 136233L, 136233L, 136233L, 136233L,
136233L, 136233L, 136233L, 136233L, 136233L, 136233L, 136233L,
136233L, 136233L, 136233L, 136233L, 136233L, 136233L, 136233L,
136430L, 136430L, 136430L, 136430L, 136430L, 136430L, 136430L,
136430L, 136430L, 136430L, 136430L, 136430L, 136430L, 136430L,
141055L, 141055L, 141055L, 141055L, 141055L, 141055L, 141055L,
141055L, 131666L, 131666L, 131666L, 131666L, 131666L, 131666L,
131666L, 131666L, 131551L, 131551L, 131551L, 131551L, 131551L,
131551L, 131551L, 131551L, 131551L, 131469L, 131469L, 131469L,
131469L, 131469L, 131469L, 131469L, 131469L, 131469L, 131469L,
131469L, 131301L, 131321L, 131775L, 131775L, 131775L, 131775L,
131775L, 131775L, 131775L, 131775L, 131993L, 131993L, 131993L,
131993L, 131993L, 131993L, 131993L, 131993L, 131993L, 131993L,
131993L, 131993L, 132139L, 132139L, 132139L, 132139L, 132139L,
132139L, 132139L, 132139L, 132139L, 132139L, 132139L, 132139L,
132139L, 132139L, 134584L, 134584L, 134584L, 134584L, 134584L,
134584L, 134584L, 134584L, 134584L, 134584L, 134584L, 134584L,
134584L, 134584L, 134584L, 134584L, 134584L, 134584L, 134584L,
134584L, 134584L, 134584L, 134584L, 134584L, 134585L, 134585L,
134585L, 134585L, 134585L, 134585L, 134585L, 134585L, 134585L,
134585L, 134585L, 134585L, 134585L, 134585L, 134585L, 134585L,
134585L, 136986L, 136986L, 136986L, 136986L, 136986L, 132252L,
132252L, 132252L, 132252L, 132252L, 132252L, 132252L, 132252L,
132252L, 132252L, 131880L, 131880L, 131880L, 131880L, 131880L,
131880L, 131880L, 131880L, 131880L, 131880L, 136227L, 136227L,
136227L, 136227L, 136227L, 136227L, 136227L, 136227L, 136227L,
136227L, 136227L, 136356L, 136356L, 136356L, 136356L, 136356L,
136356L, 136356L, 136356L, 136356L, 136356L, 136356L, 136356L,
136356L, 136356L, 136356L, 141289L, 141289L, 141289L, 141289L,
141289L, 141289L, 141289L, 141289L, 141289L, 141289L, 141289L,
141289L, 141289L, 141289L, 139342L, 139342L, 139342L, 139342L,
139342L, 131915L, 131915L, 131915L, 131915L, 139297L, 139297L,
139297L, 139297L, 139297L, 139297L, 139297L, 139297L, 132175L,
132175L, 132175L, 132175L, 134504L, 134504L, 134504L, 134504L,
134504L, 134504L, 134504L, 134504L, 134504L, 134504L, 133320L,
133320L, 133320L, 133320L, 133320L, 133320L, 133320L, 133320L,
133320L, 133320L, 133320L, 133320L, 133320L, 133320L, 133320L,
133320L, 133320L, 133320L, 139105L, 139105L, 139105L, 139105L,
139105L, 139105L, 139105L, 139105L, 138050L, 138050L, 138050L,
138050L, 138050L, 138050L, 138050L, 138050L, 138050L, 138050L,
132216L, 132216L, 132216L, 132216L, 132216L, 132216L, 132216L,
132217L, 132217L, 132217L, 132217L, 132217L, 132217L, 132217L,
132217L, 131635L, 131635L, 131635L, 135792L, 135792L, 135792L,
135792L, 135792L, 135792L, 135792L, 135792L, 135792L, 135792L,
135792L, 137650L, 137650L, 137650L, 137650L, 137788L, 137788L,
137788L, 138028L, 138028L, 138028L, 138028L, 139057L, 139057L,
139057L, 139057L, 138497L, 138497L, 138497L, 138497L, 138497L,
138497L, 138597L, 139581L, 139581L, 139581L, 139581L, 139581L,
139581L, 139581L, 139581L, 139581L, 139581L, 139581L, 139581L,
139581L, 131894L, 131894L, 131894L, 131894L, 131894L, 131894L,
131894L, 132205L, 132205L, 132205L, 132205L, 132205L, 132205L,
132205L, 132205L, 132205L, 135981L, 135981L, 135981L, 135981L,
135981L, 135981L, 135981L, 135981L, 135981L, 136683L, 136683L,
136683L, 136683L, 136683L, 136683L, 136683L, 136683L, 136683L,
136683L, 136683L, 136683L, 136683L, 136683L, 136683L, 136683L,
136683L, 136683L, 137268L, 137268L, 137268L, 137268L, 137268L,
137268L, 137268L, 137268L, 137268L, 137268L, 137268L, 137285L,
138087L, 138087L, 138087L, 138087L, 138087L, 138087L, 138087L,
138087L, 138087L, 138970L, 138970L, 138970L, 138970L, 138970L,
138970L, 138970L, 138970L, 138970L, 138970L, 138970L, 138970L,
132084L, 132084L, 141281L, 141281L, 141281L, 141281L, 137391L,
137391L, 137391L, 137391L, 137391L, 137391L, 137391L, 137391L,
138285L, 138285L, 138285L, 138285L, 138285L, 138285L, 138285L,
138285L, 138285L, 138285L, 138285L, 133381L, 133381L, 133381L,
133381L, 133381L, 133381L, 133381L, 139269L, 139265L, 139265L,
139265L, 139265L, 139265L, 139265L, 136803L, 136803L, 136803L,
136803L, 136803L, 136803L, 136803L, 136803L, 136803L, 136803L,
136803L, 137032L, 137032L, 137032L, 137032L, 137032L, 137032L,
137032L, 137234L, 137234L, 137234L, 137234L, 137234L, 137234L,
137234L, 137234L, 137234L, 137004L, 137004L, 137004L, 137004L,
137004L, 137004L, 137004L, 137004L, 137004L, 138205L, 138205L,
138205L, 139070L, 139070L, 139070L, 139070L, 139070L, 139070L,
139070L, 139070L, 139070L, 139070L, 139351L, 139351L, 139351L,
139351L, 139351L, 139351L, 139351L, 139351L, 139351L, 139351L,
140813L, 140813L, 140813L, 140813L, 140813L, 140813L, 140813L,
139479L, 139479L, 139479L, 139479L, 139479L, 139479L, 139479L,
139479L, 140667L, 140667L, 140667L, 140667L, 140667L, 140667L,
140667L, 140667L, 133291L, 133291L, 133291L, 133291L, 139465L,
139465L, 139465L, 139465L, 139465L, 139465L, 139465L, 139465L,
139465L, 141174L, 141174L, 141174L, 141174L, 141174L, 141174L,
141174L, 141174L, 141174L, 141174L, 141174L, 141174L, 141174L,
141174L, 141174L, 141174L, 141174L, 139325L, 139325L, 139325L,
139325L, 139325L, 139325L, 139325L, 139325L, 139325L, 139325L,
139325L, 139325L, 139325L, 139325L, 139325L, 138061L, 138061L,
138061L, 138061L, 138061L, 138061L, 138061L, 138061L, 138061L,
138061L, 138061L, 138061L, 138061L, 139143L, 139143L, 139143L,
139143L, 139143L, 139143L, 139143L, 139143L, 139143L, 139143L,
139143L, 139143L, 138671L, 138671L, 138671L, 138671L, 138671L,
138671L, 138671L, 138671L, 138671L, 138671L, 138671L, 138671L,
131970L, 131970L, 131970L, 131970L, 131970L, 131970L, 131970L,
131970L, 136802L, 136802L, 136802L, 136802L, 136802L, 136405L,
136405L, 136405L, 136405L, 136405L, 136405L, 136405L, 139156L,
139156L, 139156L, 139156L), OtherLangDescription = c("frying Potato",
"Flame Grape", "Zebdaya Mango", "Green pepper", "Molokhia", "White Eggplant ",
"Golden Onion", "Zucchini", "Dill", "Parsley", "Coriander", "Local Eggplant",
"Local Lemon", "Local Pear", "Flame Grape", "Superior Grape",
"Capsicum", "Green pepper", "Cucumber", "White Eggplant ", "Carrot",
"Tomato", "Zucchini", "Parsley", "Local Celery ", "frying Potato",
"Flame Grape", "Superior Grape", "Momtaza Owais Mango", "Barshomi Figs",
"Green pepper", "Cucumber", "Tomato", "Red Onion", "Parsley",
"Flame Grape", "Momtaza Owais Mango", "Barshomi Figs", "Hot Pepper",
"Green pepper", "Cucumber", "Red Onion", "Zucchini", "Parsley",
"Momtaza Owais Mango", "Barshomi Figs", "Local Pear", "Superior Grape",
"Momtaza Owais Mango", "Barshomi Figs", "Cucumber", "White Eggplant ",
"Tomato", "Classic Eggplant", "Local Pear", "Tomato", "Dill",
"Parsley", "Coriander", "Classic Eggplant", "frying Potato",
"Flame Grape", "Cucumber", "Molokhia", "Cooking Potato", "Tomato",
"Cantaloupe", " Green Beans", "Baladi Cabbage", "Local Lemon",
"Classic Eggplant", "frying Potato", "Banati Grape", "Chili Pepper",
"Green pepper", "Tomato", "Local Lemon", "Classic Eggplant",
"Banati Grape", "Chili Pepper", "Green pepper", "Tomato", "Classic Eggplant",
"frying Potato", "Local Pear", "Chili Pepper", "Green pepper",
"White Eggplant ", "Black Eggplant", "Tomato", "Zaghlol Dates",
"Local Lemon", "Baladi Garlic", "Zucchini", "Dill", "Parsley",
"Red Globe Grape", "frying Potato", "Local Pear", "Flame Grape",
"Fons Mango", "Barshomi Figs", "Cucumber", "Carrot", "Tomato",
"Red Onion", "Dill", "Parsley", "Coriander", "Owais Mango", "Melon",
"Sadeeka Mango", "Barshomi Figs", "Avocado", "Strawberry", "Sugary Peach",
"Local Cucumber", "Imported Peach", "Guava", "Watermelon ( per KG)",
"Syrian plum", "Watermelon ( per KG)", "Hot Pepper", "Watermelon ( per KG)",
"Hot Pepper", "Cucumber", "White Eggplant ", "Grape Leaves",
"Carrot", "Tomato", "Red Onion", "Sugary Peach", "Local Lemon",
"Mushroom (200G) old", "Red Radish old", "Orange For Juice",
"Watermelon ( per KG)", "Melon", "Flame Grape", "Chili Pepper",
"Capsicum", "Carrot", "Tomato", "Broccoli", "Sugary Peach", "Local Cucumber",
"Classic Eggplant", "frying Potato", "Capsicum", "Green pepper",
"Golden Onion", "Tomato", "frying Potato", "Flame Grape", "Superior Grape",
"Sadeeka Mango", "Capsicum", "Green pepper", "Black Eggplant",
"Cooking Potato", "Carrot", "Tomato", "Local Cucumber", "Local Hot Pepper",
"Capsicum", "Green pepper", "Grape Leaves", "Cooking Potato",
"Tomato", "Cantaloupe", "Local Cucumber", "Japanese Plum", "Dill",
"White Cabbage", "Coriander", "Arugula", "Local Apple", "Local Lemon",
"Classic Eggplant", "Morket Tangerine", "Cooking Potato", "Red Onion",
"Tamr hendi", "Deluxe Dried Dates", "Sokkary Mango", "Nems Watermelon (KG)",
"Sugary Peach", "Red Globe Grape", "Owais Mango", "Lebanese Apple",
"Orange For Juice", "Watermelon ( per KG)", "Golden Apple", "Tomato",
"Sweet Potato", "Sokkary Mango", "Gala Apple", "Tomato", "Okra",
"Mint", "Red Globe Grape", "Watermelon ( per KG)", "Flame Grape",
"Hot Pepper", "Capsicum", "Tomato", "Local Cucumber", "Parsley",
"Local Apple", "Local Lemon", "Flame Grape", "Superior Grape",
"Parsley", "Local Apple", "Watermelon ( per KG)", "Cooking Potato",
"Taro", "Cantaloupe", "Local Cucumber", "Dried Dates", "Local Apple",
"Watermelon ( per KG)", "Golden Onion", "Sugary Peach", "Arugula old",
"frying Potato", "Parsle old", "Coriander old", "Dill old", "White Cabbage Old",
"Tomato", "Local Cucumber", "Orange For Juice", "Watermelon ( per KG)",
"Red Onion", "Watermelon ( per KG)", "Nectarine Peach", "Granny Apple",
"Apricot", "Carrot", "Tomato", "Red Onion", "Zucchini", "Parsle old",
"Coriander old", "Dill old", "Flame Grape", "Capsicum", "Carrot",
"Tomato", "Local Cucumber", "Zucchini", "Orange For Juice", "Golden Apple",
"Golden Onion", "Cooking Potato", "Carrot", "Tomato", "Taro",
"Local Lemon", "Cauliflower", "Classic Eggplant", "frying Potato",
"Autumn Royal Grape", "Capsicum", "Green pepper", "Cucumber",
"Tomato", "Red Globe Grape", "Local Lemon", "Classic Eggplant",
"frying Potato", "Autumn Royal Grape", "Capsicum", "Green pepper",
"Cucumber", "Tomato", "Red Globe Grape", "Watermelon ( per KG)",
"Local Lemon", "Classic Eggplant", "frying Potato", "Flame Grape",
"Tomato", "Red Onion", "Local Cucumber", "Superior Grape", "Sokkary Mango",
"Sadeeka Mango", "Barshomi Figs", "Hot Pepper", "Chili Pepper",
"Black Eggplant", "Red Globe Grape", "Syrian plum", "Local Lemon",
"Classic Eggplant", "frying Potato", "Pumpkin", "Banati Grape",
"Sokkary Mango", "Green pepper", "Cucumber", "Molokhia", "Golden Onion",
"Carrot", "Tomato", "Red Onion", "Red Garlic", "Mint", "Arugula",
"Parsle old", "Coriander old", "Dill old", "White Cabbage Old",
"Capsicum", "Green pepper", "White Eggplant ", "Carrot", "Tomato",
"Sugary Peach", "Mushroom (200G) old", "Arugula old", "Mint old",
"Dessert Peach", "frying Potato", "Parsle old", "Green pepper",
"Cucumber", "Tomato", "Red Onion", "Sugary Peach", "Classic Eggplant",
"Sweet Potato", "frying Potato", "Sweet Apple", "Local Pear",
"Flame Grape", "Fons Mango", "Naoumi Mango", "Barshomi Figs",
"Green pepper", "Cucumber", "Molokhia", "White Eggplant ", "Golden Apple",
"Carrot", "Tomato", "Cantaloupe", " Green Beans", "Red Globe Grape",
"Syrian plum", "Crimson Grape", "Local Lemon", "frying Potato",
"Flame Grape", "kiwi", "Capsicum", "Cherry Tomatoes", "Beet",
"Cucumber", "Granny Apple", "Gala Apple", "Golden Onion", "Carrot",
"Tomato", "Red Onion", "Sugary Peach", "Zucchini", "Dill", "Parsley",
"Coriander", "Arugula", "Local Celery ", "Watermelon ( per KG)",
"frying Potato", "Chili Pepper", "Beet", "Cucumber", "Apricot",
"Dill", "Parsley", "Imported Leek", "Coriander", "Red Radish",
"Arugula", "Local Celery ", "Local Hot Pepper", "Cauliflower",
"Watermelon ( per KG)", "Flame Grape", "Fons Mango", "Naoumi Mango",
"Cantaloupe", "Red Globe Grape", "Syrian Green Apple", "Mushroom (200G) old",
"Arugula old", "Parsle old", "Cucumber", "Golden Onion", "Tomato",
"Cantaloupe", "Zucchini", "Local Lemon", "Mushroom (200G) old",
"Red Radish old", "Parsle old", "Avocado", "African Crimson Grape",
"Green pepper", "Cucumber", "Zucchini", "Navel Orange", "Morket Tangerine",
"Pineapple ( per KG)", "Watermelon ( per KG)", "kiwi", "African Crimson Grape",
"African Pear", "Nectarine Peach", "Golden Apple", "Gala Apple",
"Local Banana", "Orange For Juice", "Orange For Juice", "African Crimson Grape",
"Strawberry", "coconut", "Dried Figs 400G Old", "Amar Eldain 400G Old",
"ِArugula Rokla  Old", "Imported Banana", "Apricot", "Classic Eggplant",
"Avocado", "Strawberry", "Green pepper", "Nectarine Peach", "Golden Apple",
"Granny Apple", "Gala Apple", "Tomato", "Cantaloupe", "Florida Peach",
"Imported Banana", "Morket Tangerine", "Watermelon ( per KG)",
"Superior Grape", "kiwi", "Strawberry", "Golden Apple", "Granny Apple",
"Gala Apple", "Cantaloupe", "Sugary Peach", "Imported Banana",
"Apricot", "Hollywood Plum", "Japanese Plum", "Orange For Juice",
"Dessert Peach", "Morket Tangerine", "Watermelon ( per KG)",
"frying Potato", "Melon", "Flame Grape", "Superior Grape", "Capsicum",
"Cucumber", "White Eggplant ", "Gala Apple", "Golden Onion",
"Cooking Potato", "Carrot", "Tomato", "Broccoli", "Sugary Peach",
"Imported Banana", "Apricot", "Hollywood Plum", "Baladi Garlic",
"Japanese Plum", "Zucchini", "Classic Eggplant", "Orange For Juice",
"Dessert Peach", "Morket Tangerine", "Watermelon ( per KG)",
"Melon", "Cucumber", "Golden Onion", "Cooking Potato", "Tomato",
"Broccoli", "Sugary Peach", "Apricot", "Hollywood Plum", "Baladi Garlic",
"Japanese Plum", "Zucchini", "Imported Cherry", "Flame Grape",
"Momtaza Owais Mango", "Zebdaya Mango", "Imported Banana", "Local Lemon",
"Mushroom (200G) old", "Orange For Juice", "frying Potato", "Red Cabbage old",
"Parsle old", "Dill old", "Tomato", "Golden Raisin", "Zucchini",
"Mushroom (200G) old", "Arugula old", "Italian Basil Old", "Black Eggplant",
"Golden Onion", "coconut", "Golden Raisin", "Raisin", "Green Latoga Lettuce  Old",
"ِArugula Rokla  Old", "Classic Eggplant", "Superior Grape",
"Capsicum", "Green pepper", "Cucumber", "Carrot", "Tomato", "Sugary Peach",
"Dill", "Parsley", "Arugula", "Local Lemon", "Classic Eggplant",
"Watermelon ( per KG)", "Hot Pepper", "Avocado", "Capsicum",
"Green pepper", "Cucumber", "Golden Onion", "Cooking Potato",
"Carrot", "Tomato", "Zucchini", "Mushroom (200G)", "Red Globe Grape",
"Local Lemon", "Classic Eggplant", "Sweet Potato", "frying Potato",
"Autumn Royal Grape", "Capsicum", "Cucumber", "Golden Onion",
"Carrot", "Tomato", "Zucchini", "Mushroom (200G)", "White Cabbage",
"Red Spanish plum", "Cucumber", "Cooking Potato", "Tomato", "Red Onion",
"Crimson Grape", "Local Lemon", "Classic Eggplant", "Tomato",
"Red Onion", "Sweet Potato", "frying Potato", "Barbary Figs",
"Green pepper", "Cucumber", "Tomato", "Red Globe Grape", "Owais Mango",
"Morket Tangerine", "Watermelon ( per KG)", "Cherry Tomatoes",
"Sugary Peach", "Dessert Peach", "frying Potato", "Superior Grape",
"Tomato", "Red Onion", "Cantaloupe", "Sugary Peach", "Imported Banana",
"Hollywood Plum", "Japanese Plum", "Local Lemon", "Mushroom (200G) old",
"Watermelon ( per KG)", "Parsle old", "Dill old", "Hot Pepper",
"Avocado", "Green pepper", "Cucumber", "Golden Apple", "Carrot",
"Tomato", "Cantaloupe", "Tamr hendi", "sobya 1/4KG", "Hibiscus",
"Imported Banana", "Apricot", "Watermelon ( per KG)", "frying Potato",
"Ismalilia Fass Mango", "Cucumber", "Golden Onion", "Tomato",
"Cantaloupe", "Arugula", "Local Lemon", "frying Potato", "Superior Grape",
"Cucumber", "Golden Onion", "Carrot", "Tomato", "Red Onion",
"Arugula", "Yasmina Mango", "Local Lemon", "Mushroom (200G) old",
"Arugula old", "Red Cabbage old", "Capsicum", "Green pepper",
"Grape Leaves", "Orange For Juice", "Morket Tangerine", "frying Potato",
"Superior Grape", "Golden Apple", "Tomato", "Deluxe Dried Dates",
"Japanese Plum", "Morket Tangerine", "Watermelon ( per KG)",
"Sugary Peach", "Classic Eggplant", "Melon", "White Cabbage Old",
"Flame Grape", "Superior Grape", "Golden Apple", "Tomato", "Red Onion",
"Apricot", "Zucchini", "Iceberg Lettuce", "Flame Grape", "Sokkary Mango",
"Zebdaya Mango", "Yasmina Mango", "Sokkary Mango", "Zebdaya Mango",
"Yasmina Mango", "Watermelon ( per KG)", "Local Pear", "Flame Grape",
"Sokkary Mango", "Banati Grape", "Fons Mango", "Zebdaya Mango",
"Crimson Grape", "Imported Peach", "Flame Grape", "Zebdaya Mango",
"Naoumi Mango", "Gala Apple", "Cantaloupe", "Cooking Potato",
"Local Lemon", "Barhi Dates", "Fons Mango", "Green pepper", "Beet",
"Cucumber", "Golden Onion", "Cooking Potato", "Tomato", "Zucchini",
"Mint", "Baladi Cabbage", "Kathaa", "Classic Eggplant", "Mint old",
"Green pepper", "Cucumber", "Golden Onion", "Cooking Potato",
"Carrot", "Local Lemon", "Imported Apricot", "Hot Pepper", "Tomato",
"Red Onion", "Cantaloupe", "package of Celery", "Local Cucumber",
"Japanese Plum", "Local Lemon", "Classic Eggplant", "Melon",
"Superior Grape", "Capsicum", "Cucumber", "Golden Onion", "Tomato",
"Iceberg Lettuce", "Local Lemon", "Classic Eggplant", "Imported Cherry",
"Flame Grape", "Chili Pepper", "Green pepper", "Cucumber", "Molokhia",
"Black Eggplant", "Carrot", "Tomato", "Zucchini", "Mint", "Dill",
"Parsley", "Coriander", "Arugula", "Local Eggplant", "Orange For Juice",
"Imported Cherry", "Flame Grape", "Barshomi Figs", "Cucumber",
"Golden Onion", "Tomato", "Dill", "Parsley", "Coriander", "Arugula",
"Orange For Juice", "Local Lemon", "Flame Grape", "Momtaza Owais Mango",
"Barshomi Figs", "Chili Pepper", "Cucumber", "Golden Onion",
"Tomato", "Arugula", "Classic Eggplant", "Fons Mango", "Beet",
"Cucumber", "Cooking Potato", "Tomato", "Dill", "Parsley", "Coriander",
"Red Globe Grape", "Baladi Cabbage", "Kathaa", "coconut", "Deluxe Dried Dates",
"Barhi Dates", "kiwi", "Golden Apple", "Imported Banana", "Classic Eggplant",
"frying Potato", "Flame Grape", "Cucumber", "Black Eggplant",
"Golden Onion", "Tomato", "Red Globe Grape", "frying Potato",
"Flame Grape", "Sokkary Mango", "Cucumber", "Cooking Potato",
"Tomato", "Red Onion", "Okra", "Zucchini", "Parsley", "Coriander",
"Mushroom (200G) old", "Watermelon ( per KG)", "Flame Grape",
"Cucumber", "Tomato", "Apricot", "Deluxe Dried Dates", "Crimson Grape",
"Pomegranate", "Local Pear", "Cucumber", "Carrot", "Arugula",
"Owais Mango", "Watermelon ( per KG)", "frying Potato", "Golden Onion",
"Cooking Potato", "Tomato", "Local Cucumber", "Zucchini", "Mint",
"Parsley", "Arugula", "Local Apple", "Local Lemon", "Zebdaya Mango",
"Sadeeka Mango", "Capsicum", "Green pepper", "Sugary Peach",
"Local Apple", "Local Lemon", "Flame Grape", "Momtaza Owais Mango",
"Sokkary Mango", "Capsicum", "Cucumber", "Golden Onion", "Carrot",
"Local Apple", "Classic Eggplant", "frying Potato", "Flame Grape",
"Superior Grape", "Sadeeka Mango", "Green pepper", "Cucumber",
"Tomato", "Local Apple", "Watermelon ( per KG)", "Local Pear",
"Sokkary Mango", "Sweet Potato", "Watermelon ( per KG)", "frying Potato",
"Green pepper", "Cucumber", "Golden Onion", "Tomato", "Red Onion",
"Baladi Garlic", "Arugula", "Watermelon ( per KG)", "frying Potato",
"Barbary Figs", "Barshomi Figs", "Beet", "Tomato", "Mint", "Arugula",
"Owais Mango", "Lebanese Apple", "Zebdaya Mango", "kiwi", "Sugary Peach",
"Zucchini", "Mushroom (200G)", "Iceberg Lettuce", "Crimson Grape",
"Local Lemon", "Sweet Potato", "Watermelon ( per KG)", "Cucumber",
"Golden Onion", "Zucchini", "Iceberg Lettuce", "Lebanese Apple",
"Barshomi Figs", "Hot Pepper", "Cucumber", "Carrot", "Sugary Peach",
" Green Beans", "Mushroom (200G)", "Local Celery ", "frying Potato",
"Superior Grape", "Sugary Peach", "Local Cucumber", "Local Pear",
"Golden Apple", "Tomato", "Imported Banana", "Dill", "Parsley",
"Arugula", "Red Globe Grape", "Owais Mango", "Imported Peach",
"Kaka", "Local Pear", "Banati Grape", "Barshomi Figs", "Capsicum",
"Cucumber", "Tomato", "Cantaloupe", "Imported Banana", "Dill",
"Parsley", "Owais Mango", "Kathaa", "Crimson Grape", "Spanish Plum",
"Red Spanish plum", "Imported Peach", "Imported Apricot", "Local Pear",
"Banati Grape", "Barbary Figs", "Capsicum", "Green pepper", "Cucumber",
"Carrot", "Mint", "Parsley", "Arugula", "Local Celery ", "Syrian plum",
"Crimson Grape", "Melon", "Local Pear", "Flame Grape", "Superior Grape",
"Sadeeka Mango", "Barshomi Figs", "kiwi", "Capsicum", "Cucumber",
"Golden Apple", "Red Onion", "Imported Banana", "Syrian plum",
"Ismalilia Fass Mango", "Zebdaya Mango", "Barshomi Figs", "Tomato",
"Red Onion", "Cantaloupe", "Imported Banana", "Dill", "Coriander",
"Arugula", "Owais Mango", "Crimson Grape", "Melon", "Capsicum",
"Cucumber", "Granny Apple", "Tomato", "Red Onion", "Imported Banana",
"Dill", "Parsley", "Coriander", "Arugula", "Owais Mango", "Orange For Juice",
"Morket Tangerine", "Capsicum", "Tomato", "Cantaloupe", "Florida Peach",
"Imported Banana", "Dried Dates", "Watermelon ( per KG)", "Melon",
"Tomato", "Sugary Peach", "Local Cucumber", "Watermelon ( per KG)",
"Melon", "Superior Grape", "Beet", "Cucumber", "Carrot", "Sugary Peach",
"Local Pear", "Barshomi Figs", "Golden Apple", "Cantaloupe")), .Names = c("WHWorkOrderHeaderId",
"OtherLangDescription"), class = "data.frame", row.names = c(NA,
-1000L))
prodList <- unique(New$OtherLangDescription)
prodListId <- lapply(prodList, function(x) subset(New, OtherLangDescription == x)$WHWorkOrderHeaderId)
prodListProduct <- lapply(prodListId, function(x) subset(New, WHWorkOrderHeaderId %in% x)$OtherLangDescription)
prodListTable <- mapply(function(Product, ID) table(Product)/length(ID),
                        prodListProduct, prodListId)
colnames(prodListTable) <- prodList

Body:
First and foremost, on the theoretical side, the case you describe (A & B never in the panel at the same time) won't give you a null correlation but a negative correlation. Indeed, whenever A = 1, B = 0 and whenever B = 1, A = 0, so an anti-correlation appears. The correlation won't necessarily equal -1 though, because you will obviously encounter cases where A = B = 0 (unless customers always buy A and B which is unrealistic).

On the other hand, you may encounter nearly null correlation in the case A and B are seldom bought (which means numerous occurrences of A = B = 0).

As for how to code it, you can use model.matrix to transform your data into dummy variables and aggregate to gather panel contents by WOrderId. Here is an example using your structure.

mydf <- data.frame(WOrderId = c(c(1:8),c(1:8)),
                   OtherLangDescription = c(rep("Water",4),rep("Milk",4),
                     rep("Apple",2), rep("Beef",2), rep("Candy",2), rep("Apple",2)))
mydf$OtherLangDescription <- as.factor(mydf$OtherLangDescription)
dummydf <- model.matrix(WOrderId ~ OtherLangDescription, mydf,
                             contrasts.arg = list(OtherLangDescription = contrasts(mydf$OtherLangDescription,
                                                      contrasts = F)))
fulldf <- data.frame(mydf$WOrderId, dummydf[,2:ncol(dummydf)])
agregdf <- aggregate(. ~ mydf.WOrderId, fulldf, sum)
cor(agregdf[,2:ncol(agregdf)])

Which gives the following output.

                          OtherLangDescriptionApple OtherLangDescriptionBeef OtherLangDescriptionCandy
OtherLangDescriptionApple                 1.0000000               -0.5773503                -0.5773503
OtherLangDescriptionBeef                 -0.5773503                1.0000000                -0.3333333
OtherLangDescriptionCandy                -0.5773503               -0.3333333                 1.0000000
OtherLangDescriptionMilk                  0.0000000               -0.5773503                 0.5773503
OtherLangDescriptionWater                 0.0000000                0.5773503                -0.5773503
                          OtherLangDescriptionMilk OtherLangDescriptionWater
OtherLangDescriptionApple                0.0000000                 0.0000000
OtherLangDescriptionBeef                -0.5773503                 0.5773503
OtherLangDescriptionCandy                0.5773503                -0.5773503
OtherLangDescriptionMilk                 1.0000000                -1.0000000
OtherLangDescriptionWater               -1.0000000                 1.0000000

As you can see, since apples are never in the same panel as beef or candies, the correlation is negative. Beef has "great" correlation with water because water is always present whenever you get beef.

Note that apples and milk have a null correlation (same for apple and water), because half of the time apples are bought, water is also bought. Hence a null correlation does not imply that products are anti-correlated (they are just uncorrelated).

EDIT as per comments, you are not calculating correlation, but conditional probabilities per product.

Here is a way to achieve this calculation.

prodList <- unique(mydf$OtherLangDescription) # get distinct list of products
prodListId <- lapply(prodList, function(x) subset(mydf, OtherLangDescription == x)$WOrderId) # get list of orders in which each product appears
prodListProduct <- lapply(prodListId, function(x) subset(mydf, WOrderId %in% x)$OtherLangDescription) # get products appearing in those orders
prodListTable <- mapply(function(Product, ID) table(Product)/length(ID),
                         prodListProduct, prodListId) # divide occurrences of products by number of orders to get conditional probabilities
colnames(prodListTable) <- prodList


来源: stackexchange

问:
Xpath is not working with XML::Twig::XPath::Elt
I have following XML.

```<code><Path>
  <To>
    <My>
      <Node key="11">
        <ChildA>1A</ChildA>
        <ChildB key="Key1">1B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
      <Node key="22">
        <ChildA>2A</ChildA>
        <ChildB key="Key2">2B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
    </My>
  </To>
</Path>
</code>```

And I am trying to parse this xml using XML::Twig::XPath.
Following is my code to parse it and extract element from it using XPath syntax.

```<code>use 5.010;
use strict;
use warnings FATAL => 'all';
use XML::Twig::XPath;  #Issue with this shit as this thing was up to data but XML::XPath was not installed. So I did cpanm XML::XPath
use XML::Twig;
use Data::Dumper;
my @xml;

$xml[0] = q|<Path>
  <To>
    <My>
      <Node key="11">
        <ChildA>1A</ChildA>
        <ChildB key="Key1">1B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
      <Node key="22">
        <ChildA>2A</ChildA>
        <ChildB key="Key2">2B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
    </My>
  </To>
</Path>|;

my $twig = XML::Twig::XPath->new(pretty_print => 'indented')->parse($xml[0]);

#Finding the whole Node, using xpath. This shit also works if you have Twig, not XPath.
my @constraint = $twig->findnodes('/Path/To/My/Node[@key="22"]');
say $constraint[0]->sprint;
say ref($constraint[0]);

my $child_key = $constraint[0]->find('//ChildB/@key');
say $child_key;
</code>```

$constraint[0] rightfully prints the XML Node.

And I expect $child_key to be Key2 but it turns out to be Key1Key2

What I could be possibly doing wrong? If I do full XPath search it is giving me corrct output.

答:
The //ChildB/@key xpath expression means that it starts at the root element and looks in any element for an element ChildB and the attribute @key.

It's confusing that your twig $constraint[0] is not completely taken out of the tree. It's like a view on some part of the full document tree, so the // actually looks in the full tree. It starts at root of the document, not at the <Node key="22"> element.

You need to tell your find to start the current element by using the ..

```<code>#                                     V
my $child_key = $constraint[0]->find('.//ChildB/@key');
</code>```

Now your output is only

```<code>Key2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following XML.

<Path>
  <To>
    <My>
      <Node key="11">
        <ChildA>1A</ChildA>
        <ChildB key="Key1">1B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
      <Node key="22">
        <ChildA>2A</ChildA>
        <ChildB key="Key2">2B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
    </My>
  </To>
</Path>

And I am trying to parse this xml using XML::Twig::XPath.
Following is my code to parse it and extract element from it using XPath syntax.

use 5.010;
use strict;
use warnings FATAL => 'all';
use XML::Twig::XPath;  #Issue with this shit as this thing was up to data but XML::XPath was not installed. So I did cpanm XML::XPath
use XML::Twig;
use Data::Dumper;
my @xml;

$xml[0] = q|<Path>
  <To>
    <My>
      <Node key="11">
        <ChildA>1A</ChildA>
        <ChildB key="Key1">1B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
      <Node key="22">
        <ChildA>2A</ChildA>
        <ChildB key="Key2">2B</ChildB>
        <ChildC>
            <ChildD>ValD</ChildD>
        </ChildC>
      </Node>
    </My>
  </To>
</Path>|;

my $twig = XML::Twig::XPath->new(pretty_print => 'indented')->parse($xml[0]);

#Finding the whole Node, using xpath. This shit also works if you have Twig, not XPath.
my @constraint = $twig->findnodes('/Path/To/My/Node[@key="22"]');
say $constraint[0]->sprint;
say ref($constraint[0]);

my $child_key = $constraint[0]->find('//ChildB/@key');
say $child_key;

$constraint[0] rightfully prints the XML Node.

And I expect $child_key to be Key2 but it turns out to be Key1Key2

What I could be possibly doing wrong? If I do full XPath search it is giving me corrct output.

Body:
The //ChildB/@key xpath expression means that it starts at the root element and looks in any element for an element ChildB and the attribute @key.

It's confusing that your twig $constraint[0] is not completely taken out of the tree. It's like a view on some part of the full document tree, so the // actually looks in the full tree. It starts at root of the document, not at the <Node key="22"> element.

You need to tell your find to start the current element by using the ..

#                                     V
my $child_key = $constraint[0]->find('.//ChildB/@key');

Now your output is only

Key2


问:
How to remove string with specific value from a string using JavaScript?
Suppose my string is like:

```<code>var str = "USA;UK;AUS;NZ"
</code>```

Now from some a source I am getting one value like:

```<code>country.data = "AUS"
</code>```

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

```<code>var someStr= str.substring(0, str.indexOf(country.data))
</code>```

In this case I got the same result.

答:
Here is a good old split/join method:

var str = "USA;UK;AUS;NZ;AUS";
var str2 = "AUS";
var str3 = str2 + ";";
console.log(str.split(str3).join("").split(str2).join(""));```

Body:
Suppose my string is like:

var str = "USA;UK;AUS;NZ"

Now from some a source I am getting one value like:

country.data = "AUS"

Now in this case I want to remove "AUS" from my string.

Can anyone please suggest how to achieve this.

Here is what I have tried:

var someStr= str.substring(0, str.indexOf(country.data))

In this case I got the same result.


问:
Scala expression to replace a file extension in a string
Here is a version I wrote using split:

```<code>fileName.split('.').init ++ Seq("js") mkString "."
</code>```

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

答:
Will a simple regex replacement do the trick?

Like:

```<code>scala> "package.file.java".replaceAll("(\\.[^\\.]*$)", ".rb")
scala> "package.file.rb"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is a version I wrote using split:

fileName.split('.').init ++ Seq("js") mkString "."

This transforms e.g. foo.bar.coffee into foo.bar.js.

What I like:

it works

it doesn't rely on things like indexOf()

it feels functional ;)

What I don't like:

it's not as short as I would hope

it might confuse some readers

How can I write an even simpler / straightforward version?

UPDATE: Great answers below! In short:

seems like my original approach above was not bad although it doesn't cover some corner cases, but that's fixable with a longer expression if you need to cover those

another, slightly shorter approach uses regexps, which will be more or less readable depending on your regexp background

a slightly shorter syntax for the original approach (corner cases not covered) reads:

fileName.split('.').init :+ "js" mkString "."

Body:
Will a simple regex replacement do the trick?

Like:

scala> "package.file.java".replaceAll("(\\.[^\\.]*$)", ".rb")
scala> "package.file.rb"


问:
Remove table rows based on condition in matlab
a=[1; 2 ; 3]; b=[ 4; 5; 6 ]; T=table(a,b).
I want to remove rows of table for which the value of b is less than or equal to 5 (b<=5).

答:
You can use logical indexing:

```<code>a=[1; 2 ; 3];
b=[ 4; 5; 6 ];
T=table(a,b);

rowidx = (T.b <= 5);
T = T(~rowidx, :);
</code>```

Which returns:

```<code>T =

  1×2 table

    a    b
    _    _

    3    6
</code>```

Body:
You can use logical indexing:

a=[1; 2 ; 3];
b=[ 4; 5; 6 ];
T=table(a,b);

rowidx = (T.b <= 5);
T = T(~rowidx, :);

Which returns:

T =

  1×2 table

    a    b
    _    _

    3    6


问:
WordPress only showing home page after migration
I'm currently working on a WordPress website. I have taken a database dump from my site and imported to localhost. When I open the localhost, only home page is working, all the other pages are showing error:

The requested URL was not found on this server.

How can I fix this issue?

答:
You need change all permalinks in database. For example use wp-cli.
Open cmd (windows) in your WordPress folder, and execute this command

```<code>wp search-replace "http://old-url.website" "http://new-url.website" --all-tables
</code>```

or use this tool link. This tool special for wordpress.

Body:
You need change all permalinks in database. For example use wp-cli.
Open cmd (windows) in your WordPress folder, and execute this command

wp search-replace "http://old-url.website" "http://new-url.website" --all-tables

or use this tool link. This tool special for wordpress.


问:
How can I get a `Single<T>` from an infinite sequence?

Problem

Given an Observable<NaturalNumber> that represent the sequence off all natural numbers.

Example 1 (addressed in this answer, check next example)

How can I get a Single<String> that contains the sum expression and result of all the numbers between a range?
Ex: for a range from 10 to 13 -> "11 + 12 = 23"

So far this is what I have (and don't like):

```<code>let min = 10
let max = 15
//No special meaning, just to add an "error" case
let maxAllowed = 20

Single<String>.create(subscribe: { (complete) -> Disposable in
    return Observable.range(start: 0, count: Int.max)
        .filter { min < $0 && max > $0 }
        .scan([], accumulator: { (acc: [Int], number) in
            guard number < maxAllowed else {
                complete(.error(SomeError()))
                return []
            }
            return acc + [number]
        })
        .single { $0.count == (max - min - 1) }
        .map { range in
            let sum = range.reduce(0, +)
            return range.reduce("", { (acc, number) -> String in
                if number == (max - 1) {
                    return acc + " + \(number) = \(sum)"
                } else {
                    return acc + "\(acc != "" ? " + " : "")\(number)"
                }
        })}
        .subscribe(onNext: { complete(.success($0)) })
}).subscribe(onSuccess: { (s) in
    print("Success: \(s)") // "Success: 11 + 12 + 13 + 14 = 50"
}, onError: { (e) in
    print("Error")
}).disposed(by: d)
</code>```

Example 2

Given a struct Point3D that needs to be constructed from an array of size 3. How can I get a Single<Point3D> where the values in the input vector should be in a specified range?

```<code>let min = 10
let max = 15
//No special meaning, just to add an "error" case
let maxAllowed = 20

struct Point3D {
    let x: Int
    let y: Int
    let z: Int

    init(vector: [Int]) {
        x = vector[0]
        y = vector[1]
        z = vector[2]
    }
}

Single<Point3D>.create(subscribe: { (complete) -> Disposable in
    return Observable.range(start: 0, count: Int.max)
        .filter { min < $0 && max > $0 }
        .scan([], accumulator: { (acc: [Int], number) in
            guard number < maxAllowed else {
                complete(.error(SomeError()))
                return []
            }
            return acc + [number]
        })
        .single { $0.count == 3 }
        .map(Point3D.init(vector:))
        .subscribe(onNext: { complete(.success($0)) })
}).subscribe(onSuccess: { (s) in
    print("Success: \(s)") // "Success: Point3D #1(x: 11, y: 12, z: 13)"
}, onError: { (e) in
    print("Error")
}).disposed(by: d)
</code>```

Keep in mind:
This is an abstraction of a real problem I have that involves an infinite sequence of values coming from a bluetooth connection. So please try to avoid answers that change to problem instead of the solution unless you think it make sense given the above.

Objective

The patter I look to extract is: select some values from an infinite sequence and construct a new one with only those values. Once all the values are collected completes with .success(allValues)

What I want to improve over the examples is:

The need of the Single<T>.create() wrapper. It's there only for been able to complete with and error in some cases (the maxAlloed in the examples). Also I'm not sure if the asSingle() operator completes the returned Single after a value is returned (?).

The use of filter, scan and single to take values from the original sequence and to control when the finite sequence should complete. Think on the Example 2.

Thanks

答:
If I've understood the problem correctly (reduce a continuous portion of an infinite sequence to a Single), I would compose the following:

Skip elements until the start

Take elements until the end

Reduce

Convert to Single

In code for summing (but the same should be true for any infinite sequence, even of bluetooth events):

```<code>let sum = Observable.range(start: 0, count: Int.max)
    .skipWhile({ $0 <= min })
    .takeWhile({ $0 < max })
    .reduce(0, accumulator: +)
    .asSingle()

// Can't have any errors in the above code, but to demonstrate the general case
sum.subscribe(onSuccess: { print($0) },
              onError: { (e) in print("Error: \(e)") })
    .disposed(by: d)
</code>```

I wasn't quite clear what maxAllowed was doing in your original code (which may be the complexity), but if the point is to throw errors if a value is out of range, then you'd just throw in the reduce accumulator. Or you could add an identity map in the middle that just looked for invalid values and threw errors in those cases.

Body:
Problem

Given an Observable<NaturalNumber> that represent the sequence off all natural numbers.

Example 1 (addressed in this answer, check next example)

How can I get a Single<String> that contains the sum expression and result of all the numbers between a range?
Ex: for a range from 10 to 13 -> "11 + 12 = 23"

So far this is what I have (and don't like):

let min = 10
let max = 15
//No special meaning, just to add an "error" case
let maxAllowed = 20

Single<String>.create(subscribe: { (complete) -> Disposable in
    return Observable.range(start: 0, count: Int.max)
        .filter { min < $0 && max > $0 }
        .scan([], accumulator: { (acc: [Int], number) in
            guard number < maxAllowed else {
                complete(.error(SomeError()))
                return []
            }
            return acc + [number]
        })
        .single { $0.count == (max - min - 1) }
        .map { range in
            let sum = range.reduce(0, +)
            return range.reduce("", { (acc, number) -> String in
                if number == (max - 1) {
                    return acc + " + \(number) = \(sum)"
                } else {
                    return acc + "\(acc != "" ? " + " : "")\(number)"
                }
        })}
        .subscribe(onNext: { complete(.success($0)) })
}).subscribe(onSuccess: { (s) in
    print("Success: \(s)") // "Success: 11 + 12 + 13 + 14 = 50"
}, onError: { (e) in
    print("Error")
}).disposed(by: d)

Example 2

Given a struct Point3D that needs to be constructed from an array of size 3. How can I get a Single<Point3D> where the values in the input vector should be in a specified range?

let min = 10
let max = 15
//No special meaning, just to add an "error" case
let maxAllowed = 20

struct Point3D {
    let x: Int
    let y: Int
    let z: Int

    init(vector: [Int]) {
        x = vector[0]
        y = vector[1]
        z = vector[2]
    }
}

Single<Point3D>.create(subscribe: { (complete) -> Disposable in
    return Observable.range(start: 0, count: Int.max)
        .filter { min < $0 && max > $0 }
        .scan([], accumulator: { (acc: [Int], number) in
            guard number < maxAllowed else {
                complete(.error(SomeError()))
                return []
            }
            return acc + [number]
        })
        .single { $0.count == 3 }
        .map(Point3D.init(vector:))
        .subscribe(onNext: { complete(.success($0)) })
}).subscribe(onSuccess: { (s) in
    print("Success: \(s)") // "Success: Point3D #1(x: 11, y: 12, z: 13)"
}, onError: { (e) in
    print("Error")
}).disposed(by: d)

Keep in mind:
This is an abstraction of a real problem I have that involves an infinite sequence of values coming from a bluetooth connection. So please try to avoid answers that change to problem instead of the solution unless you think it make sense given the above.

Objective

The patter I look to extract is: select some values from an infinite sequence and construct a new one with only those values. Once all the values are collected completes with .success(allValues)

What I want to improve over the examples is:

The need of the Single<T>.create() wrapper. It's there only for been able to complete with and error in some cases (the maxAlloed in the examples). Also I'm not sure if the asSingle() operator completes the returned Single after a value is returned (?).

The use of filter, scan and single to take values from the original sequence and to control when the finite sequence should complete. Think on the Example 2.

Thanks

Body:
If I've understood the problem correctly (reduce a continuous portion of an infinite sequence to a Single), I would compose the following:

Skip elements until the start

Take elements until the end

Reduce

Convert to Single

In code for summing (but the same should be true for any infinite sequence, even of bluetooth events):

let sum = Observable.range(start: 0, count: Int.max)
    .skipWhile({ $0 <= min })
    .takeWhile({ $0 < max })
    .reduce(0, accumulator: +)
    .asSingle()

// Can't have any errors in the above code, but to demonstrate the general case
sum.subscribe(onSuccess: { print($0) },
              onError: { (e) in print("Error: \(e)") })
    .disposed(by: d)

I wasn't quite clear what maxAllowed was doing in your original code (which may be the complexity), but if the point is to throw errors if a value is out of range, then you'd just throw in the reduce accumulator. Or you could add an identity map in the middle that just looked for invalid values and threw errors in those cases.


问:
Need Tensorflow/Keras equivalent for scipy signal.fftconvolve
I want to use scipy.signal.fftconvolve in Tensorflow/Keras, is there any way to do that?

Right now I am using the following code :

```<code>window = np.tile(window, (1, 1, 1, 3))
tf.nn.conv2d(img1, window, strides=[1,1,1,1], padding='VALID')
</code>```

Are these lines equivalent to :

```<code>signal.fftconvolve(img1, window, mode='valid')
</code>```

答:
You want just a regular conv2d then...

If you want it somewhere in the model, add a Conv2D(...,name='myLayer') layer, and in the model use model.get_layer('myLayer').set_weights([filters,biases])

If you want it in a loss function, just create a loss function:

```<code>import keras.backend as K
def myLoss(y_true, y_pred):

    #where y_true is the true training data and y_pred is the model's output
    convResult = K.conv2d(y_pred, kernel = window, padding = 'same')
    anotherResult = K.depthwise_conv2d(y_pred, kernel = window, padding='same')
</code>```

The regular conv2D will assume each output channel in the filter will process and sum all input channels.

The depthwise convolution will keep input channels separate.

Beware of the window, though. I don't know the format in tensorflow or scipy, but the kernel in keras should have this shape: (height, width, numberOfInputChannels, numberOfOutputChannels)

I believe, if I understand it right, it should be window = np.reshape(_FSpecialGauss(size, sigma), (size, size, 1, 1)), considering that "size" is the size of the kernel and you have only 1 input and output channels.

I used padding='same' to get the result image the same size of the input. If you use padding='valid', you will lose the borders (although in your case, your filter seems to have size (1,1), which won't remove borders).

You can use any tensorflow function inside the loss function as well:

```<code>def customLoss(yTrue,yPred):
    tf.anyFunction(yTrue)
    tf.anyFunction(yPred)
</code>```

Using keras backend will let your code be portable to other backends later.

When compiling the model, give it your loss function:

```<code>model.compile(loss=myLoss, optimizer =....)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to use scipy.signal.fftconvolve in Tensorflow/Keras, is there any way to do that?

Right now I am using the following code :

window = np.tile(window, (1, 1, 1, 3))
tf.nn.conv2d(img1, window, strides=[1,1,1,1], padding='VALID')

Are these lines equivalent to :

signal.fftconvolve(img1, window, mode='valid')

Body:
You want just a regular conv2d then...

If you want it somewhere in the model, add a Conv2D(...,name='myLayer') layer, and in the model use model.get_layer('myLayer').set_weights([filters,biases])

If you want it in a loss function, just create a loss function:

import keras.backend as K
def myLoss(y_true, y_pred):

    #where y_true is the true training data and y_pred is the model's output
    convResult = K.conv2d(y_pred, kernel = window, padding = 'same')
    anotherResult = K.depthwise_conv2d(y_pred, kernel = window, padding='same')

The regular conv2D will assume each output channel in the filter will process and sum all input channels.

The depthwise convolution will keep input channels separate.

Beware of the window, though. I don't know the format in tensorflow or scipy, but the kernel in keras should have this shape: (height, width, numberOfInputChannels, numberOfOutputChannels)

I believe, if I understand it right, it should be window = np.reshape(_FSpecialGauss(size, sigma), (size, size, 1, 1)), considering that "size" is the size of the kernel and you have only 1 input and output channels.

I used padding='same' to get the result image the same size of the input. If you use padding='valid', you will lose the borders (although in your case, your filter seems to have size (1,1), which won't remove borders).

You can use any tensorflow function inside the loss function as well:

def customLoss(yTrue,yPred):
    tf.anyFunction(yTrue)
    tf.anyFunction(yPred)

Using keras backend will let your code be portable to other backends later.

When compiling the model, give it your loss function:

model.compile(loss=myLoss, optimizer =....)


答:
You could always use the replaceAll method on java.lang.String

```<code>scala> "foo.bar.coffee".replaceAll("\\.[^.]*$", ".js")
res11: java.lang.String = foo.bar.js
</code>```

It's shorter but less readable.

Title: Scala expression to replace a file extension in a string

Body:
You could always use the replaceAll method on java.lang.String

scala> "foo.bar.coffee".replaceAll("\\.[^.]*$", ".js")
res11: java.lang.String = foo.bar.js

It's shorter but less readable.


问:
Python: How combine returned value from 2 functions and appending them into a list using thread?
I am new to thread, I had encountered abnormal result while printing the value inside a list using thread to allow 2 functions to working at the same time and appending the result to a list. Below my code:

```<code>import threading
def func1():

  return "HTML"

def func2():

  return "IS FUN"

threadslist = []

thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)

x = thread1
y = thread2

x.start()
y.start()

threadslist.append(x)
threadslist.append(y)

print(threadslist)
</code>```

And here is the result for the list:

```<code>[<Thread(Thread-1, stopped 1076)>, <Thread(Thread-2, stopped 7948)>]
</code>```

Why it storing the Threads object instead of storing ['HTML', 'IS FUN'] ?

答:
In your threadlist you are saving the Thread variables, so that is what you're seeing in your output is their representation as strings.

You can't get the return value of a function running in a different thread like that.
To do what you can either:

Use the multithreading module:

:

```<code>from multiprocessing.pool import ThreadPool
def func1():
  return 'HTML'

def func2():
  return 'IS FUN'

pool = ThreadPool(processes=1)

return_values = []

return_values.append(pool.apply(func1, ())) # Using apply for synchronous call directly returns the function return value.
func2_result = pool.applyasync(func2) # Using applyasync for asynchronous call will require a later call.

return_values.append(func2_result.get())  # get return value from asynchronous call to func2.

print(return_values)
</code>```

Use mutable object, like a list, to save the return values:

:

```<code>return_values = []
def func1():
   return_values.append('HTML')

def func2():
   return_values.append('IS FUN')

# rest of your code here
print(return_values)
</code>```

And you'll get:

['HTML', 'IS FUN']

Body:
I am new to thread, I had encountered abnormal result while printing the value inside a list using thread to allow 2 functions to working at the same time and appending the result to a list. Below my code:

import threading
def func1():

  return "HTML"

def func2():

  return "IS FUN"

threadslist = []

thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)

x = thread1
y = thread2

x.start()
y.start()

threadslist.append(x)
threadslist.append(y)

print(threadslist)

And here is the result for the list:

[<Thread(Thread-1, stopped 1076)>, <Thread(Thread-2, stopped 7948)>]

Why it storing the Threads object instead of storing ['HTML', 'IS FUN'] ?

Body:
In your threadlist you are saving the Thread variables, so that is what you're seeing in your output is their representation as strings.

You can't get the return value of a function running in a different thread like that.
To do what you can either:

Use the multithreading module:

:

from multiprocessing.pool import ThreadPool
def func1():
  return 'HTML'

def func2():
  return 'IS FUN'

pool = ThreadPool(processes=1)

return_values = []

return_values.append(pool.apply(func1, ())) # Using apply for synchronous call directly returns the function return value.
func2_result = pool.applyasync(func2) # Using applyasync for asynchronous call will require a later call.

return_values.append(func2_result.get())  # get return value from asynchronous call to func2.

print(return_values)

Use mutable object, like a list, to save the return values:

:

return_values = []
def func1():
   return_values.append('HTML')

def func2():
   return_values.append('IS FUN')

# rest of your code here
print(return_values)

And you'll get:

['HTML', 'IS FUN']


问:
finding the average after a BubbleSort Method
I am an IT students, and i really need to finish writing this code, i am almost done with it, its sorting the numbers using Bubble sort but the things is, that we have to find the mean at the end, and i have no idea how to do this. can anybody help me?
my code looks like this, and till here it also works, I just need to add the rest to it:

```<code>public static void main(String[] args) {
    int num, i, j;
    double temp;
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of Numbers you want to sort:");
    num = input.nextInt();

    double array[] = new double[num];

    System.out.println("Enter " + num + " Number: ");

    for (i = 0; i < num; i++)
        array[i] = input.nextDouble();

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}
</code>```

}

Thanks :)

答:
```<code> int avg = 0;
 for (i = 0; i < num; i++) {
     avg = avg + array[i];
 }
 avg = avg / array.length();
</code>```

Body:
I am an IT students, and i really need to finish writing this code, i am almost done with it, its sorting the numbers using Bubble sort but the things is, that we have to find the mean at the end, and i have no idea how to do this. can anybody help me?
my code looks like this, and till here it also works, I just need to add the rest to it:

public static void main(String[] args) {
    int num, i, j;
    double temp;
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the amount of Numbers you want to sort:");
    num = input.nextInt();

    double array[] = new double[num];

    System.out.println("Enter " + num + " Number: ");

    for (i = 0; i < num; i++)
        array[i] = input.nextDouble();

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}

}

Thanks :)


问:
How to quickly execute a python file on Mac
I'm a beginner of Python and today I learned a new program that can search a place with Google Maps. This is the code:

```<code>import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/' + address)
</code>```

My file name is mapit.py and I really want to know that I can execute by only typing, for example,

```<code>mapit New York
</code>```

in the root command line instead of

```<code>Pycharm\......\pythoh3 mapit.py New York
</code>```

I've tried to execute mapit.py New York on Spotlight search, but it didn't work.

答:
To simply run a Python script, you can either invoke Python and pass the script

```<code>python mapit.py someargument "some argument with spaces"
</code>```

Or you can add the proper Python shebang to the top of the script and enable the executable bit

```<code>#!/usr/bin/env python
import webbrowser, sys, pyperclip
some_code_here ...
</code>```

If you then want to make this even simpler, you can set up an alias for show_me or something else to python /path/to/mapit.py. Then you can simple call show_me "New York".

As a side note, if you call python /path/to/mapit.py New York, it will parse New and York to be two separate arguments. If you want them to be one single argument, you will need to wrap them in quotes as such:

```<code>python /path/to/mapit.py "New York"
</code>```

Body:
I'm a beginner of Python and today I learned a new program that can search a place with Google Maps. This is the code:

import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
    address = ' '.join(sys.argv[1:])
else:
    address = pyperclip.paste()

webbrowser.open('https://www.google.com/maps/place/' + address)

My file name is mapit.py and I really want to know that I can execute by only typing, for example,

mapit New York

in the root command line instead of

Pycharm\......\pythoh3 mapit.py New York

I've tried to execute mapit.py New York on Spotlight search, but it didn't work.

Body:
To simply run a Python script, you can either invoke Python and pass the script

python mapit.py someargument "some argument with spaces"

Or you can add the proper Python shebang to the top of the script and enable the executable bit

#!/usr/bin/env python
import webbrowser, sys, pyperclip
some_code_here ...

If you then want to make this even simpler, you can set up an alias for show_me or something else to python /path/to/mapit.py. Then you can simple call show_me "New York".

As a side note, if you call python /path/to/mapit.py New York, it will parse New and York to be two separate arguments. If you want them to be one single argument, you will need to wrap them in quotes as such:

python /path/to/mapit.py "New York"


问:
Pause Excel macro while Windows is locked
I have a macro which runs an SQL query, which triggers a long slow recalculation of the spreadsheet based on the new data. When it finishes I've used application.speech to alert me if certain conditions have been met; all this works fine. But:

As I said, the recalculation can take quite a while, so I sometimes lock Windows and go do something else while I wait. Does anyone know of a way to pause the macro so that it doesn't run the last few lines (i.e. the audio alerts) until Windows is unlocked?

答:
Before you call Application.speech you could check if the system is locked and if it is locked you repeat the check every minute until it is unlocked.
Code if a system is locked

```<code>Sub SystemLocked()

    Do While Check_If_Locked = "Locked"
        Application.Wait TimeValue("00:00:01")
    Loop

    MsgBox "Done"

End Sub
</code>```

Code for Check_If_Locked can be found here
https://www.mrexcel.com/forum/microsoft-access/646623-check-if-system-locked-unlocked-using-vba.html

Body:
Before you call Application.speech you could check if the system is locked and if it is locked you repeat the check every minute until it is unlocked.
Code if a system is locked

Sub SystemLocked()

    Do While Check_If_Locked = "Locked"
        Application.Wait TimeValue("00:00:01")
    Loop

    MsgBox "Done"

End Sub

Code for Check_If_Locked can be found here
https://www.mrexcel.com/forum/microsoft-access/646623-check-if-system-locked-unlocked-using-vba.html


问:
What is the equivalent of this syntax in Java?
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

```<code>Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};
</code>```

and my code is:

```<code>public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor
</code>```

My question is, how do I convert:

```<code>SNeuron(int NumInputs);
</code>```

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.

答:
Given the comments in code, I'm pretty sure the equivalent is:

```<code>public class SNeuron {
    public final double[] weights;

    public SNeuron(int numInputs) {
        weights = new double[numInputs];
    }
}
</code>```

You don't really want to use a List<Double>, it will be much slower and take much more memory - each double in such a list becomes a full-fledged object with all associated overheads.

Body:
Just a quick question about how to convert a certain line of code between c++ and Java. I've been learning about Neural Networks and I've been starting to write my own in the language I have the most experience with, Java. It's been pretty straightforward to translate the code from C++ to Java so far, however there's one little issue I've ran into. I'm puzzled by how to translate this specific line of code into a Java equivalent, and I can't find anything specific to this issue through searching.

The original code is:

Struct SNeuron {
   //the number of inputs into the neuron

   int m_NumInputs;
   //the weights for each input
   vector<double> m_vecWeight;
   //ctor
   SNeuron(int NumInputs);
};

and my code is:

public class SNeuron {

public int m_NumInputs; // the number of inputs into the neuron
public ArrayList<Double> m_vecWeight = new ArrayList<Double>(); // the weights for each input
// ctor

My question is, how do I convert:

SNeuron(int NumInputs);

into its Java equivalent? From what i've read, Structs don't seem to be a feature Java uses, so i'm just struggling a bit to understand what exactly that line of code actually does in the context it's used.

Body:
Given the comments in code, I'm pretty sure the equivalent is:

public class SNeuron {
    public final double[] weights;

    public SNeuron(int numInputs) {
        weights = new double[numInputs];
    }
}

You don't really want to use a List<Double>, it will be much slower and take much more memory - each double in such a list becomes a full-fledged object with all associated overheads.


问:
How to nest container class in simple project with SASS?
HTML:

```<code><section>
  <div class="container"></div>
</section>
<nav>
  <div class="container"></div>
</nav>
</code>```

How to nest container class?
Probably not like this:

```<code>section {
  .container {
  }
}

nav {
 .continer {
 }
}
</code>```

Because I don't want to double style for .container.
And not like this:

```<code>.container {
  section {
  }
  nav {
  }
}
</code>```

Because container is in section, not section in container. So how?

I can use " & " but:

```<code>body {
  .container {
     section & {
     }
  }
}
</code>```

will compile to:

```<code> section body .container {
 }
</code>```

but i need:

```<code>body section .container {
}
</code>```

答:
You could achieve it by using the '&' which references the parent selector.

```<code>.container {
  section & {
    color: blue;
  }

  nav & {
    color: black;
  }
}
</code>```

The above will compile to

```<code>section .container {
  color: blue;
}

nav .container {
  color: black;
}
</code>```

The way you mentioned above would compile the other way around like:

```<code>.container section {
}
</code>```

which is not what you are looking for.

Body:
HTML:

How to nest container class?
Probably not like this:

section {
  .container {
  }
}

nav {
 .continer {
 }
}

Because I don't want to double style for .container.
And not like this:

.container {
  section {
  }
  nav {
  }
}

Because container is in section, not section in container. So how?

I can use " & " but:

body {
  .container {
     section & {
     }
  }
}

will compile to:

 section body .container {
 }

but i need:

body section .container {
}

Body:
You could achieve it by using the '&' which references the parent selector.

.container {
  section & {
    color: blue;
  }

  nav & {
    color: black;
  }
}

The above will compile to

section .container {
  color: blue;
}

nav .container {
  color: black;
}

The way you mentioned above would compile the other way around like:

.container section {
}

which is not what you are looking for.


问:
Current UTC time independant from system clock?
I need the correct time in UTC no matter what the system time is set to and also the timezone the machine is in.

(Even if I have to make a call to the internet to sync up...)

Is there some library or other way to do this elegantly?

答:
If you want to get accurate reliable time then you need to use NTP(Network time protocol) to read time from one of the public respected NTP servers more info on below links

For Node there are two ways you can get time using one of the actual NTP client implemented as Node module one i have used is [this ntp client ]

var ntpClient = require('ntp-client');

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    console.log("Current time : ");
    console.log(date); // Mon Jul 08 2013 21:31:31 GMT+0200 (Paris, Madrid (heure d’été))
});```

There are JSON api's which gives you time in JSON format you can google for them

Body:
If you want to get accurate reliable time then you need to use NTP(Network time protocol) to read time from one of the public respected NTP servers more info on below links

For Node there are two ways you can get time using one of the actual NTP client implemented as Node module one i have used is [this ntp client ]

var ntpClient = require('ntp-client');

ntpClient.getNetworkTime("pool.ntp.org", 123, function(err, date) {
    if(err) {
        console.error(err);
        return;
    }

    console.log("Current time : ");
    console.log(date); // Mon Jul 08 2013 21:31:31 GMT+0200 (Paris, Madrid (heure d’été))
});

There are JSON api's which gives you time in JSON format you can google for them


问:
Render Foreign Key in template as Checkboxes instead of Select in Django
Say we have this Model:

```<code>class Event(models.Model):
    name = models.CharField('Nome do evento', max_length=50)
    code = models.CharField('Código de entrada', max_length=10)
    artists_list = models.ForeignKey(ListGroup, on_delete=None,
    related_name='lists_names', null=True)
</code>```

and this View

```<code>class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['form'] = CreateEventForm(self.request.POST or None)
        context['defaultTitle'] = 'Novo Evento'
        context['formTitle'] = 'Criar'
        return context

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        form = context['form']
        print(form)
        if form.is_valid():
            form.save()
        return self.render_to_response(context)
</code>```

and this Form

```<code>class CreateEventForm(forms.ModelForm):

    class Meta:
        model = Event
        fields = ('name', 'code', 'artists_list',)
</code>```

Everything works great, but I would like to be able to select multiple entries that my Foreign key will retrieve. So I would like to render each entry as a checkbox instead of a select. How can I achieve that? I already searched a lot and only found about general charfields, nothing about Foreing Key
Here's how its rendering

答: A foreign key can't point to multiple entries. If you want that, you should use a ManyToManyField.</p>

Body:
Say we have this Model:

class Event(models.Model):
    name = models.CharField('Nome do evento', max_length=50)
    code = models.CharField('Código de entrada', max_length=10)
    artists_list = models.ForeignKey(ListGroup, on_delete=None,
    related_name='lists_names', null=True)

and this View

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['form'] = CreateEventForm(self.request.POST or None)
        context['defaultTitle'] = 'Novo Evento'
        context['formTitle'] = 'Criar'
        return context

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        form = context['form']
        print(form)
        if form.is_valid():
            form.save()
        return self.render_to_response(context)

and this Form

class CreateEventForm(forms.ModelForm):

    class Meta:
        model = Event
        fields = ('name', 'code', 'artists_list',)

Everything works great, but I would like to be able to select multiple entries that my Foreign key will retrieve. So I would like to render each entry as a checkbox instead of a select. How can I achieve that? I already searched a lot and only found about general charfields, nothing about Foreing Key
Here's how its rendering


问:
Session variable not set in Spring
I have a Spring controller which is putting a variable in the session:

```<code>public class LoginFormController extends SimpleFormController {

    public ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command) throws Exception {

            request.getSession().setAttribute("authenticated_user", "authenticated_user");
    }
}
</code>```

I then have a HandlerInterceptor. In the preHandle method, I check for the variable in the session:

```<code>public boolean preHandle(HttpServletRequest request,
                                      HttpServletResponse response,
                                      Object handler) throws Exception {

        /* first, check if the requested view even required authentication */
        if (isAuthenticationRequired(request)) {

            /* check to see that user is logged in */
            if (null == request.getSession().getAttribute("authenticated_user")) {
                forwardToLogonPage(request, response);
                return false;
            }
            /* all is ok - pass the request on */
            return true;
        }
        /* all is ok - pass the request on */
        return true;
    }
</code>```

The problem is it seems that the session variable is not being set since request.getSession().getAttribute("authenticated_user")) is always resolving to null.

Any ideas plz?

Thanks,
Krt_Malta

答:
Try throw new ModelAndViewDefiningException(new ModelAndView("logonPage")) instead of return false.

And in your logonPage, explicitly include the action in the form tag, something like this:

```<code><form:form method="post" commandName="login" action="logonPage.htm">
</code>```

Title: Session variable not set in Spring

Body:
I have a Spring controller which is putting a variable in the session:

public class LoginFormController extends SimpleFormController {

    public ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command) throws Exception {

            request.getSession().setAttribute("authenticated_user", "authenticated_user");
    }
}

I then have a HandlerInterceptor. In the preHandle method, I check for the variable in the session:

public boolean preHandle(HttpServletRequest request,
                                      HttpServletResponse response,
                                      Object handler) throws Exception {

        /* first, check if the requested view even required authentication */
        if (isAuthenticationRequired(request)) {

            /* check to see that user is logged in */
            if (null == request.getSession().getAttribute("authenticated_user")) {
                forwardToLogonPage(request, response);
                return false;
            }
            /* all is ok - pass the request on */
            return true;
        }
        /* all is ok - pass the request on */
        return true;
    }

The problem is it seems that the session variable is not being set since request.getSession().getAttribute("authenticated_user")) is always resolving to null.

Any ideas plz?

Thanks,
Krt_Malta

Body:
Try throw new ModelAndViewDefiningException(new ModelAndView("logonPage")) instead of return false.

And in your logonPage, explicitly include the action in the form tag, something like this:

<form:form method="post" commandName="login" action="logonPage.htm">


问:
iptables issue centos 6 - is my port open?
I've entered some rules into IPtables on CentOS 6. But when I run 'service iptables status' I get a different result than when I go 'iptables -L'.

I need to open up port 1270 on this machine.

This is what I see when I go 'service iptables status'

```<code>[root@server01 sysconfig]# service iptables status
Table: filter
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     icmp --  0.0.0.0/0            0.0.0.0/0           /* 000 reject all icmp requests */ reject-with icmp-port-unreachable
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           /* 001 accept all to lo interface */
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           /* 002 accept related established rules */ state RELATED,ESTABLISHED
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           multiport ports 22 /* 100 allow ssh access */
5    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           multiport ports 443,8443 /* 110 allow https access */
6    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:1556
7    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:13782
8    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:13724
9    ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:1556
10   ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:13782
11   ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:13724
12   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
13   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:443
14   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:5222
15   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:5269
16   ACCEPT     tcp  --  10.36.16.25          0.0.0.0/0           tcp dpt:1270
17   ACCEPT     tcp  --  10.36.16.26          0.0.0.0/0           tcp dpt:1270
18   ACCEPT     tcp  --  10.36.16.37          0.0.0.0/0           tcp dpt:1270
19   ACCEPT     tcp  --  10.36.16.31          0.0.0.0/0           tcp dpt:1270

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
</code>```

And this is what I see when I go iptables -L

```<code>[root@server01 sysconfig]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
REJECT     icmp --  anywhere             anywhere            /* 000 reject all icmp requests */ reject-with icmp-port-unreachable
ACCEPT     all  --  anywhere             anywhere            /* 001 accept all to lo interface */
ACCEPT     all  --  anywhere             anywhere            /* 002 accept related established rules */ state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            multiport ports ssh /* 100 allow ssh access */
ACCEPT     tcp  --  anywhere             anywhere            multiport ports https,pcsync-https /* 110 allow https access */
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:veritas_pbx
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:bpcd
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:vnetd
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:veritas_pbx
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:bpcd
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:vnetd
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:xmpp-client
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:xmpp-server
ACCEPT     tcp  --  abckpap6181.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abckpap6182.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abcepap6782.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abcepap6783.us.companyworld.company.com  anywhere            tcp dpt:opsmgr

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
</code>```

So, is port 120 open on this machine or not? Why am I see a difference between the two commands?

答:
Port 1270 is open as you can see bellow:

```<code>16   ACCEPT     tcp  --  10.36.16.25          0.0.0.0/0           tcp dpt:1270
17   ACCEPT     tcp  --  10.36.16.26          0.0.0.0/0           tcp dpt:1270
18   ACCEPT     tcp  --  10.36.16.37          0.0.0.0/0           tcp dpt:1270
19   ACCEPT     tcp  --  10.36.16.31          0.0.0.0/0           tcp dpt:1270
</code>```

but it's limited to those 4 ip addresses.

The output is different since service iptables status shows the iptables output using numeric format for ip addresses and ports while using iptables -L doesn't do that. If you want to get a similar ouput try iptables -nL

I would also issue a netstat -tunlp | grep 1270 just to be sure that there is some service/program/app actually listening to that port

Body:
I've entered some rules into IPtables on CentOS 6. But when I run 'service iptables status' I get a different result than when I go 'iptables -L'.

I need to open up port 1270 on this machine.

This is what I see when I go 'service iptables status'

[root@server01 sysconfig]# service iptables status
Table: filter
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    REJECT     icmp --  0.0.0.0/0            0.0.0.0/0           /* 000 reject all icmp requests */ reject-with icmp-port-unreachable
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           /* 001 accept all to lo interface */
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           /* 002 accept related established rules */ state RELATED,ESTABLISHED
4    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           multiport ports 22 /* 100 allow ssh access */
5    ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           multiport ports 443,8443 /* 110 allow https access */
6    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:1556
7    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:13782
8    ACCEPT     tcp  --  10.1.190.65          0.0.0.0/0           tcp dpt:13724
9    ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:1556
10   ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:13782
11   ACCEPT     tcp  --  10.48.131.220        0.0.0.0/0           tcp dpt:13724
12   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
13   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:443
14   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:5222
15   ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:5269
16   ACCEPT     tcp  --  10.36.16.25          0.0.0.0/0           tcp dpt:1270
17   ACCEPT     tcp  --  10.36.16.26          0.0.0.0/0           tcp dpt:1270
18   ACCEPT     tcp  --  10.36.16.37          0.0.0.0/0           tcp dpt:1270
19   ACCEPT     tcp  --  10.36.16.31          0.0.0.0/0           tcp dpt:1270

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

And this is what I see when I go iptables -L

[root@server01 sysconfig]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
REJECT     icmp --  anywhere             anywhere            /* 000 reject all icmp requests */ reject-with icmp-port-unreachable
ACCEPT     all  --  anywhere             anywhere            /* 001 accept all to lo interface */
ACCEPT     all  --  anywhere             anywhere            /* 002 accept related established rules */ state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            multiport ports ssh /* 100 allow ssh access */
ACCEPT     tcp  --  anywhere             anywhere            multiport ports https,pcsync-https /* 110 allow https access */
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:veritas_pbx
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:bpcd
ACCEPT     tcp  --  10.1.190.65          anywhere            tcp dpt:vnetd
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:veritas_pbx
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:bpcd
ACCEPT     tcp  --  uawscdap0000.us.companyworld.company.com  anywhere            tcp dpt:vnetd
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:xmpp-client
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:xmpp-server
ACCEPT     tcp  --  abckpap6181.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abckpap6182.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abcepap6782.us.companyworld.company.com  anywhere            tcp dpt:opsmgr
ACCEPT     tcp  --  abcepap6783.us.companyworld.company.com  anywhere            tcp dpt:opsmgr

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

So, is port 120 open on this machine or not? Why am I see a difference between the two commands?

Body:
Port 1270 is open as you can see bellow:

16   ACCEPT     tcp  --  10.36.16.25          0.0.0.0/0           tcp dpt:1270
17   ACCEPT     tcp  --  10.36.16.26          0.0.0.0/0           tcp dpt:1270
18   ACCEPT     tcp  --  10.36.16.37          0.0.0.0/0           tcp dpt:1270
19   ACCEPT     tcp  --  10.36.16.31          0.0.0.0/0           tcp dpt:1270

but it's limited to those 4 ip addresses.

The output is different since service iptables status shows the iptables output using numeric format for ip addresses and ports while using iptables -L doesn't do that. If you want to get a similar ouput try iptables -nL

I would also issue a netstat -tunlp | grep 1270 just to be sure that there is some service/program/app actually listening to that port


问:
PHP built in server, any way to configure it to show files of directory?
As yous may be aware, as of PHP 5.4 there is built in server available. However, if you browse to directory with no "index" file, instead if listing all available files/directories (like apache for example), it will give you and error.

Now as far as I understand this is by design and not some sort of bug. But maybe someone knows if there is a way to configure it, to list the contents of directory?

答:
Old question, but I feel this could still be useful.

I'm guilty of using the integrate web server not just for debug, but also to share files from random folders on my pc with virtualmachines or other pc in lan.

Said so, here's my updates script (it cam be used with "php -S localhost:8080 -t . script.php" from any folder):

<?php
$dir = realpath(isset($_GET['dir']) ? $_GET['dir'] : ".");
if (is_dir($dir)) {
  echo "
Index of $dir:
\n";
  $files = array_diff(scandir($dir), array('..', '.'));
  usort($files, function($a, $b) use ($dir) {
    if (is_dir("{$dir}/{$a}") == is_dir("{$dir}/{$b}")) {
      return strnatcasecmp($a, $b);
    } else {
      return is_dir("{$dir}/{$a}") ? -1 : 1;
    }
  });
  echo "⏎\n";
  foreach ($files as $file) {
    if (is_dir("{$dir}/{$file}")) {
      $typef = "[directory]";
    } else {
      $typef = "[" . pathinfo($file, PATHINFO_EXTENSION) . " file]";
    }
    ?>
    '>

<?= $file; ?>

<?= $typef; ?>

    <?php
  }
} else if (is_file($dir)) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . basename($dir) . '"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($dir));
  readfile($dir);
}
```

Body:
Old question, but I feel this could still be useful.

I'm guilty of using the integrate web server not just for debug, but also to share files from random folders on my pc with virtualmachines or other pc in lan.

Said so, here's my updates script (it cam be used with "php -S localhost:8080 -t . script.php" from any folder):

<style>
  a {
    color: black;
    width: 100%;
    display: flex;
    flex-direction: row;
  }

  a:hover {
    background-color: #77AAFF;
    color: black;
  }

  .linkLeft {
    flex-grow: 0;
  }

  .linkCenter {
    flex-grow: 1;
    margin: -3px 10px 3px;
    border-bottom: 1px dotted black;
  }

  .linkRight {
    flex-grow: 0;
  }
</style>
<?php
$dir = realpath(isset($_GET['dir']) ? $_GET['dir'] : ".");
if (is_dir($dir)) {
  echo "<h2>Index of $dir:</h2>\n";
  $files = array_diff(scandir($dir), array('..', '.'));
  usort($files, function($a, $b) use ($dir) {
    if (is_dir("{$dir}/{$a}") == is_dir("{$dir}/{$b}")) {
      return strnatcasecmp($a, $b);
    } else {
      return is_dir("{$dir}/{$a}") ? -1 : 1;
    }
  });
  echo "<a href='?dir=" . urlencode(realpath("{$dir}/..")) . "'>⏎</a>\n";
  foreach ($files as $file) {
    if (is_dir("{$dir}/{$file}")) {
      $typef = "[directory]";
    } else {
      $typef = "[" . pathinfo($file, PATHINFO_EXTENSION) . " file]";
    }
    ?>
    <a href='?dir=<?= urlencode("{$dir}/{$file}"); ?>'>
      <div class='linkLeft'><?= $file; ?></div>
      <div class='linkCenter'></div>
      <div class='linkRight'><?= $typef; ?></div>
    </a>
    <?php
  }
} else if (is_file($dir)) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . basename($dir) . '"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($dir));
  readfile($dir);
}


问:
how to get the first splited part of each index in an array
we have an array like below, length of the array is not constant(may increase/decrease).

```<code>[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
</code>```

My aim is to achieve only the first part of each index like below.

```<code>[255028AD,261830AD,.........]
</code>```

Please help.

答:
Using a for ... of:

var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'];
var index = 0;
for (item of arr) {
  arr[index] = item.split('_')[0];
  index++;
}

console.log(arr);```

Body:
we have an array like below, length of the array is not constant(may increase/decrease).

[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]

My aim is to achieve only the first part of each index like below.

[255028AD,261830AD,.........]

Please help.


问:
Widows Server STFP client (Not Server) with restricted access to a specific folder
I need to install and configure SFTP Client on Windows Server 2012 with restricted access to one folder only. This is to transfer file, the file is being pushed from UNIX server. This means I need something that is command line friendly. The server will have SQL Server 2016.

I have tried cygwin and it seems to be too complicated and heavyweight with tonnes of packages so I gave up on it. I have now downloaded PSFTP, this is quite light and I wonder if anyone have installed this? If yes can you provide a link to the steps in configuring it on Windows Server with restricted access to a specific folder.

How can I make the psftp client on windows server to accept connection for file transfer from UNIX server.I see that I have to run the PSFTP manually on windows server.

答: In order to accept connections we need to install full SFTP server like Filezilla, openSSH etc. on to the Windows Server. So I ended up using the PSFTP client with script to pull file and run it via Scheduler at a set timing.</p>


问:
Python appending to a sublist in a list of lists
I have a list of empty lists as such:

```<code>some_lists = [[]] * 3
[[], [], []]
</code>```

I want to append an integer to the first sublist:

```<code>some_lists[0].append(1)
</code>```

But it appends the integer 1 to all the sublists and generates:

```<code>[[1], [1], [1]]
</code>```

How do I append elements individually to the sublists?

答:
You have created a reference to every sublist in the list. Instead, you can use a list comprehension:

```<code>some_lists = [[] for i in range(3)]
some_lists[0].append(3)
</code>```

Output:

```<code>[[3], [], []]

</code>```

Body:
I have a list of empty lists as such:

some_lists = [[]] * 3
[[], [], []]

I want to append an integer to the first sublist:

some_lists[0].append(1)

But it appends the integer 1 to all the sublists and generates:

[[1], [1], [1]]

How do I append elements individually to the sublists?

Body:
You have created a reference to every sublist in the list. Instead, you can use a list comprehension:

some_lists = [[] for i in range(3)]
some_lists[0].append(3)

Output:

[[3], [], []]