qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
8,828,687
Mostly out of curiosity, I would like to know if there are any edge cases that can arise from cases like: ``` <span class="class1 class2 class3 class2 class4">...</span> ``` (`class2` is listed twice) or ``` <span class="class1 class2 class3 class2 class2 class2 class3 class4 class4 class3">...</span> ``` (a more extreme version of the same) This is obviously messy css and not ideal, but **are there any edge cases this creates?**
2012/01/12
[ "https://Stackoverflow.com/questions/8828687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224354/" ]
**No, none whatsoever**, unless you have the habit of using the `class` attribute: ``` [class="class1 class2"] { /* ... */ } ``` instead of: ``` .class1.class2 { /* ... */ } ``` which is terrible practice, of course. --- Also, although your question isn't tagged [javascript](/questions/tagged/javascript "show questions tagged 'javascript'"), note that if only the first instance of a class is removed and an unlimited number added, say: ``` function addClass(element, cls) { element.className += ' ' + cls; } ``` but ``` function removeClass(element, cls) { return element.className.replace(cls, ' '); } ``` this will cause problems in more ways than one.
FYI browsers such as firefox/chrome/ie9, **computing the style contexts using the rule tree**, **if two rules have the same weight, origin and specificity, the one written lower down in the style sheet wins**. so ... styles : ``` .c1 {background:red;}.c1.c3 {background:blue;}.c2 {background:orange;} ``` case1 : ``` <div class="c1 c1 c1"/><!-- background is red --> ``` case2 : ``` <div class="c1 c2"/><div class="c2 c1 c2"/><!-- background is orange --> ``` case3 : ``` <div class="c2 c1 c1 c2 c3"/><!-- background is blue --> ```
8,828,687
Mostly out of curiosity, I would like to know if there are any edge cases that can arise from cases like: ``` <span class="class1 class2 class3 class2 class4">...</span> ``` (`class2` is listed twice) or ``` <span class="class1 class2 class3 class2 class2 class2 class3 class4 class4 class3">...</span> ``` (a more extreme version of the same) This is obviously messy css and not ideal, but **are there any edge cases this creates?**
2012/01/12
[ "https://Stackoverflow.com/questions/8828687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224354/" ]
FYI browsers such as firefox/chrome/ie9, **computing the style contexts using the rule tree**, **if two rules have the same weight, origin and specificity, the one written lower down in the style sheet wins**. so ... styles : ``` .c1 {background:red;}.c1.c3 {background:blue;}.c2 {background:orange;} ``` case1 : ``` <div class="c1 c1 c1"/><!-- background is red --> ``` case2 : ``` <div class="c1 c2"/><div class="c2 c1 c2"/><!-- background is orange --> ``` case3 : ``` <div class="c2 c1 c1 c2 c3"/><!-- background is blue --> ```
No, there is nothing *wrong* with it other than it looks weird. Any re-occurences of a class name won't affect anything, ever. It doesn't "reapply" those styles after applying styles from the class defined before it or anything. Remember that CSS will always select the style defined *last* for that level of specificity. See this [jsFiddle](http://jsfiddle.net/xZmvX/2/) and note how class4 *always* overrides the font color, no matter what combinations of class1, class2, and class3 are used. Ultimately, it's seen as having class name class1, having class name class2, having class name class3, and having class name class4. Repeating them is like clicking on the radio button again. It's already selected, no need to keep clicking it...
43,838,466
I've found this code on another thread (shown at the very bottom) for Swift 3 and can't seem to get it to work in my IOS project. I know it's a Singleton, but I'll have to admit, I'm not sure how to USE it in my IOS project so that the timer will work across all ViewControllers. Can I do the following? And if not, how can I use this? ``` var t = TimeModel.sharedTimer t.startTimer(0.25, testing) var counter = 0 func testing() { counter += 1 print("this is a test \(counter)") } ``` **What am I doing wrong?** ``` class TimerModel: NSObject { static let sharedTimer: TimerModel = { let timer = TimerModel() return timer }() var internalTimer: Timer? var jobs = [() -> Void]() func startTimer(withInterval interval: Double, andJob job: @escaping () -> Void) { if internalTimer == nil { internalTimer?.invalidate() } jobs.append(job) internalTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(doJob), userInfo: nil, repeats: true) } func pauseTimer() { guard internalTimer != nil else { print("No timer active, start the timer before you stop it.") return } internalTimer?.invalidate() } func stopTimer() { guard internalTimer != nil else { print("No timer active, start the timer before you stop it.") return } jobs = [()->()]() internalTimer?.invalidate() } func doJob() { for job in jobs { job() } } } ```
2017/05/08
[ "https://Stackoverflow.com/questions/43838466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7978073/" ]
`#rainbow` refers to the unordered list, not the list items themselves. You need to change your selector to include the list elements: ``` let listItems = document.querySelectorAll('#rainbow li'); ``` ### Explanation The selector passed to the `querySelectorAll` method matches the way you would write a CSS selector: you are gathering all elements that match that selector and *only* that selector. The selector `#rainbow li` may be a little bit greedy, too, in that it will select all `li`s that are **descendants** of the `#rainbow` element, not just the **children**. To select only the children you could write: ``` let listItems = document.querySelectorAll('#rainbow > li'); // or, more verbose... let rainbow = document.querySelectorAll('#rainbow'); let listItems = rainbow.children; ``` Had `querySelectorAll` given back elements that you weren't explicitly asking for, I'd say that's a broken method.
The array of colors could have more elements than the listItems array. So, when i variable is greater than the size of the listItems array - 1, you receive a TypeError. And of course, you have to select the items inside the ul and not the ul itself.
7,796
I'm trying to solve a system of equations: ``` Solve[ A1 D1 + E1 H1 == 0 && A2 D1 + A1 D2 + E2 H1 + E1 H2 == 0 && C1 F1 - E1 G1 == 0 && C2 F2 - E2 G2 == 0 && A1 - B1 + C1 == 0 && A2 - B2 + C2 == 0 && A3 - B3 + C3 == 0, {A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,E1,E2,F1,F2,G1,G2,H1,H2}] ``` Since we have more variables than equations, we have more than 1 solution satisfying the above equations but I don't want Mathematica to give me all possible solutions -- I would like just only one. **1. How do I get Mathematica to give me just one possible solution?** One way I thought about doing this is to plug in random numbers such as `A2 = 1/2, B2 = 1, C2 = 1/2`, etc. so that all other variables are determined. But this isn't a very effective strategy in case the numbers I plug in do not satisfy all of the above equations. (One reason why I don't want all possible solutions to a system of equations is because suppose I am working with 30 equations and 80 variables. Then this is crashing Mathematica.)
2012/07/02
[ "https://mathematica.stackexchange.com/questions/7796", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1481/" ]
The Wolfram Demonstration in its original version was wrong. The demo **has since been corrected (updated March 2013)**. The *first* five functions called $H$ there (**which were originally the only functions listed**) do *not* form a group. You need a **sixth** element to make the set closed under multiplication! This can be checked by defining the six functions as follows, with the missing element as the last function. I call the table of functions `h`, and then construct the multiplication table: ``` h = {# &, 1/# &, 1 - # &, 1/(1 - #) &, (# - 1)/# &, #/(# - 1) &}; TableForm[multiplicationTable = Table[ Simplify[ h[[i]][h[[j]][x]] ], {i, 1, 6}, {j, 1, 6} ] ] ``` > > $\left( > \begin{array}{cccccc} > x & \frac{1}{x} & 1-x & \frac{1}{1-x} & \frac{x-1}{x} & > \frac{x}{x-1} \\ > \frac{1}{x} & x & \frac{1}{1-x} & 1-x & \frac{x}{x-1} & > \frac{x-1}{x} \\ > 1-x & \frac{x-1}{x} & x & \frac{x}{x-1} & \frac{1}{x} & > \frac{1}{1-x} \\ > \frac{1}{1-x} & \frac{x}{x-1} & \frac{1}{x} & > \frac{x-1}{x} & x & 1-x \\ > \frac{x-1}{x} & 1-x & \frac{x}{x-1} & x & \frac{1}{1-x} > & \frac{1}{x} \\ > \frac{x}{x-1} & \frac{1}{1-x} & \frac{x-1}{x} & > \frac{1}{x} & 1-x & x \\ > \end{array} > \right)$ > > > To see that this table would be incomplete without the last function $x/(x-1)$, look at the element `{2, 5}` in the table: it is not equal to any of the first five functions. Now to **answer the question** of how to construct a function that is invariant under this (corrected) group. This is done in group theory using *projection operators*. Here we're only interested in the simplest (identity) representation of the group, for which the projector consists of adding all the group actions on an arbitrary trial function and dividing by the order `n` of the group $\mathcal{G}$. Here is the formula in mathematical notation and then as a *Mathematica* definition: $$f\_\text{sym}(x)\equiv \frac{1}{n}\sum\_{H\in \mathcal{G}} f(H(x)) $$ ``` symmetrize[f_] := With[{n = Length[h]}, Function[{x}, 1/n Total@Map[Composition[f, #][x] &, h] ] ] ``` Here `f` is the trial function, and the simplest choice is ``` f[x_] := x; fSym = symmetrize[f]; fSym[x] ``` > > $\frac{1}{6} > \left(\frac{x-1}{x}+\frac{1}{1-x}+\frac{1}{x}+\frac{x} > {x-1}+1\right)$ > > > Check that this is indeed an invariant function: ``` Table[ Simplify[fSym[h[[i]][x]] == fSym[h[[j]][x]]], {i, 1, 6}, {j, 1, 6}] // TableForm ``` > > $\left( > \begin{array}{cccccc} > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \text{True} & \text{True} & \text{True} & \text{True} & > \text{True} & \text{True} \\ > \end{array} > \right)$ > > > Now the real fun starts if you choose different trial functions `f`. ``` f[x_] := Exp[x - x^2] fSym = symmetrize[f]; Simplify[fSym[x]] ``` > > $\frac{1}{3} > \left(e^{\frac{x-1}{x^2}}+e^{x-x^2}+e^{-\frac{x}{(x-1) > ^2}}\right)$ > > > And believe it or not, this is also an invariant function. To verify, repeat the check I did above. **Edit: check the given invariant function** We can also verify that the function that is *given* in the Wolfram demonstration is indeed one of the possible invariant functions, by showing that it is mapped onto itself by the projection operator `symmetrize`: ``` invariant1[x_] := (x^2 - x + 1)^3/(x^2 (x - 1)^2) Simplify[symmetrize[invariant1][x] == invariant1[x]] (* ==> True *) ```
Not a general solution, but works for the case you cited; ``` (*Definitions*) an=6; bn=4; h[0,x_]:=x; h[1,x_]:=1/x; h[2,x_]:=1-x; h[3,x_]:=1/(1-x); h[4,x_]:=(x-1)/x; f[x_] := Sum[a@i x^i,{i,an}] / Sum[b@i x^i,{i,bn}]; (*Proposed form / Rational*) (*Now find the coefficients a[i] and b[i]*) ss=Solve[And @@ Table[f@h[i,x] == f@x,{i,0,4}], Join[Array[a,an],Array[b,bn]]]; (*Get a function from the results set*) ff[x_] := FullSimplify[f@x/.ss[[1]]/.Table[a@i->1,{i,an}]/.Table[b@i->1,{i,bn}]]; ``` Now test it: ``` Table[ff@h[i,x] == ff@x, {i, 0, 4}] ff@x (* -> {True, True, True, True, True} -> 2/(-1 + x) + ((-1 + x)^2 (1 + x + x^2))/x^2 *) ```
55,634,148
I am training Logistic Regression in R. I use train set and test set. I have some data and binary output. In a data file the output is the integers 1 or 0 without missing values. I have more 1 than 0 (the proportion is 70/30). The result of LR is very different depending on if I factories the output or not, namely if I keep output variable as numeric 0-1 and I write ``` m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` then I get something without warnings and errors and if I write ``` dt$output<-as.factor(ifelse(dt$output == 1, "Good", "Bad")) m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` I get completely different performance! What could it be? To be more precise, after training LR I do the following: ``` score <- predict(m1,type='response',dt_test) m1_pred <- prediction(m1_score, dt_test$output) m1_perf <- performance(m1_pred,"tpr","fpr") #ROC plot(m1_perf, lwd=2, main="ROC") ``` I get very different ROCs and AUCs.
2019/04/11
[ "https://Stackoverflow.com/questions/55634148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11346454/" ]
You could turn off/on the click handler conditionally by using ``` end.tap { |item| item.on(:click) { select_envelope } unless conflicts } ``` to replace ``` end.on(:click) { select_envelope } ```
I'm not sure that checking the element for a click event would be reliable due to event bubbling. I would write the test to click the element, and then expect whatever logic is in the click event to not happen. ``` conflicts = true element.click() # trigger select_envelope expect(selected_envelope).to be_nil # no envelope should be selected due to conflicts ```
55,634,148
I am training Logistic Regression in R. I use train set and test set. I have some data and binary output. In a data file the output is the integers 1 or 0 without missing values. I have more 1 than 0 (the proportion is 70/30). The result of LR is very different depending on if I factories the output or not, namely if I keep output variable as numeric 0-1 and I write ``` m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` then I get something without warnings and errors and if I write ``` dt$output<-as.factor(ifelse(dt$output == 1, "Good", "Bad")) m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` I get completely different performance! What could it be? To be more precise, after training LR I do the following: ``` score <- predict(m1,type='response',dt_test) m1_pred <- prediction(m1_score, dt_test$output) m1_perf <- performance(m1_pred,"tpr","fpr") #ROC plot(m1_perf, lwd=2, main="ROC") ``` I get very different ROCs and AUCs.
2019/04/11
[ "https://Stackoverflow.com/questions/55634148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11346454/" ]
You could turn off/on the click handler conditionally by using ``` end.tap { |item| item.on(:click) { select_envelope } unless conflicts } ``` to replace ``` end.on(:click) { select_envelope } ```
A nice way to keep the code clean is just return inside the method called in the event: ```rb def select_envelope return if conflicts ... end # this keeps the event handler the same end.on(:click) { select_envelope } ``` There will be a negligible performance hit from having to always trigger the event, but there's always the debate of performance vs readability.
55,634,148
I am training Logistic Regression in R. I use train set and test set. I have some data and binary output. In a data file the output is the integers 1 or 0 without missing values. I have more 1 than 0 (the proportion is 70/30). The result of LR is very different depending on if I factories the output or not, namely if I keep output variable as numeric 0-1 and I write ``` m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` then I get something without warnings and errors and if I write ``` dt$output<-as.factor(ifelse(dt$output == 1, "Good", "Bad")) m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` I get completely different performance! What could it be? To be more precise, after training LR I do the following: ``` score <- predict(m1,type='response',dt_test) m1_pred <- prediction(m1_score, dt_test$output) m1_perf <- performance(m1_pred,"tpr","fpr") #ROC plot(m1_perf, lwd=2, main="ROC") ``` I get very different ROCs and AUCs.
2019/04/11
[ "https://Stackoverflow.com/questions/55634148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11346454/" ]
``` end.on(:click) { select_envelope } ``` You could replace `(:click)` with: ``` (!conflicts && :click) ``` This works because if conflicts is not nil, this would result in a nil click handler that doesn't do anything.
I'm not sure that checking the element for a click event would be reliable due to event bubbling. I would write the test to click the element, and then expect whatever logic is in the click event to not happen. ``` conflicts = true element.click() # trigger select_envelope expect(selected_envelope).to be_nil # no envelope should be selected due to conflicts ```
55,634,148
I am training Logistic Regression in R. I use train set and test set. I have some data and binary output. In a data file the output is the integers 1 or 0 without missing values. I have more 1 than 0 (the proportion is 70/30). The result of LR is very different depending on if I factories the output or not, namely if I keep output variable as numeric 0-1 and I write ``` m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` then I get something without warnings and errors and if I write ``` dt$output<-as.factor(ifelse(dt$output == 1, "Good", "Bad")) m1 <- glm(output~.,data=dt_tr,family=binomial()) ``` I get completely different performance! What could it be? To be more precise, after training LR I do the following: ``` score <- predict(m1,type='response',dt_test) m1_pred <- prediction(m1_score, dt_test$output) m1_perf <- performance(m1_pred,"tpr","fpr") #ROC plot(m1_perf, lwd=2, main="ROC") ``` I get very different ROCs and AUCs.
2019/04/11
[ "https://Stackoverflow.com/questions/55634148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11346454/" ]
``` end.on(:click) { select_envelope } ``` You could replace `(:click)` with: ``` (!conflicts && :click) ``` This works because if conflicts is not nil, this would result in a nil click handler that doesn't do anything.
A nice way to keep the code clean is just return inside the method called in the event: ```rb def select_envelope return if conflicts ... end # this keeps the event handler the same end.on(:click) { select_envelope } ``` There will be a negligible performance hit from having to always trigger the event, but there's always the debate of performance vs readability.
58,617,144
I am trying to filter a list of POJOs with two different predicates using a stream. ``` public class Toy { public boolean isRed(); public boolean isBlue(); public boolean isGreen(); } public class RedBlueExtravaganza { public RedBlueExtravaganza(RedToy rt, BlueToy bt) { //construct } } // Wrappers around Toy with more verbose names public class RedToy extends Toy { } public class BlueToy extends Toy { } public class GreenToy extends Toy { } ``` Basically, I want the first red and the first blue toy in the list of Toy objects. ``` List<Toy> toyList = Arrays.asList(greenToy1, redToy1, greenToy2, redToy2, blueToy1); ``` I want to write a stream that does the following: ``` RedBlueExtravaganza firstRedBlueList = toyList.stream() // get first red but keep rest of list // get first blue but keep rest of list // discard rest of list // map to a Tuple (or something) to distinguish the one red and one blue toy // map to RedBlueExtravaganza .findFirst() .get(); log.info(firstRedBlueList); // now contains redToy1, blueToy1 ``` Thanks for the help!
2019/10/30
[ "https://Stackoverflow.com/questions/58617144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10205830/" ]
Here's a solution which traverses your list only once, giving you the first red and blue toys at the end. We can filter out all the other irrelevent colors and then create a map whose key is whether the toy is red and the value is the first toy matching the given criteria. Here's how it looks. ``` Map<Boolean, Toy> firstRedAndBlueToysMap = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .collect(Collectors.toMap(Toy::isRed, t -> t, (a, b) -> a)); Toy firstRedToy = firstRedAndBlueToysMap.get(true); Toy firstBlueToy = firstRedAndBlueToysMap.get(false); ``` And here's a one step approach to solve your problem. ``` RedBlueExtravaganza firstRedAndBlueToyPair = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .collect(Collectors.collectingAndThen(Collectors.toMap(Toy::isRed, t -> t, (a, b) -> a), m -> new RedBlueExtravaganza(m.get(true), m.get(false)))); ``` P.S. For this to work you need to have the following constructor in your `RedBlueExtravaganza` class contrary to the one you have provided above. ``` public RedBlueExtravaganza(Toy rt, Toy bt) { if (!(rt instanceof RedToy) || !(bt instanceof BlueToy)) throw new IllegalArgumentException(); // remainder omitted. } ```
One way which first comes into my mind is to use 2 streams for finding first red and blue toy object, respectively. Then merge them into one stream by using `Stream.concat()` so that you can add more oprations for this. **Code snippet** ``` RedBlueExtravaganza firstRedBlueList = Stream .concat( toyList.stream().filter(t -> t.isRed()) .findFirst() .map(Collections::singletonList) .orElseGet(Collections::emptyList) .stream(), toyList.stream().filter(t -> t.isBlue()) .findFirst() .map(Collections::singletonList) .orElseGet(Collections::emptyList) .stream()) .map(x -> { RedToy rt = new RedToy(); BlueToy bt = new BlueToy(); ... return new RedBlueExtravaganza(rt, bt);}) .findFirst() .get(); ```
58,617,144
I am trying to filter a list of POJOs with two different predicates using a stream. ``` public class Toy { public boolean isRed(); public boolean isBlue(); public boolean isGreen(); } public class RedBlueExtravaganza { public RedBlueExtravaganza(RedToy rt, BlueToy bt) { //construct } } // Wrappers around Toy with more verbose names public class RedToy extends Toy { } public class BlueToy extends Toy { } public class GreenToy extends Toy { } ``` Basically, I want the first red and the first blue toy in the list of Toy objects. ``` List<Toy> toyList = Arrays.asList(greenToy1, redToy1, greenToy2, redToy2, blueToy1); ``` I want to write a stream that does the following: ``` RedBlueExtravaganza firstRedBlueList = toyList.stream() // get first red but keep rest of list // get first blue but keep rest of list // discard rest of list // map to a Tuple (or something) to distinguish the one red and one blue toy // map to RedBlueExtravaganza .findFirst() .get(); log.info(firstRedBlueList); // now contains redToy1, blueToy1 ``` Thanks for the help!
2019/10/30
[ "https://Stackoverflow.com/questions/58617144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10205830/" ]
I like [this answers](https://stackoverflow.com/a/58618100/11733759), similar solution can be with reduce and List as "Tuple (or something)" ```java List<Toy> reduceToList = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .map(t -> Arrays.asList(t, t)) .reduce(Arrays.asList(null, null), (a, c) -> a.get(0) == null && c.get(0).isRed() ? Arrays.asList(c.get(0), a.get(1)) : (a.get(1) == null && c.get(1).isBlue() ? Arrays.asList(a.get(0), c.get(1)) : a) ); ``` If both values are not null then you can map to `RedBlueExtravaganza`
One way which first comes into my mind is to use 2 streams for finding first red and blue toy object, respectively. Then merge them into one stream by using `Stream.concat()` so that you can add more oprations for this. **Code snippet** ``` RedBlueExtravaganza firstRedBlueList = Stream .concat( toyList.stream().filter(t -> t.isRed()) .findFirst() .map(Collections::singletonList) .orElseGet(Collections::emptyList) .stream(), toyList.stream().filter(t -> t.isBlue()) .findFirst() .map(Collections::singletonList) .orElseGet(Collections::emptyList) .stream()) .map(x -> { RedToy rt = new RedToy(); BlueToy bt = new BlueToy(); ... return new RedBlueExtravaganza(rt, bt);}) .findFirst() .get(); ```
58,617,144
I am trying to filter a list of POJOs with two different predicates using a stream. ``` public class Toy { public boolean isRed(); public boolean isBlue(); public boolean isGreen(); } public class RedBlueExtravaganza { public RedBlueExtravaganza(RedToy rt, BlueToy bt) { //construct } } // Wrappers around Toy with more verbose names public class RedToy extends Toy { } public class BlueToy extends Toy { } public class GreenToy extends Toy { } ``` Basically, I want the first red and the first blue toy in the list of Toy objects. ``` List<Toy> toyList = Arrays.asList(greenToy1, redToy1, greenToy2, redToy2, blueToy1); ``` I want to write a stream that does the following: ``` RedBlueExtravaganza firstRedBlueList = toyList.stream() // get first red but keep rest of list // get first blue but keep rest of list // discard rest of list // map to a Tuple (or something) to distinguish the one red and one blue toy // map to RedBlueExtravaganza .findFirst() .get(); log.info(firstRedBlueList); // now contains redToy1, blueToy1 ``` Thanks for the help!
2019/10/30
[ "https://Stackoverflow.com/questions/58617144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10205830/" ]
Here's a solution which traverses your list only once, giving you the first red and blue toys at the end. We can filter out all the other irrelevent colors and then create a map whose key is whether the toy is red and the value is the first toy matching the given criteria. Here's how it looks. ``` Map<Boolean, Toy> firstRedAndBlueToysMap = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .collect(Collectors.toMap(Toy::isRed, t -> t, (a, b) -> a)); Toy firstRedToy = firstRedAndBlueToysMap.get(true); Toy firstBlueToy = firstRedAndBlueToysMap.get(false); ``` And here's a one step approach to solve your problem. ``` RedBlueExtravaganza firstRedAndBlueToyPair = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .collect(Collectors.collectingAndThen(Collectors.toMap(Toy::isRed, t -> t, (a, b) -> a), m -> new RedBlueExtravaganza(m.get(true), m.get(false)))); ``` P.S. For this to work you need to have the following constructor in your `RedBlueExtravaganza` class contrary to the one you have provided above. ``` public RedBlueExtravaganza(Toy rt, Toy bt) { if (!(rt instanceof RedToy) || !(bt instanceof BlueToy)) throw new IllegalArgumentException(); // remainder omitted. } ```
I like [this answers](https://stackoverflow.com/a/58618100/11733759), similar solution can be with reduce and List as "Tuple (or something)" ```java List<Toy> reduceToList = toyList.stream() .filter(t -> t.isBlue() || t.isRed()) .map(t -> Arrays.asList(t, t)) .reduce(Arrays.asList(null, null), (a, c) -> a.get(0) == null && c.get(0).isRed() ? Arrays.asList(c.get(0), a.get(1)) : (a.get(1) == null && c.get(1).isBlue() ? Arrays.asList(a.get(0), c.get(1)) : a) ); ``` If both values are not null then you can map to `RedBlueExtravaganza`
66,539,704
I have been trying to solve this problem since yesterday. The program should accept N numbers from the user and will place them in an array. I have done this. However, I don't seem to know how to "warn" the user that the input is a duplicate and lets the user enter again. Here is my code: ``` # include <iostream> using namespace std; int main () { int N, pos = -1, arr [N], i, j; int startLoop = 1; // the 'startLoop' variable is used so that the first user input can have the break function bool found = false; while (startLoop != 0) { cout << "Enter the number of integers to be entered: "; cin >> N; if (N <= 4) { cout << "Invalid. \n"; } if (N > 4) { cout << "\n\nEnter " << N << " unique numbers: " ; for (i = 0; i < N; i++) { cin >> arr [i]; for (j = 0; j < N && !found; j++) { if (arr [j] == arr [i]) { found = true; cout << "Enter again: "; } } break; } } } ```
2021/03/09
[ "https://Stackoverflow.com/questions/66539704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13634556/" ]
You need to force b2 to where master is. If you are on master at the moment: ``` git branch -f b2 ``` That will do.
Just try: ``` git checkout b2 git reset --hard master ```
67,834,792
I have a model structured like so: ``` public int JobID { get; set; } public int SiteID { get; set; } public List<AModel> ListAModel { get; set; } ``` In my main view, I am iterating through the List using a for loop with i as an index. I want to call a partial view from within this main page to avoid repeat code across the system but this partial view needs to be aware of the index number as well as the job id and site id. I cannot just pass in in Model.ListAModel[i] as this will not be aware of job or site id, and likewise with the other way round. Any help would be appreciated.
2021/06/04
[ "https://Stackoverflow.com/questions/67834792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7728486/" ]
As @SOS touches on in their comment (not sure why they did not make it an "answer"?), the issue is not the conversion. The issue is that ColdFusion is displaying `69.35 * 100` as equalling `6935`, which it isn't. And even ColdFusion doesn't really think it is. As far as most computing languages are concerned, `69.35 * 100` is `6934.999999999999` (check on JS, Python, Ruby etc if you like), due to issues with the inherent inaccuracy of representing decimal fractional values in a system that stores stuff in binary. I've written about this before: [Floating point arithmetic with decimals](https://blog.adamcameron.me/2016/01/floating-point-arithmetic-with-decimals.html). Internally ColdFusion is storing the result as `6934.999999999999`: ``` <cfset f = 69.35 * 100> <cfoutput>#f.toString()#</cfoutput> ``` This yields: ``` 6934.999999999999 ``` So when you use `int` to take the integer portion of `6934.999999999999`, you get `6934`. *That part* is actually doing the job correctly! ;-)
I know I'm kind of late to the game with this answer, but here's what I've used in the past when encountering precision issues in ColdFusion when dealing with mathematical calculations using currency. In order to avoid precision errors, I've always wrapped my mathematical calculations with the `precisionEvaluate()` function. Using it with your sample code ``` <cfoutput> <cfset a = 69.35> #getMetadata(a)# #a#</br> <cfset b = precisionEvaluate(a * 100)> #getMetadata(b)# #b#</br> <cfset c = int(b)> #getMetadata(c)# #c#</br> </cfoutput> ``` The resultant output looks like this. As you can see, it converts it from a Double to a BigDecimal and it avoids the precision issues. ``` class coldfusion.runtime.CFDouble 69.35 class java.math.BigDecimal 6935.00 class java.lang.Long 6935 ``` You can view the results [here](https://cffiddle.org/app/file?filepath=a0d18eca-d58c-45ac-8d91-66ac81281516/e57ffe82-0c61-4daf-b010-2068753d5e82/4c949e10-637b-49b0-93d4-6e31009a7182.cfm).
19,052,347
I run a script with the param `-A AA/BB` . To get an array with AA and BB, i can do this. ``` INPUT_PARAM=(${AIRLINE_OPTION//-A / }) #get rid of the '-A ' in the begining LIST=(${AIRLINES_PARAM//\// }) # split by '/' ``` Can we achieve this in a single line? Thanks in advance.
2013/09/27
[ "https://Stackoverflow.com/questions/19052347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494659/" ]
One way ``` IFS=/ read -r -a LIST <<< "${AIRLINE_OPTION//-A /}" ``` This places the output from the parameter substitution `${AIRLINE_OPTION//-A /}` into a "here-string" and uses the bash `read` built-in to parse this into an array. Splitting by `/` is achieved by setting the value of `IFS` to `/` for the `read` command.
With `awk`, for example, you can create an array and store it in `LIST` variable: ``` $ LIST=($(awk -F"[\/ ]" '{print $2,$3}' <<< "-A AA/BB")) ``` Result: ``` $ echo ${LIST[0]} AA $ echo ${LIST[1]} BB ``` ### Explanation * `-F"[\/ ]"` defines two possible field separators: a space or a slash `/`. * `'{print $2$3}'` prints the 2nd and 3rd fields based on those separators.
19,052,347
I run a script with the param `-A AA/BB` . To get an array with AA and BB, i can do this. ``` INPUT_PARAM=(${AIRLINE_OPTION//-A / }) #get rid of the '-A ' in the begining LIST=(${AIRLINES_PARAM//\// }) # split by '/' ``` Can we achieve this in a single line? Thanks in advance.
2013/09/27
[ "https://Stackoverflow.com/questions/19052347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494659/" ]
One way ``` IFS=/ read -r -a LIST <<< "${AIRLINE_OPTION//-A /}" ``` This places the output from the parameter substitution `${AIRLINE_OPTION//-A /}` into a "here-string" and uses the bash `read` built-in to parse this into an array. Splitting by `/` is achieved by setting the value of `IFS` to `/` for the `read` command.
``` LIST=( $(IFS=/; for x in ${AIRLINE_OPTION#-A }; do printf "$x "; done) ) ``` This is a portable solution, but if your `read` supports `-a` and you don't mind portability then you should go for @1\_CR's solution.
45,142,355
I have this html file: ``` <!DOCTYPE html> <html> <head> <meta name="viewport" content="width = device-width"> <meta name="description" content="Some training on web design"> <meta name="keywords" content="web, design"> <meta name="author" content="Houssem badri"> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css"> <script src="js/script.js"></script> <title>My Web design | Welcome</title> </head> <body> <header> <div class="branding"> <h1>Some title</h1> </div> <nav> <ul> <li><a href="#">Contact us</a></li> <li><a href="#">About us</a></li> <li><a href="#">Services</a></li> <li><a class="current" href="#">Home</a></li> </ul> </nav> </header> <div class="left-col"> <section> <article> <h1>My first article</h1> <p>Some Text</p> </article> <article> <h1>My Second article</h1> <p>Some Text</p> </article> </section> </div> <div class="mid-col"> <section> <h1> Main section title </h1> <p>Some Text</p> </section> </div> <aside role="complementary"> <h1>Aside title</h1> <p> Some text </p> </aside> <footer> <h4>Copyright&copy <a href="#">blabla.com</a></h4> </footer> </body> </html> ``` And this css styling file: ``` /* Global */ body{ background: #E1F9A8; font-family: "Arial"; font-size: 16px; width: 80%; margin: auto; overflow: hidden; padding-bottom:60px; } ul{ margin:0; padding:0; } /* Header */ header{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; min-height: 75px; padding-top:30px; margin-top: 20px; } header nav{ margin-top:10px; } header li{ float: right; padding: 0 10px 10px 0; display: inline; } header a { text-decoration: none; text-transform: uppercase; color: #226B90; font-weight: bold; } header .branding{ float: left; margin: 0 0 35px 10px; /* Some design */ text-shadow: 1px 1px 2px orange; } header .branding h1{ margin:0; } header .current, header a:hover{ color: #C48B19; text-shadow: 1px 1px 2px orange; } /* Left side */ .left-col { width: 26%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; margin-right: 12px; } .left-col h1{ padding-left: 10px; } .left-col p{ padding-left: 10px; } .left-col i{ padding-left: 10px; } .left-col .read-more{ color: #C48B19; text-shadow: 1px 1px 2px orange; float: right; text-decoration: none; } /* Right side */ aside{ width: 25%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; } aside h1{ padding-left: 10px; } aside form{ padding: 0 10px 10px 10px; } /* Main section */ .mid-col{ width: 46%; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; float: left; margin-right: 12px; } .mid-col h1, .mid-col h2, .mid-col img, .mid-col p{ padding-left: 10px; } .mid-col img{ width: 96%; } /* footer */ footer{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding:20px; margin:20px 0 0 20px; } ``` When I see the output, I get this overlapping. I didn't catch how to fix it. I think I have bad restructured my html 5 page. [![enter image description here](https://i.stack.imgur.com/WrPJV.png)](https://i.stack.imgur.com/WrPJV.png)
2017/07/17
[ "https://Stackoverflow.com/questions/45142355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807373/" ]
Add `clear: both` to the footer's CSS (you need that because of the floating elements above it) And erase `overflow: hidden` from the `body` tag. ```css body{ background: #E1F9A8; font-family: "Arial"; font-size: 16px; width: 80%; margin: auto; padding-bottom:60px; } ul{ margin:0; padding:0; } /* Header */ header{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; min-height: 75px; padding-top:30px; margin-top: 20px; } header nav{ margin-top:10px; } header li{ float: right; padding: 0 10px 10px 0; display: inline; } header a { text-decoration: none; text-transform: uppercase; color: #226B90; font-weight: bold; } header .branding{ float: left; margin: 0 0 35px 10px; /* Some design */ text-shadow: 1px 1px 2px orange; } header .branding h1{ margin:0; } header .current, header a:hover{ color: #C48B19; text-shadow: 1px 1px 2px orange; } /* Left side */ .left-col { width: 26%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; margin-right: 12px; } .left-col h1{ padding-left: 10px; } .left-col p{ padding-left: 10px; } .left-col i{ padding-left: 10px; } .left-col .read-more{ color: #C48B19; text-shadow: 1px 1px 2px orange; float: right; text-decoration: none; } /* Right side */ aside{ width: 25%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; } aside h1{ padding-left: 10px; } aside form{ padding: 0 10px 10px 10px; } /* Main section */ .mid-col{ width: 46%; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; float: left; margin-right: 12px; } .mid-col h1, .mid-col h2, .mid-col img, .mid-col p{ padding-left: 10px; } .mid-col img{ width: 96%; } /* footer */ footer{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding:20px; margin:20px 0 0 20px; clear: both; } ``` ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width = device-width"> <meta name="description" content="Some training on web design"> <meta name="keywords" content="web, design"> <meta name="author" content="Houssem badri"> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css"> <script src="js/script.js"></script> <title>My Web design | Welcome</title> </head> <body> <header> <div class="branding"> <h1>Some title</h1> </div> <nav> <ul> <li><a href="#">Contact us</a></li> <li><a href="#">About us</a></li> <li><a href="#">Services</a></li> <li><a class="current" href="#">Home</a></li> </ul> </nav> </header> <div class="left-col"> <section> <article> <h1>My first article</h1> <p>Some Text</p> </article> <article> <h1>My Second article</h1> <p>Some Text</p> </article> </section> </div> <div class="mid-col"> <section> <h1> Main section title </h1> <p>Some Text</p> </section> </div> <aside role="complementary"> <h1>Aside title</h1> <p> Some text </p> </aside> <footer> <h4>Copyright&copy <a href="#">blabla.com</a></h4> </footer> </body> </html> ```
i have tried your code, everything is correct what you done, but you need to add a small code in footer css part check the below css footer code ``` <!-- css --> <style> footer { border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding: 20px; margin: 15px 0 0 0px; clear: both; } </style> ```
45,142,355
I have this html file: ``` <!DOCTYPE html> <html> <head> <meta name="viewport" content="width = device-width"> <meta name="description" content="Some training on web design"> <meta name="keywords" content="web, design"> <meta name="author" content="Houssem badri"> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css"> <script src="js/script.js"></script> <title>My Web design | Welcome</title> </head> <body> <header> <div class="branding"> <h1>Some title</h1> </div> <nav> <ul> <li><a href="#">Contact us</a></li> <li><a href="#">About us</a></li> <li><a href="#">Services</a></li> <li><a class="current" href="#">Home</a></li> </ul> </nav> </header> <div class="left-col"> <section> <article> <h1>My first article</h1> <p>Some Text</p> </article> <article> <h1>My Second article</h1> <p>Some Text</p> </article> </section> </div> <div class="mid-col"> <section> <h1> Main section title </h1> <p>Some Text</p> </section> </div> <aside role="complementary"> <h1>Aside title</h1> <p> Some text </p> </aside> <footer> <h4>Copyright&copy <a href="#">blabla.com</a></h4> </footer> </body> </html> ``` And this css styling file: ``` /* Global */ body{ background: #E1F9A8; font-family: "Arial"; font-size: 16px; width: 80%; margin: auto; overflow: hidden; padding-bottom:60px; } ul{ margin:0; padding:0; } /* Header */ header{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; min-height: 75px; padding-top:30px; margin-top: 20px; } header nav{ margin-top:10px; } header li{ float: right; padding: 0 10px 10px 0; display: inline; } header a { text-decoration: none; text-transform: uppercase; color: #226B90; font-weight: bold; } header .branding{ float: left; margin: 0 0 35px 10px; /* Some design */ text-shadow: 1px 1px 2px orange; } header .branding h1{ margin:0; } header .current, header a:hover{ color: #C48B19; text-shadow: 1px 1px 2px orange; } /* Left side */ .left-col { width: 26%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; margin-right: 12px; } .left-col h1{ padding-left: 10px; } .left-col p{ padding-left: 10px; } .left-col i{ padding-left: 10px; } .left-col .read-more{ color: #C48B19; text-shadow: 1px 1px 2px orange; float: right; text-decoration: none; } /* Right side */ aside{ width: 25%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; } aside h1{ padding-left: 10px; } aside form{ padding: 0 10px 10px 10px; } /* Main section */ .mid-col{ width: 46%; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; float: left; margin-right: 12px; } .mid-col h1, .mid-col h2, .mid-col img, .mid-col p{ padding-left: 10px; } .mid-col img{ width: 96%; } /* footer */ footer{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding:20px; margin:20px 0 0 20px; } ``` When I see the output, I get this overlapping. I didn't catch how to fix it. I think I have bad restructured my html 5 page. [![enter image description here](https://i.stack.imgur.com/WrPJV.png)](https://i.stack.imgur.com/WrPJV.png)
2017/07/17
[ "https://Stackoverflow.com/questions/45142355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807373/" ]
Define a class called `clearfix` with css as provided in snippet which will clear the ends. Where ever you have floating child divs, give this to the parent div ```css body{ background: #E1F9A8; font-family: "Arial"; font-size: 16px; width: 80%; margin: auto; overflow: hidden; padding-bottom:60px; } ul{ margin:0; padding:0; } /* Header */ header{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; min-height: 75px; padding-top:30px; margin-top: 20px; } header nav{ margin-top:10px; } header li{ float: right; padding: 0 10px 10px 0; display: inline; } header a { text-decoration: none; text-transform: uppercase; color: #226B90; font-weight: bold; } header .branding{ float: left; margin: 0 0 35px 10px; /* Some design */ text-shadow: 1px 1px 2px orange; } header .branding h1{ margin:0; } header .current, header a:hover{ color: #C48B19; text-shadow: 1px 1px 2px orange; } /* Left side */ .left-col { width: 26%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; margin-right: 12px; } .left-col h1{ padding-left: 10px; } .left-col p{ padding-left: 10px; } .left-col i{ padding-left: 10px; } .left-col .read-more{ color: #C48B19; text-shadow: 1px 1px 2px orange; float: right; text-decoration: none; } /* Right side */ aside{ width: 25%; float: left; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; } aside h1{ padding-left: 10px; } aside form{ padding: 0 10px 10px 10px; } /* Main section */ .mid-col{ width: 46%; border: 1px solid; border-radius: 10px; overflow: hidden; margin-top: 10px; background-color: #FAF8F3; float: left; margin-right: 12px; } .mid-col h1, .mid-col h2, .mid-col img, .mid-col p{ padding-left: 10px; } .mid-col img{ width: 96%; } /* footer */ footer{ border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding:20px; margin:20px 0 0 20px; } .clearfix:before, .clearfix:after { display: table; content: " "; } .clearfix:after { clear: both; } ``` ```html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width = device-width"> <meta name="description" content="Some training on web design"> <meta name="keywords" content="web, design"> <meta name="author" content="Houssem badri"> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css"> <script src="js/script.js"></script> <title>My Web design | Welcome</title> </head> <body> <header> <div class="branding"> <h1>Some title</h1> </div> <nav> <ul> <li><a href="#">Contact us</a></li> <li><a href="#">About us</a></li> <li><a href="#">Services</a></li> <li><a class="current" href="#">Home</a></li> </ul> </nav> </header> <div class="clearfix"> <div class="left-col"> <section> <article> <h1>My first article</h1> <p>Some Text</p> </article> <article> <h1>My Second article</h1> <p>Some Text</p> </article> </section> </div> <div class="mid-col"> <section> <h1> Main section title </h1> <p>Some Text</p> </section> </div> <aside role="complementary"> <h1>Aside title</h1> <p> Some text </p> </aside> </div> <footer> <h4>Copyright&copy <a href="#">blabla.com</a></h4> </footer> </body> </html> ```
i have tried your code, everything is correct what you done, but you need to add a small code in footer css part check the below css footer code ``` <!-- css --> <style> footer { border: 1px solid; border-radius: 10px; background-color: #D0D8BE; padding: 20px; margin: 15px 0 0 0px; clear: both; } </style> ```
7,363,077
I am trying to get no. of recent unread mails from a gmail account.For this I have installed IMAP in my Ubuntu system and tried some PHP iMAP functions. Here are what i have tried till now. ``` /* connect to gmail */ $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = 'user@gmail.com'; $password = 'user_password'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error()); ``` Now I am stating all my attempts. NB - I have tried each attempt by sending new mails to the testing email id Attempt\_1: Using imap\_search() ``` $recent_emails = imap_search($inbox,'RECENT'); if ($recent_emails) echo count($recent_emails); else echo "false return"; imap_close($inbox); ``` Now Output of Attempt\_1 is "false return"; Attempt\_2: Using imap\_mailboxmsginfo() ``` $check = imap_mailboxmsginfo($inbox); if ($check) echo "Recent: " . $check->Recent . "<br />\n" ; else echo "imap_check() failed: " . imap_last_error() . "<br />\n"; imap_close($inbox); ``` Here the output is Recent:0 while I have sent 2 new mails to this id Attempt\_3: using imap\_status() ``` $status = imap_status($inbox, $hostname, SA_ALL); if ($status) echo "Recent: " . $status->recent . "<br />\n"; else echo "imap_status failed: " . imap_last_error() . "\n"; ``` //Output Recent:0 Attempt\_4: Using Using imap\_search() Again with parameter NEW ``` $recent_emails = imap_search($inbox,'NEW'); if ($recent_emails) echo count($recent_emails); else echo "false return"; imap_close($inbox); ``` Output - false return So Where Am I WRONG? How can I get the recent unread emails count?
2011/09/09
[ "https://Stackoverflow.com/questions/7363077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936786/" ]
This function seems to work: ``` function CountUnreadMail($host, $login, $passwd) { $mbox = imap_open($host, $login, $passwd); $count = 0; if (!$mbox) { echo "Error"; } else { $headers = imap_headers($mbox); foreach ($headers as $mail) { $flags = substr($mail, 0, 4); $isunr = (strpos($flags, "U") !== false); if ($isunr) $count++; } } imap_close($mbox); return $count; } ``` **Usage:** ``` $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = 'user@gmail.com'; $password = 'user_password'; $count = CountUnreadMail($hostname, $username, $password); ``` I can’t claim full credit for this function. It’s a slightly edited version of sdolgy’s answer to [PHP Displaying unread mail count](https://stackoverflow.com/q/6707581/911182). His version assumed POP mail. This version requires the full `$hostname`. I tested it with my own gmail account and it correctly reported the number of *unread* messages I had in my inbox. [PHP Displaying unread mail count](https://stackoverflow.com/q/6707581/911182) has some pretty good reading material. Check it out. Hope this helps. **UPDATE** From: [Does Gmail support all IMAP features?](http://mail.google.com/support/bin/answer.py?hl=en&answer=78761 "GMail Support Questions") > > Gmail IMAP1 is a fairly complete implementation of IMAP, but the > following features are currently unsupported: > > > > ``` > \Recent flags on messages. > > ``` > > Verfied at: [Gmail's Buggy IMAP Implementation](http://weblog.timaltman.com/archive/2008/02/24/gmails-buggy-imap-implementation "The Good Life... a weblog about life, technology, and the Opera Web browser") > > Gmail doesn't handle standard IMAP flags, such as "\Deleted", > "\Answered", and "\Recent". > > > **See also:** [Jyoti Ranjan's answer](https://stackoverflow.com/a/7441374/911182) (below) for a possible solution.
I have solved it using database,This is how I have done it. 1.I made a column in users table, for ex- 'email\_max\_uid' INT(11) NOT NULL default 0 2.When a user loads this page first, using my sql query I retrieved the value of 'email\_max\_uid' of that particular users 3.connect to his gmail account automatically and got the unread mails and total mails ``` $inbox = imap_open('{imap.gmail.com:993/imap/ssl}INBOX','user's email id','user's password') or die('Cannot connect to Gmail: ' . imap_last_error()); $unread_emails = imap_search($inbox,'UNSEEN'); $emails = imap_search($inbox,'ALL', SE_UID); ``` 4.Then ``` if ('email_max_uid') = 0 $recent_mails_count = count($unread_emails); else $recent_mails_count = max($emails) - Array['email_max_uid']; ``` 5.Show the recent mails count ``` echo count($recent_mails_count); ``` 6.I have put a link which makes the user log in to his gmail account without asking his email id and password When the users log in to his account, `email_max_uid is updated with count($emails)` 1. Now again when the users visits that page, it follows the above proceedure and his no. of recent emails will be displayed on the page. \*My solution is for the case where a user can log in to his gmail account only through this application, if he logs into his account from outside, the database wont be updated so that wrong no. of mail counts will be shown.In my problem case, user even doesn't know his gmail id and password provided by the company to see only their mails. So he cant log in to his this account from outside. That's why this solution works. This is how I solved it 3 days ago.Sorry for late reply
446,341
I have this zpool: ``` bash-3.2# zpool status dpool pool: dpool state: ONLINE scan: none requested config: NAME STATE READ WRITE CKSUM dpool ONLINE 0 0 0 c3t600601604F021A009E1F867A3E24E211d0 ONLINE 0 0 0 c3t600601604F021A00141D843A3F24E211d0 ONLINE 0 0 0 ``` I would like to replace both of these disks with a single (larger disk). Can it be done? **zpool attach** allows me to replace one physical disk, but it won't allow me to replace both at once.
2012/11/07
[ "https://serverfault.com/questions/446341", "https://serverfault.com", "https://serverfault.com/users/5756/" ]
No, I don't think this is possible in the manner you're describing. You *can*, however, create a new pool with the single disk and copy your ZFS filesystems to the new pool using a simple [zfs send/receive](http://docs.oracle.com/cd/E19963-01/html/821-1448/gbchx.html) process.
You should be able to `zpool attach` the new and larger drive, wait for the mirroring to be completed, and then `zpool detach` the old drives. *Edit*: I had misread your question, and I was quite sure that you were running them as a mirror. I agree that the best course of action is to create a new pool and recursively send all datasets to the new pool, but if you really cannot do that, then you could still follow the steps I'm outlining, provided that you partition the new, larger disk, into two partitions, each as least as large as the disk that it is meant to replace. I recommend against this, mainly because (1) management becomes more complex, and (2) you won't be able to take advantage of the drive's write cache. I'll paste here the sequence as performed on a recent Illumos box. Please note that I'm creating empty files to show this, instead of using whole disks and slices/partitions, as I can't juggle physical devices on that box. The files are named `aa1`, `aa2` and `aa3`. 1. Prepare the devices. `aa3` is 200M large, while `aa1` and `aa2` are 100M only: ``` # dd if=/dev/zero of=/opt/local/aa1 bs=1M count=100 # dd if=/dev/zero of=/opt/local/aa2 bs=1M count=100 # dd if=/dev/zero of=/opt/local/aa3 bs=1M count=200 ``` 2. Create our test pool: ``` # zpool create test mirror /opt/local/aa1 /opt/local/aa2 ``` Check that everything went smoothly: ``` # zpool list -v test NAME SIZE ALLOC FREE EXPANDSZ CAP DEDUP HEALTH ALTROOT test 95,5M 106K 95,4M - 0% 1.00x ONLINE - mirror 95,5M 106K 95,4M - /opt/local/aa1 - - - - /opt/local/aa2 - - - - ``` 3. Set the `autoexpand` property: ``` # zpool set autoexpand=on test ``` 4. Attach the new device: ``` # zpool attach test /opt/local/aa2 /opt/local/aa3 ``` Is everything still fine? ``` # zpool list -v test NAME SIZE ALLOC FREE EXPANDSZ CAP DEDUP HEALTH ALTROOT test 95,5M 120K 95,4M - 0% 1.00x ONLINE - mirror 95,5M 120K 95,4M - /opt/local/aa1 - - - - /opt/local/aa2 - - - - /opt/local/aa3 - - - - ``` Yes, it is. 5. Detach the first two devs: ``` # zpool detach test /opt/local/aa1 # zpool detach test /opt/local/aa2 ``` Finally, let's check the pool again: ``` # zpool list -v test NAME SIZE ALLOC FREE EXPANDSZ CAP DEDUP HEALTH ALTROOT test 196M 124K 195M - 0% 1.00x ONLINE - /opt/local/aa3 196M 124K 195M - ``` It has correctly grown to 200MB.
32,351,138
The following code replaces an anchor element with an inputbox and assigns an ID to it. I'd also like to assign an onblur event to it, but can't get it working. `newElement.onblur = texOnBlur(this));` All help is welcome. ``` function replaceElement(e) { selectedElement = e.id var newElement = document.createElement("input"); newElement.setAttribute("id", selectedElement); newElement.onblur = texOnBlur(this)); newElement.value = document.getElementById(selectedElement).innerHTML; var oldElement = document.getElementById(selectedElement); var parentDiv = oldElement.parentNode parentDiv.replaceChild(newElement, oldElement); document.getElementById(selectedElement).style.width = "45px"; document.getElementById(selectedElement).style.height = "12px"; } ```
2015/09/02
[ "https://Stackoverflow.com/questions/32351138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018622/" ]
As you can see <http://www.w3schools.com/jsref/event_onblur.asp> ``` object.onblur=function(){myScript}; ``` you should assign a function to `.onblur` event, you assigned function result.
try this one ``` newElement.addEventListener("blur", function(){ // do stuff texOnBlur(this); alert("Done"); }); ```
32,351,138
The following code replaces an anchor element with an inputbox and assigns an ID to it. I'd also like to assign an onblur event to it, but can't get it working. `newElement.onblur = texOnBlur(this));` All help is welcome. ``` function replaceElement(e) { selectedElement = e.id var newElement = document.createElement("input"); newElement.setAttribute("id", selectedElement); newElement.onblur = texOnBlur(this)); newElement.value = document.getElementById(selectedElement).innerHTML; var oldElement = document.getElementById(selectedElement); var parentDiv = oldElement.parentNode parentDiv.replaceChild(newElement, oldElement); document.getElementById(selectedElement).style.width = "45px"; document.getElementById(selectedElement).style.height = "12px"; } ```
2015/09/02
[ "https://Stackoverflow.com/questions/32351138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5018622/" ]
As you can see <http://www.w3schools.com/jsref/event_onblur.asp> ``` object.onblur=function(){myScript}; ``` you should assign a function to `.onblur` event, you assigned function result.
You are currently referencing the result of the `textOnBlur` function instead of the function itself. You should write : ``` newElement.onblur = textOnBlur; ``` `this` should refer to the input element inside the `textOnBlur` function automatically.
33,603,250
`Add-AzureRmAccount` or the alias `Login-AzureRmAccount` doesn't seem to persist between sessions the way that `Add-AzureAccount` does. Is there a way to get it to persist?
2015/11/09
[ "https://Stackoverflow.com/questions/33603250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82993/" ]
After adding the account to your session (either `Add-AzureRmAccount` or `Login-AzureRmAccount`,) use ``` Save-AzureRmProfile -Path <path-to-file> ``` to save the current credentials and ``` Select-AzureRmProfile -Path <path-to-file> ``` to load them. [Thanks to Mark Cowlishaw](https://github.com/Azure/azure-powershell/issues/1272#issuecomment-155608348)
Not yet, not in the way you're used to... It's a known issue, but I couldn't find it in the list. Feel free to add it to: <https://github.com/Azure/azure-powershell/issues>
187,172
I got this quote from a customer service email explaining why my order is being delayed: ...."Hence we request your patience in this regards."... This reads weird to me, is this a common phrase? Shouldn't the customer service be hoping/asking for my patience instead of "requesting" my patience, since they are causing my delay?
2018/11/30
[ "https://ell.stackexchange.com/questions/187172", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
> > Hence we request your patience in this regard > > > (it should normally be "regard" singular) means "We ask that you be patient about this issue". The tone here is both formal and old-fashioned, particularly "hence" which means "therefore". Really this phrase means "we are sorry that you must wait".
*Asking* for would be more polite but the difference is minor in my opinion. There are many such phrases in business letters to explain their lateness or offer to excuse your lateness with a bill, say. The language can slowly become more urgent and less patient with each notice. If English is their first language it may be that they had not thought long about what words to use for this particular letter.
65,379,652
I'm trying to develop a GUI in python for analyze tRNA-Seq data which could be run in Linux and Windows. For this it is needed run some programs like: bowtie2, samtools or bedtools, which can be downloaded by anaconda easily on Linux but is a headache on Windows. This programs can't be downloaded on Windows so I had to install Windows Subsystem for Linux (WSL) and tried to downloaded by this way. I have developed the following python script (anaconda\_setup.py) for doing this: ``` import os #Download the file for Linux, altough this script will run only on Windows Subsystem for Linux os.system('curl -O https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_64.sh') #Checking the integrity of the file os.system('sha256sum Anaconda3-2020.07-Linux-x86_64.sh') #Running the .sh script os.system('bash Anaconda3-2020.07-Linux-x86_64.sh') #Compiling from source os.system('source ~/.bashrc') os.system('Anaconda3-2020.07-Linux-x86_64.sh') #Using conda to install bowtie2, samtools and bedtools os.system('conda install -c bioconda bowtie2') os.system('conda install -c bioconda samtools') os.system('conda install -c bioconda bedtools') ``` And then I use the following code in the main script for call the other script: ``` import os ... os.system("wsl python3 anaconda_setup.py") ``` With this anaconda is installed correctly, but I'm not sure if it is installed on windows or in WSL. But I obtained the next error: sh: 1: source: not found sh: 1: conda: not found sh: 1: conda: not found sh: 1: conda: not found On the other hand I have entered to WSL from CMD and I can run conda.exe and conda manually, but I can't do it in an automatically way. Moreover from CMD I can't run: "wsl conda" (error: /bin/bash: conda: command not found) but I can run wsl conda.exe without anyproblem. Any idea what I'm doing wrong or how can I fix this? Thank you very much.
2020/12/20
[ "https://Stackoverflow.com/questions/65379652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14802400/" ]
In order to really be `O(logN)`, the updates to the bounding indeces `minInd,maxInd` should only ever be ``` maxInd = midInd [- 1] minInd = midInd [+ 1] ``` to half the search space. Since there are paths through your loop body that only do ``` minInd += 1 maxInd -= 1 ``` respectively, I am not sure that you can't create data for which your function is linear. The following is a bit simpler and guaranteed `O(logN)` ``` def x(A): if len(A) < 3: return False minInd, maxInd = 0, len(A)-1 mn, mx = A[minInd], A[maxInd] while minInd < maxInd: midInd = (minInd + maxInd) // 2 if mn != A[midInd] != mx: return True if A[midInd] == mn: minInd = midInd + 1 # minInd == midInd might occur else: maxInd = midInd # while maxInd != midInd is safe return False ``` BTW, if you can use the standard library, it is as easy as: ``` from bisect import bisect_right def x(A): return A and (i := bisect_right(A, A[0])) < len(A) and A[i] < A[-1] ```
Yes, there is a better approach. As the list is sorted, you can use binary search with slight custom modifications as follows: ``` list = [1, 1, 1, 2, 2] uniqueElementSet = set([]) def binary_search(minIndex, maxIndex, n): if(len(uniqueElementSet)>=3): return #Checking the bounds for index: if(minIndex<0 or minIndex>=n or maxIndex<0 or maxIndex>=n): return if(minIndex > maxIndex): return if(minIndex == maxIndex): uniqueElementSet.add(list[minIndex]) return if(list[minIndex] == list[maxIndex]): uniqueElementSet.add(list[minIndex]) return uniqueElementSet.add(list[minIndex]) uniqueElementSet.add(list[maxIndex]) midIndex = (minIndex + maxIndex)//2 binary_search(minIndex+1, midIndex, n) binary_search(midIndex+1, maxIndex-1, n) return binary_search(0, len(list)-1, len(list)) print(True if len(uniqueElementSet)>=3 else False) ``` As, we are dividing the array into 2 parts in each iteration of the recursion, it will require maximum of log(n) steps to check if it contains 3 unique elements. **Time Complexity = O(log(n)).**
65,379,652
I'm trying to develop a GUI in python for analyze tRNA-Seq data which could be run in Linux and Windows. For this it is needed run some programs like: bowtie2, samtools or bedtools, which can be downloaded by anaconda easily on Linux but is a headache on Windows. This programs can't be downloaded on Windows so I had to install Windows Subsystem for Linux (WSL) and tried to downloaded by this way. I have developed the following python script (anaconda\_setup.py) for doing this: ``` import os #Download the file for Linux, altough this script will run only on Windows Subsystem for Linux os.system('curl -O https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_64.sh') #Checking the integrity of the file os.system('sha256sum Anaconda3-2020.07-Linux-x86_64.sh') #Running the .sh script os.system('bash Anaconda3-2020.07-Linux-x86_64.sh') #Compiling from source os.system('source ~/.bashrc') os.system('Anaconda3-2020.07-Linux-x86_64.sh') #Using conda to install bowtie2, samtools and bedtools os.system('conda install -c bioconda bowtie2') os.system('conda install -c bioconda samtools') os.system('conda install -c bioconda bedtools') ``` And then I use the following code in the main script for call the other script: ``` import os ... os.system("wsl python3 anaconda_setup.py") ``` With this anaconda is installed correctly, but I'm not sure if it is installed on windows or in WSL. But I obtained the next error: sh: 1: source: not found sh: 1: conda: not found sh: 1: conda: not found sh: 1: conda: not found On the other hand I have entered to WSL from CMD and I can run conda.exe and conda manually, but I can't do it in an automatically way. Moreover from CMD I can't run: "wsl conda" (error: /bin/bash: conda: command not found) but I can run wsl conda.exe without anyproblem. Any idea what I'm doing wrong or how can I fix this? Thank you very much.
2020/12/20
[ "https://Stackoverflow.com/questions/65379652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14802400/" ]
``` from bisect import bisect def hasThreeDistinctElements(A): return A[:1] < A[-1:] > [A[bisect(A, A[0])]] ``` The first comparison safely(\*) checks whether there are two different values at all. If so, we check whether the first value larger than `A[0]` is also smaller than `A[-1]`. (\*): Doesn't crash if `A` is empty. Or without `bisect`, binary-searching for a third value in `A[1:-1]`. The invariant is that if there is any, it must be in `A[lo : hi+1]`: ``` def hasThreeDistinctElements(A): lo, hi = 1, len(A) - 2 while lo <= hi: mid = (lo + hi) // 2 if A[mid] == A[0]: lo = mid + 1 elif A[mid] == A[-1]: hi = mid - 1 else: return True return False ```
Yes, there is a better approach. As the list is sorted, you can use binary search with slight custom modifications as follows: ``` list = [1, 1, 1, 2, 2] uniqueElementSet = set([]) def binary_search(minIndex, maxIndex, n): if(len(uniqueElementSet)>=3): return #Checking the bounds for index: if(minIndex<0 or minIndex>=n or maxIndex<0 or maxIndex>=n): return if(minIndex > maxIndex): return if(minIndex == maxIndex): uniqueElementSet.add(list[minIndex]) return if(list[minIndex] == list[maxIndex]): uniqueElementSet.add(list[minIndex]) return uniqueElementSet.add(list[minIndex]) uniqueElementSet.add(list[maxIndex]) midIndex = (minIndex + maxIndex)//2 binary_search(minIndex+1, midIndex, n) binary_search(midIndex+1, maxIndex-1, n) return binary_search(0, len(list)-1, len(list)) print(True if len(uniqueElementSet)>=3 else False) ``` As, we are dividing the array into 2 parts in each iteration of the recursion, it will require maximum of log(n) steps to check if it contains 3 unique elements. **Time Complexity = O(log(n)).**
65,379,652
I'm trying to develop a GUI in python for analyze tRNA-Seq data which could be run in Linux and Windows. For this it is needed run some programs like: bowtie2, samtools or bedtools, which can be downloaded by anaconda easily on Linux but is a headache on Windows. This programs can't be downloaded on Windows so I had to install Windows Subsystem for Linux (WSL) and tried to downloaded by this way. I have developed the following python script (anaconda\_setup.py) for doing this: ``` import os #Download the file for Linux, altough this script will run only on Windows Subsystem for Linux os.system('curl -O https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_64.sh') #Checking the integrity of the file os.system('sha256sum Anaconda3-2020.07-Linux-x86_64.sh') #Running the .sh script os.system('bash Anaconda3-2020.07-Linux-x86_64.sh') #Compiling from source os.system('source ~/.bashrc') os.system('Anaconda3-2020.07-Linux-x86_64.sh') #Using conda to install bowtie2, samtools and bedtools os.system('conda install -c bioconda bowtie2') os.system('conda install -c bioconda samtools') os.system('conda install -c bioconda bedtools') ``` And then I use the following code in the main script for call the other script: ``` import os ... os.system("wsl python3 anaconda_setup.py") ``` With this anaconda is installed correctly, but I'm not sure if it is installed on windows or in WSL. But I obtained the next error: sh: 1: source: not found sh: 1: conda: not found sh: 1: conda: not found sh: 1: conda: not found On the other hand I have entered to WSL from CMD and I can run conda.exe and conda manually, but I can't do it in an automatically way. Moreover from CMD I can't run: "wsl conda" (error: /bin/bash: conda: command not found) but I can run wsl conda.exe without anyproblem. Any idea what I'm doing wrong or how can I fix this? Thank you very much.
2020/12/20
[ "https://Stackoverflow.com/questions/65379652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14802400/" ]
``` from bisect import bisect def hasThreeDistinctElements(A): return A[:1] < A[-1:] > [A[bisect(A, A[0])]] ``` The first comparison safely(\*) checks whether there are two different values at all. If so, we check whether the first value larger than `A[0]` is also smaller than `A[-1]`. (\*): Doesn't crash if `A` is empty. Or without `bisect`, binary-searching for a third value in `A[1:-1]`. The invariant is that if there is any, it must be in `A[lo : hi+1]`: ``` def hasThreeDistinctElements(A): lo, hi = 1, len(A) - 2 while lo <= hi: mid = (lo + hi) // 2 if A[mid] == A[0]: lo = mid + 1 elif A[mid] == A[-1]: hi = mid - 1 else: return True return False ```
In order to really be `O(logN)`, the updates to the bounding indeces `minInd,maxInd` should only ever be ``` maxInd = midInd [- 1] minInd = midInd [+ 1] ``` to half the search space. Since there are paths through your loop body that only do ``` minInd += 1 maxInd -= 1 ``` respectively, I am not sure that you can't create data for which your function is linear. The following is a bit simpler and guaranteed `O(logN)` ``` def x(A): if len(A) < 3: return False minInd, maxInd = 0, len(A)-1 mn, mx = A[minInd], A[maxInd] while minInd < maxInd: midInd = (minInd + maxInd) // 2 if mn != A[midInd] != mx: return True if A[midInd] == mn: minInd = midInd + 1 # minInd == midInd might occur else: maxInd = midInd # while maxInd != midInd is safe return False ``` BTW, if you can use the standard library, it is as easy as: ``` from bisect import bisect_right def x(A): return A and (i := bisect_right(A, A[0])) < len(A) and A[i] < A[-1] ```
14,925,707
I'd like to right align several text when drawing using Core Graphics. Below is the code I'm using to draw text now. How can I draw several texts that are right aligned? ``` CGContextSelectFont(context, "Helvetica-Light", 10.0f,kCGEncodingMacRoman); CGContextSetTextDrawingMode(context, kCGTextFill); CGContextSetFillColorWithColor(context, _privateColor.CGColor); CGContextShowTextAtPoint(context, point.x, point.y, [text cStringUsingEncoding:NSUTF8StringEncoding], text.length); ```
2013/02/17
[ "https://Stackoverflow.com/questions/14925707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473780/" ]
perhaps you're looking for something like this... ``` [@"Any text what you like to show" drawInRect:CGRectMake(0.f, 0.f, 320.f, 80.f) withFont:[UIFont fontWithName:@"Helvetica-Light" size:10.f] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentRight]; ``` update ====== that way is unfortunately deprecated in iOS7+. [source](https://developer.apple.com/library/ios/documentation/uikit/reference/NSString_UIKit_Additions/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/NSString/drawInRect%3awithFont%3alineBreakMode%3a).
``` [@"your Text" drawInRect:CGRectMake(0.f, 0.f, 320.f, 80.f) withAttributes:"dictionary with text attributes"]; ``` here the attributes refers to text font,text size,alignment etc. Where the alignment can be set using the NSMutableParagraphStyle object with the text i.e.lineBreakMode etc
45,563,414
I am trying to build a chaincode using `go build`. Environment: * installed go 1.8.3 windows/amd * Windows 10 When I run `go build` I get the following error: ``` # github.com/hyperledger/fabric/vendor/github.com/miekg/pkcs11 ..\..\github.com\hyperledger\fabric\vendor\github.com\miekg\pkcs11\pkcs11.go:29:18: fatal error: ltdl.h: No such file or directory compilation terminated. ``` I checked and my GCC installation does not contain the **ltdl.h** file in the *include* folder. I found a SO post with a [solution for Linux](https://stackoverflow.com/questions/43626320/ltdl-h-not-found-error-while-building-chaincode), but not one for Windows. Can someone help?
2017/08/08
[ "https://Stackoverflow.com/questions/45563414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1315125/" ]
On windows you can build without `PKCS` `go build --tags nopkcs11`
Try running the following command ``` sudo apt install libtool libltdl-dev ``` Make sure `go get -u github.com/hyperledger/fabric/core/chaincode/shim` throws no error then `go build` it.
38,420,057
I have a simple code to make Java code compiler ``` import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.tools.*; import java.io.*; import java.util.*; public class Compiler extends JFrame { String loc="D:\\java"; File file=null, dir=null; boolean success; public Compiler() { super("Highlight example"); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) {} setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(1,2)); JTextPane textPane = new JTextPane(); JTextArea debug=new JTextArea(); JButton comp=new JButton("Compile"), browse=new JButton("..."); JTextArea location=new JTextArea(); JPanel right=new JPanel(), up=new JPanel(); up.setLayout(new BorderLayout()); up.add(new JScrollPane(location),"Center"); up.add(browse,"East"); right.setLayout(new BorderLayout(2,1)); right.add(up,BorderLayout.NORTH); right.add(new JScrollPane(textPane), "Center"); right.add(comp,"South"); add(right); add(new JScrollPane(debug)); setSize(800, 400); setVisible(true); browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { success=false; UIManager.put("FileChooser.readOnly", Boolean.TRUE); JFileChooser fc = new JFileChooser(loc); int status = fc.showOpenDialog(new JFrame()); if (status==JFileChooser.APPROVE_OPTION) { debug.setText(""); file = fc.getSelectedFile(); dir = fc.getCurrentDirectory(); try { textPane.read(new FileReader(file), null); } catch(Exception ex) { } } } }); comp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file+"")); String[] option=new String[]{"-g","-parameters"}; Iterable<String> options = Arrays.asList(option); JavaCompiler.CompilationTask task=null; fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir)); task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); success = task.call(); fileManager.close(); // System.out.println("Success: " + success); if(success==true) { debug.setText("Success"); } else { int i=1; for (Diagnostic diagnostic : diagnostics.getDiagnostics()) if(diagnostic.getLineNumber()!=-1) debug.append("Error on line "+diagnostic.getLineNumber()+" in "+ diagnostic+"\n"); } } catch(Exception ex) { } } }); } public static void main(String[]args) { new Compiler(); } } ``` I don't know why compiler can not find previous result of code before. And I have no idea how to fix that. For more details, I made an example : 1. select A.java [![select A.java](https://i.stack.imgur.com/IDgX8.png)](https://i.stack.imgur.com/IDgX8.png) 2. Content of A.java [![result A](https://i.stack.imgur.com/5jIFO.png)](https://i.stack.imgur.com/5jIFO.png) 3. then I have select B.java. look A.java has been compiled with create A.class [![enter image description here](https://i.stack.imgur.com/AjuDK.png)](https://i.stack.imgur.com/AjuDK.png) 4. B.java can not compile because it can not find `class A` [![enter image description here](https://i.stack.imgur.com/ZqsE5.png)](https://i.stack.imgur.com/ZqsE5.png) And also can not find class inside package folder. Here is example 2: [![enter image description here](https://i.stack.imgur.com/VGbFn.png)](https://i.stack.imgur.com/VGbFn.png) `A.java` has been compiled with create folder `<path>\a\b` [![enter image description here](https://i.stack.imgur.com/SdWBU.png)](https://i.stack.imgur.com/SdWBU.png) and access class using import [![enter image description here](https://i.stack.imgur.com/dq9b9.png)](https://i.stack.imgur.com/dq9b9.png) I have some try from : ``` fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir)); ``` to : ``` fileManager.setLocation(javax.tools.StandardLocation.CLASS_PATH, Arrays.asList(dir)); ``` but it's not working
2016/07/17
[ "https://Stackoverflow.com/questions/38420057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539582/" ]
In addition to setting `javax.tools.StandardLocation.CLASS_OUTPUT`, you need to set `javax.tools.StandardLocation.CLASS_PATH` to include the same location where you put the previous output: ``` fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir)); // Set dirClassPath to include dir, and optionally other locations fileManager.setLocation(javax.tools.StandardLocation.CLASS_PATH, Arrays.asList(dirClassPath)); ```
Create jar File of external classes and attach with compiler. ``` List<String> optionList = new ArrayList<String>(); // set compiler's classpath to be same as the runtime's optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path") + getValueFromPropertieFile("jarfile1;jarfile2"))); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); ```
38,420,057
I have a simple code to make Java code compiler ``` import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.tools.*; import java.io.*; import java.util.*; public class Compiler extends JFrame { String loc="D:\\java"; File file=null, dir=null; boolean success; public Compiler() { super("Highlight example"); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception evt) {} setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(1,2)); JTextPane textPane = new JTextPane(); JTextArea debug=new JTextArea(); JButton comp=new JButton("Compile"), browse=new JButton("..."); JTextArea location=new JTextArea(); JPanel right=new JPanel(), up=new JPanel(); up.setLayout(new BorderLayout()); up.add(new JScrollPane(location),"Center"); up.add(browse,"East"); right.setLayout(new BorderLayout(2,1)); right.add(up,BorderLayout.NORTH); right.add(new JScrollPane(textPane), "Center"); right.add(comp,"South"); add(right); add(new JScrollPane(debug)); setSize(800, 400); setVisible(true); browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { success=false; UIManager.put("FileChooser.readOnly", Boolean.TRUE); JFileChooser fc = new JFileChooser(loc); int status = fc.showOpenDialog(new JFrame()); if (status==JFileChooser.APPROVE_OPTION) { debug.setText(""); file = fc.getSelectedFile(); dir = fc.getCurrentDirectory(); try { textPane.read(new FileReader(file), null); } catch(Exception ex) { } } } }); comp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file+"")); String[] option=new String[]{"-g","-parameters"}; Iterable<String> options = Arrays.asList(option); JavaCompiler.CompilationTask task=null; fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir)); task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); success = task.call(); fileManager.close(); // System.out.println("Success: " + success); if(success==true) { debug.setText("Success"); } else { int i=1; for (Diagnostic diagnostic : diagnostics.getDiagnostics()) if(diagnostic.getLineNumber()!=-1) debug.append("Error on line "+diagnostic.getLineNumber()+" in "+ diagnostic+"\n"); } } catch(Exception ex) { } } }); } public static void main(String[]args) { new Compiler(); } } ``` I don't know why compiler can not find previous result of code before. And I have no idea how to fix that. For more details, I made an example : 1. select A.java [![select A.java](https://i.stack.imgur.com/IDgX8.png)](https://i.stack.imgur.com/IDgX8.png) 2. Content of A.java [![result A](https://i.stack.imgur.com/5jIFO.png)](https://i.stack.imgur.com/5jIFO.png) 3. then I have select B.java. look A.java has been compiled with create A.class [![enter image description here](https://i.stack.imgur.com/AjuDK.png)](https://i.stack.imgur.com/AjuDK.png) 4. B.java can not compile because it can not find `class A` [![enter image description here](https://i.stack.imgur.com/ZqsE5.png)](https://i.stack.imgur.com/ZqsE5.png) And also can not find class inside package folder. Here is example 2: [![enter image description here](https://i.stack.imgur.com/VGbFn.png)](https://i.stack.imgur.com/VGbFn.png) `A.java` has been compiled with create folder `<path>\a\b` [![enter image description here](https://i.stack.imgur.com/SdWBU.png)](https://i.stack.imgur.com/SdWBU.png) and access class using import [![enter image description here](https://i.stack.imgur.com/dq9b9.png)](https://i.stack.imgur.com/dq9b9.png) I have some try from : ``` fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir)); ``` to : ``` fileManager.setLocation(javax.tools.StandardLocation.CLASS_PATH, Arrays.asList(dir)); ``` but it's not working
2016/07/17
[ "https://Stackoverflow.com/questions/38420057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539582/" ]
You need to specify the sourcepath directory, your code `String[] option=new String[]{"-g","-parameters"};`, try this `String[] option=new String[]{"-g","-sourcepath", loc};` where `loc` is the root directory for the `B` class. With `A` properly stored inside its own package. I've tried your code, with my modification <http://kurungkurawal.com/gifs/tut-compile.gif>
Create jar File of external classes and attach with compiler. ``` List<String> optionList = new ArrayList<String>(); // set compiler's classpath to be same as the runtime's optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path") + getValueFromPropertieFile("jarfile1;jarfile2"))); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); ```
64,552,799
First file:- ``` <!doctype html> <html> <head> <link rel="stylesheet" href="mexp_css.css"> <title>php_main3_feed</title> </head> <body> <?php if(isset($_POST['submit'])) { $a=$_POST['fname']; $b=$_POST['email']; $c=$_POST['cnum']; setcookie("c1",$a,time()+3600); setcookie("c2",$b,time()+3600); setcookie("c3",$c,time()+3600); } ?> <div> <b> <table border="1"> <form method="POST" action=""> <tbody> <tr> <td> <label> First Name </label> </td> <td> <input type="text" name="fname" placeholder=" First name"> </td> </tr> <tr> <td> <label>Email</label> </td> <td> <input type="text" name="email" placeholder=" example@exampl.com"> </td> </tr> <tr> <td> <label>Contact_no</label> </td> <td> <input type="number" name="cnum" placeholder="9999999999"> </td> </tr> <tr> <tr> <td> <input type="submit" value="Submit" name="submit"> </td> <td> <input type="reset" value="Reset" name="reset"> </td> </tr> </tbody> </form> </table> </b> </div> </body> </html> **Second file** <?php echo "First name:-".$_COOKIE['c_fname']."<br>"; echo "Email:-".$_COOKIE['c_email']."<br>"; echo "Contact number:-".$_COOKIE['c_cnum']."<br>"; ?> ``` Description:- I have set cookie in first file and I want to retrieve them in second file but it displays this error. **Error:-** Notice: Undefined index: c\_fname in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 2 First name:- Notice: Undefined index: c\_email in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 3 Email:- Notice: Undefined index: c\_cnum in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 4 Contact number:-
2020/10/27
[ "https://Stackoverflow.com/questions/64552799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12903710/" ]
The main idea of unit testing is to test units separately. Otherwise, it would be an integration test. In this case, you need to write a separate test suite for `Dependency`, and mock the call to it in `ClassUnderTest`.
If you're writing your unit test suite you probably want to mock it, even more if your dependency is pure logic. Consider the following scenario ``` public class ClassUnderTest { @Autowired private Dependency dependency; public int doSomething(int a, int b) { return dependency.add(a, b) * 2; } } public class Dependency { public int add(int a, int b) { return 0; // bug here! } } ``` In your unit test, you'll have something like ``` @Test void testingClass() { assertThat(classUnderTest.doSomething(2, 2), is(equalTo(8))); } ``` which will fail. However, your class under test is working fine! It's just delegating the task to another class You can avoid this false positives by mocking properly your dependencies ``` @Test void testingClass() { when(dependency.add(any(), any()).thenReturn(10); assertThat(classUnderTest.doSomething(2, 2), is(equalTo(20))); } ```
64,552,799
First file:- ``` <!doctype html> <html> <head> <link rel="stylesheet" href="mexp_css.css"> <title>php_main3_feed</title> </head> <body> <?php if(isset($_POST['submit'])) { $a=$_POST['fname']; $b=$_POST['email']; $c=$_POST['cnum']; setcookie("c1",$a,time()+3600); setcookie("c2",$b,time()+3600); setcookie("c3",$c,time()+3600); } ?> <div> <b> <table border="1"> <form method="POST" action=""> <tbody> <tr> <td> <label> First Name </label> </td> <td> <input type="text" name="fname" placeholder=" First name"> </td> </tr> <tr> <td> <label>Email</label> </td> <td> <input type="text" name="email" placeholder=" example@exampl.com"> </td> </tr> <tr> <td> <label>Contact_no</label> </td> <td> <input type="number" name="cnum" placeholder="9999999999"> </td> </tr> <tr> <tr> <td> <input type="submit" value="Submit" name="submit"> </td> <td> <input type="reset" value="Reset" name="reset"> </td> </tr> </tbody> </form> </table> </b> </div> </body> </html> **Second file** <?php echo "First name:-".$_COOKIE['c_fname']."<br>"; echo "Email:-".$_COOKIE['c_email']."<br>"; echo "Contact number:-".$_COOKIE['c_cnum']."<br>"; ?> ``` Description:- I have set cookie in first file and I want to retrieve them in second file but it displays this error. **Error:-** Notice: Undefined index: c\_fname in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 2 First name:- Notice: Undefined index: c\_email in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 3 Email:- Notice: Undefined index: c\_cnum in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 4 Contact number:-
2020/10/27
[ "https://Stackoverflow.com/questions/64552799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12903710/" ]
The main idea of unit testing is to test units separately. Otherwise, it would be an integration test. In this case, you need to write a separate test suite for `Dependency`, and mock the call to it in `ClassUnderTest`.
You have two separate question. The point of mocking is to not have dependencies in your unit tests creating implicit behavior. You want unit tests to be explicit about the code unit you test to be able to identify regression and also declare your expectation how `ClassUnderTest` behaves in different conditions. Whether you need to cover `Dependency` is a question concerning your coding standards. In general I find if a class is so simple that you ponder whether you need to test it, then usually writing the test should be a none issue and if writing a test is an issue to me that often enough indicates you really should have a test there, given you are unsure precisely because that code region is opaque.
64,552,799
First file:- ``` <!doctype html> <html> <head> <link rel="stylesheet" href="mexp_css.css"> <title>php_main3_feed</title> </head> <body> <?php if(isset($_POST['submit'])) { $a=$_POST['fname']; $b=$_POST['email']; $c=$_POST['cnum']; setcookie("c1",$a,time()+3600); setcookie("c2",$b,time()+3600); setcookie("c3",$c,time()+3600); } ?> <div> <b> <table border="1"> <form method="POST" action=""> <tbody> <tr> <td> <label> First Name </label> </td> <td> <input type="text" name="fname" placeholder=" First name"> </td> </tr> <tr> <td> <label>Email</label> </td> <td> <input type="text" name="email" placeholder=" example@exampl.com"> </td> </tr> <tr> <td> <label>Contact_no</label> </td> <td> <input type="number" name="cnum" placeholder="9999999999"> </td> </tr> <tr> <tr> <td> <input type="submit" value="Submit" name="submit"> </td> <td> <input type="reset" value="Reset" name="reset"> </td> </tr> </tbody> </form> </table> </b> </div> </body> </html> **Second file** <?php echo "First name:-".$_COOKIE['c_fname']."<br>"; echo "Email:-".$_COOKIE['c_email']."<br>"; echo "Contact number:-".$_COOKIE['c_cnum']."<br>"; ?> ``` Description:- I have set cookie in first file and I want to retrieve them in second file but it displays this error. **Error:-** Notice: Undefined index: c\_fname in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 2 First name:- Notice: Undefined index: c\_email in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 3 Email:- Notice: Undefined index: c\_cnum in C:\xampp\htdocs\My PHP\Main\18\_2\php1.php on line 4 Contact number:-
2020/10/27
[ "https://Stackoverflow.com/questions/64552799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12903710/" ]
You have two separate question. The point of mocking is to not have dependencies in your unit tests creating implicit behavior. You want unit tests to be explicit about the code unit you test to be able to identify regression and also declare your expectation how `ClassUnderTest` behaves in different conditions. Whether you need to cover `Dependency` is a question concerning your coding standards. In general I find if a class is so simple that you ponder whether you need to test it, then usually writing the test should be a none issue and if writing a test is an issue to me that often enough indicates you really should have a test there, given you are unsure precisely because that code region is opaque.
If you're writing your unit test suite you probably want to mock it, even more if your dependency is pure logic. Consider the following scenario ``` public class ClassUnderTest { @Autowired private Dependency dependency; public int doSomething(int a, int b) { return dependency.add(a, b) * 2; } } public class Dependency { public int add(int a, int b) { return 0; // bug here! } } ``` In your unit test, you'll have something like ``` @Test void testingClass() { assertThat(classUnderTest.doSomething(2, 2), is(equalTo(8))); } ``` which will fail. However, your class under test is working fine! It's just delegating the task to another class You can avoid this false positives by mocking properly your dependencies ``` @Test void testingClass() { when(dependency.add(any(), any()).thenReturn(10); assertThat(classUnderTest.doSomething(2, 2), is(equalTo(20))); } ```
6,523,301
So I want to put a list of newsitems in \_Layout.cshtml I have a News model and a Show Action in its controller, and I want to put it in there with a RenderAction. ``` @Html.RenderAction("Show","News"); ``` Does not seem to work. But <http://localhost:49295/News/Show/> does work I should be using renderaction right? EDIT ``` @{Html.RenderAction("Show","News");} ``` stackoverflowerror, probably because I just put an action that uses the layout, in the layout itself? How do I not use the default layout for this view?
2011/06/29
[ "https://Stackoverflow.com/questions/6523301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295688/" ]
Set the layout to null in the View ``` @{ Layout = null; } ```
In your View try: ``` @{Html.RenderAction("Show","News");} ```
373,608
I'm new to this vmware stuff. I was wondering if anyone knows how to modify virtual images offline or know of any tools. I used VM Converter to convert my current desktop to an image. This is for a school project to be able to make changes to the image offline such as changing the os, install/remove software etc...
2012/03/26
[ "https://serverfault.com/questions/373608", "https://serverfault.com", "https://serverfault.com/users/115424/" ]
You can use [UFS Explorer](http://www.ufsexplorer.com/) to modify a cold VMDK image. It's a good data recovery tool as well.
maybe you want to take a look at this <http://www.vmware.com/support/developer/vddk/>
62,840,198
So I'm trying to parse quotes from a website, but within the Result class there are multiple paragraphs. Is there a way to ignore the date and author and only select the material in quotes? So I would only be left with a list of quotes? Using BeautifulSoup btw. Thanks. ``` <div class="result"> <p><strong>Date:</strong> February 2, 2019</p> <p>"My mind had no choice but to drift into an elaborate fantasy realm."</p> <blockquote> <p class="attribution">&mdash; Pamela, Paul</p> </blockquote> <a href="/metaphors/25249" class="load_details">preview</a> | <a href="/metaphors/25249" title="Let Children Get Bored Again [from The New York Times]">full record</a> <div class="details_container"></div> </div> <div class="result"> <p><strong>Date:</strong> February 2, 2019</p> <p>"You let your mind wander and follow it where it goes."</p> <blockquote> <p class="attribution">&mdash; Pamela, Paul</p> </blockquote> <a href="/metaphors/25250" class="load_details">preview</a> | <a href="/metaphors/25250" title="Let Children Get Bored Again [from The New York Times]">full record</a> <div class="details_container"></div> </div> ``` My current code is here: ``` import bs4 as bs import urllib.request sauce = urllib.request.urlopen('URLHERE').read() soup = bs.BeautifulSoup(sauce,'lxml') body = soup.body for paragraph in body.find_all('p'): print(paragraph.text) ```
2020/07/10
[ "https://Stackoverflow.com/questions/62840198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13907664/" ]
you can use xpath for your query, for example: ``` import requests from lxml import html page = requests.get('enter_your_url') tree = html.fromstring(page.content) data = tree.xpath('//div[@class="result"]//p[2]/text()') print(data) ```
If I understand your question properly, you're looking to print just the quotes, which appear in every 3rd paragraph element, starting with the 2nd one. ```py quotes = soup.find_all('p') for i in range(1, len(quotes), 3): print(quotes[i].text) ``` There may be a cleaner way of doing this, but that should work.
41,576,119
I'm currently working on an Angular 2 project and even though everything concernig routes seems to be working relatively fine, I'm not entirely happy with how I've accomplished this. Here's a diagram closely matching the structure I'm using for our app: ![diagram](https://i.imgur.com/9TvC1fc.gif) So, this app has two parts. According to their actions, they might require the user to be or not authenticated in order to reach them. Gaining access to one of them prevents the access to the other. * The non-authenticated pages (painted red on the diagram) all share the same design; apart from their forms and actions, they all look pretty much the same. So I've created a template and added a `<router-outlet>` to inject the required parts. * The authenticated pages all share the same structure: a navbar and a `<router-outlet>` to inject their contents; So, they all share the same parent: `LayoutComponent` (which belongs to `LayoutModule`). As you can see from the diagram, there are some particularities about each page: some redirect, some are not accessible and some of them do not have a path. The only way I was able to achieve this setup was by setting all the routes on the `LayoutModule` and even then, I was not to able to cover all of the cases (particularly the redirect from the root to `/home`). Also, `/page3` and `/page4` are not accessible, but each have their own component because they have links to reach the children which are injected via a `<router-outlet>`. Since every page has its own module (and the subpages are contained in them), I'd like to be able to set the routes in each module, to keep everything tight to each module and not spread around the app's code. Here are the routes defined on the LayoutModule, later imported via `RouterModule.forChild(ROUTES)`: ``` let ROUTES: Routes = [{ path: '', component: LayoutComponent, children: [ { path: 'home', component: HomeComponent }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component, children: [{ path: '', component: Subpage31Component }, { path: ':id', component: Subpage32Component }, { path: 'subpage3', component: Subpage33Component } ] }, { path: 'page4', component: Page4Component, children: [{ path: ':id/subpage1', component: Subpage41Component }, { path: ':id/subpage2', component: Subpage42Component }] } ] }]; ``` Is it possible to define the routes in each module? I'm sorry for such a verbose post but I'm trying to provide as much insight about my problem, as I can. I'm using Angular 2.2.0 and using angular-router 3.2.0.
2017/01/10
[ "https://Stackoverflow.com/questions/41576119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3219404/" ]
Any time you need to have a delay in iterations, it makes sense to use a self-calling function instead of a loop. ``` function doStuff(data, i){ //do things here console.log(i) if(--i) setTimeout(function(){doStuff(data, i)}, 1000) else nextStep(data) } function nextStep(data){ //after the loop ends, move to the next step of your code } doStuff([], 10) ```
Have you tried the equivalent of thread sleep? ``` var millisecondsToWait = 500; setTimeout(function() { // Whatever you want to do after the wait }, millisecondsToWait); ```
41,576,119
I'm currently working on an Angular 2 project and even though everything concernig routes seems to be working relatively fine, I'm not entirely happy with how I've accomplished this. Here's a diagram closely matching the structure I'm using for our app: ![diagram](https://i.imgur.com/9TvC1fc.gif) So, this app has two parts. According to their actions, they might require the user to be or not authenticated in order to reach them. Gaining access to one of them prevents the access to the other. * The non-authenticated pages (painted red on the diagram) all share the same design; apart from their forms and actions, they all look pretty much the same. So I've created a template and added a `<router-outlet>` to inject the required parts. * The authenticated pages all share the same structure: a navbar and a `<router-outlet>` to inject their contents; So, they all share the same parent: `LayoutComponent` (which belongs to `LayoutModule`). As you can see from the diagram, there are some particularities about each page: some redirect, some are not accessible and some of them do not have a path. The only way I was able to achieve this setup was by setting all the routes on the `LayoutModule` and even then, I was not to able to cover all of the cases (particularly the redirect from the root to `/home`). Also, `/page3` and `/page4` are not accessible, but each have their own component because they have links to reach the children which are injected via a `<router-outlet>`. Since every page has its own module (and the subpages are contained in them), I'd like to be able to set the routes in each module, to keep everything tight to each module and not spread around the app's code. Here are the routes defined on the LayoutModule, later imported via `RouterModule.forChild(ROUTES)`: ``` let ROUTES: Routes = [{ path: '', component: LayoutComponent, children: [ { path: 'home', component: HomeComponent }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component, children: [{ path: '', component: Subpage31Component }, { path: ':id', component: Subpage32Component }, { path: 'subpage3', component: Subpage33Component } ] }, { path: 'page4', component: Page4Component, children: [{ path: ':id/subpage1', component: Subpage41Component }, { path: ':id/subpage2', component: Subpage42Component }] } ] }]; ``` Is it possible to define the routes in each module? I'm sorry for such a verbose post but I'm trying to provide as much insight about my problem, as I can. I'm using Angular 2.2.0 and using angular-router 3.2.0.
2017/01/10
[ "https://Stackoverflow.com/questions/41576119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3219404/" ]
I'm not really sure of what you're after, but if you want to wait for each counter (in each input) to finish and then start the next counter, a linked list comes to mind. Jquery provides the method [next](https://api.jquery.com/next/) that gets you the next sibling. That could help you to build the linked list. The iteration over the list could be done using an interval that would be cleared when there were no more siblings. Putting it all together: ```js var $element = $("#wrap input:first"), countdownLimit = 10; var loop = setInterval(function() { if (!$element.length) { clearInterval(loop); } else { $element.val(countdownLimit--); if (countdownLimit < 0) { $element = $element.next('input'); countdownLimit = 10; } } }, 1000); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrap"> <input type="text"> <input type="text"> <input type="text"> </div> ``` There can be as many inputs as you like as long as they all are siblings.
Have you tried the equivalent of thread sleep? ``` var millisecondsToWait = 500; setTimeout(function() { // Whatever you want to do after the wait }, millisecondsToWait); ```
41,576,119
I'm currently working on an Angular 2 project and even though everything concernig routes seems to be working relatively fine, I'm not entirely happy with how I've accomplished this. Here's a diagram closely matching the structure I'm using for our app: ![diagram](https://i.imgur.com/9TvC1fc.gif) So, this app has two parts. According to their actions, they might require the user to be or not authenticated in order to reach them. Gaining access to one of them prevents the access to the other. * The non-authenticated pages (painted red on the diagram) all share the same design; apart from their forms and actions, they all look pretty much the same. So I've created a template and added a `<router-outlet>` to inject the required parts. * The authenticated pages all share the same structure: a navbar and a `<router-outlet>` to inject their contents; So, they all share the same parent: `LayoutComponent` (which belongs to `LayoutModule`). As you can see from the diagram, there are some particularities about each page: some redirect, some are not accessible and some of them do not have a path. The only way I was able to achieve this setup was by setting all the routes on the `LayoutModule` and even then, I was not to able to cover all of the cases (particularly the redirect from the root to `/home`). Also, `/page3` and `/page4` are not accessible, but each have their own component because they have links to reach the children which are injected via a `<router-outlet>`. Since every page has its own module (and the subpages are contained in them), I'd like to be able to set the routes in each module, to keep everything tight to each module and not spread around the app's code. Here are the routes defined on the LayoutModule, later imported via `RouterModule.forChild(ROUTES)`: ``` let ROUTES: Routes = [{ path: '', component: LayoutComponent, children: [ { path: 'home', component: HomeComponent }, { path: 'page2', component: Page2Component }, { path: 'page3', component: Page3Component, children: [{ path: '', component: Subpage31Component }, { path: ':id', component: Subpage32Component }, { path: 'subpage3', component: Subpage33Component } ] }, { path: 'page4', component: Page4Component, children: [{ path: ':id/subpage1', component: Subpage41Component }, { path: ':id/subpage2', component: Subpage42Component }] } ] }]; ``` Is it possible to define the routes in each module? I'm sorry for such a verbose post but I'm trying to provide as much insight about my problem, as I can. I'm using Angular 2.2.0 and using angular-router 3.2.0.
2017/01/10
[ "https://Stackoverflow.com/questions/41576119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3219404/" ]
I'm not really sure of what you're after, but if you want to wait for each counter (in each input) to finish and then start the next counter, a linked list comes to mind. Jquery provides the method [next](https://api.jquery.com/next/) that gets you the next sibling. That could help you to build the linked list. The iteration over the list could be done using an interval that would be cleared when there were no more siblings. Putting it all together: ```js var $element = $("#wrap input:first"), countdownLimit = 10; var loop = setInterval(function() { if (!$element.length) { clearInterval(loop); } else { $element.val(countdownLimit--); if (countdownLimit < 0) { $element = $element.next('input'); countdownLimit = 10; } } }, 1000); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrap"> <input type="text"> <input type="text"> <input type="text"> </div> ``` There can be as many inputs as you like as long as they all are siblings.
Any time you need to have a delay in iterations, it makes sense to use a self-calling function instead of a loop. ``` function doStuff(data, i){ //do things here console.log(i) if(--i) setTimeout(function(){doStuff(data, i)}, 1000) else nextStep(data) } function nextStep(data){ //after the loop ends, move to the next step of your code } doStuff([], 10) ```
28,263,366
I have below code, but I don't understand how the output is working. ``` String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); String s4 = new String("hello"); System.out.println(s1==s2); System.out.println(s3==s4); ``` The output is **true** then **false**. But the hashcode value for all s1,s2,s3 and s4 is same. Then how one is returning true and another one is returning false. Could you please make me understand this.
2015/02/01
[ "https://Stackoverflow.com/questions/28263366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757481/" ]
Use `s1.equals(s2)` for comparison between `String`, as `equals()` checks value equality while `==` checks reference equality, and `==` would never invoke `hashCode()`. Your first case is true because literals are interned by the compiler and thus refer to the same object ``` String s1 = "hello"; String s2 = "hello"; System.out.println(s1==s2); // true ```
Paul Lo is right. '==' checks if those objects are stored at the same place in the memory. The equals methode is suppost to return true if the hash is the same, not '=='.
28,263,366
I have below code, but I don't understand how the output is working. ``` String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); String s4 = new String("hello"); System.out.println(s1==s2); System.out.println(s3==s4); ``` The output is **true** then **false**. But the hashcode value for all s1,s2,s3 and s4 is same. Then how one is returning true and another one is returning false. Could you please make me understand this.
2015/02/01
[ "https://Stackoverflow.com/questions/28263366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757481/" ]
``` == tests for reference equality. .equals() tests for value equality. ``` and **==** has nothing to do with hashCode();
Paul Lo is right. '==' checks if those objects are stored at the same place in the memory. The equals methode is suppost to return true if the hash is the same, not '=='.
28,263,366
I have below code, but I don't understand how the output is working. ``` String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); String s4 = new String("hello"); System.out.println(s1==s2); System.out.println(s3==s4); ``` The output is **true** then **false**. But the hashcode value for all s1,s2,s3 and s4 is same. Then how one is returning true and another one is returning false. Could you please make me understand this.
2015/02/01
[ "https://Stackoverflow.com/questions/28263366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757481/" ]
s1 and s2, created using string literal, are always of the same object, being retrieved from the String constant pool. On the other hand, two new String objects are being created for s3 and S4 using new constructor.
Paul Lo is right. '==' checks if those objects are stored at the same place in the memory. The equals methode is suppost to return true if the hash is the same, not '=='.
14,835,436
I have a config.ini file with some values. One of them is the path to the root of my script. So in my js file i get the content from the config.ini file, but i have one big mistake. To load the data from the config file i already need one value from the config file, namely the path to the config file. Any idea how to handle that? Regards Sylnois **Edit**: This is my htaccess: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [L] RewriteRule ^([^/]+)/$ index.php?token=$1 [L] ``` This rewrites my link from <http://domain.com/fun/bla/index.php?token?123> to <http://domain.com/fun/bla/123/> .. So if someone access the second link, my js script would not be run anymore, cause i work with relative paths. I have now a value in my config which points to the root directory of my applicatoin: "./fun/bla/". Everything works so fine. But my requirement are, that no paths should be implemented in my code.
2013/02/12
[ "https://Stackoverflow.com/questions/14835436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515190/" ]
Yes. Store the path to your config file in code. The rest can be loaded from the config file. You can't possibly have everything in a config file. I once worked with someone who tried to store database configuration in the database. And then realized their mistake when they tried to make the application, you know, work.
What I've always done is to statically define the name of the config file in my code, so in your JS: ``` config_file = '/path/to/myconfig.ini' ```
14,835,436
I have a config.ini file with some values. One of them is the path to the root of my script. So in my js file i get the content from the config.ini file, but i have one big mistake. To load the data from the config file i already need one value from the config file, namely the path to the config file. Any idea how to handle that? Regards Sylnois **Edit**: This is my htaccess: ``` RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [L] RewriteRule ^([^/]+)/$ index.php?token=$1 [L] ``` This rewrites my link from <http://domain.com/fun/bla/index.php?token?123> to <http://domain.com/fun/bla/123/> .. So if someone access the second link, my js script would not be run anymore, cause i work with relative paths. I have now a value in my config which points to the root directory of my applicatoin: "./fun/bla/". Everything works so fine. But my requirement are, that no paths should be implemented in my code.
2013/02/12
[ "https://Stackoverflow.com/questions/14835436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515190/" ]
Yes. Store the path to your config file in code. The rest can be loaded from the config file. You can't possibly have everything in a config file. I once worked with someone who tried to store database configuration in the database. And then realized their mistake when they tried to make the application, you know, work.
This is a chicken and egg problem. The config file cannot contain the path to the config file, its path needs to be known to all parts of the program that need to know the settings. Perhaps have the path as a global variable in your program somewhere?
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
I would use [Celery](https://docs.celeryproject.org/en/stable/index.html) to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended). `app.py`: ``` from flask import Flask from celery import Celery broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue app = Flask(__name__) celery = Celery(app.name, broker=broker_url) celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py @celery.task(bind=True) def some_long_task(self, x, y): # Do some long task ... @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables return Response( mimetype='application/json', status=200 ) ``` Run your Flask app, and start another process to run your celery worker. ``` $ celery worker -A app.celery --loglevel=debug ``` I would also refer to Miguel Gringberg's [write up](http://blog.miguelgrinberg.com/post/using-celery-with-flask) for a more in depth guide to using Celery with Flask.
Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative. This solution is based on [Miguel Grinberg's PyCon 2016 Flask at Scale presentation](https://youtu.be/tdIIJuPh3SI?t=5070), specifically [slide 41](https://speakerdeck.com/miguelgrinberg/flask-at-scale?slide=41) in his slide deck. His [code is also available on github](https://github.com/miguelgrinberg/flack) for those interested in the original source. From a user perspective the code works as follows: 1. You make a call to the endpoint that performs the long running task. 2. This endpoint returns 202 Accepted with a link to check on the task status. 3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete. To convert an api call to a background task, simply add the @async\_api decorator. Here is a fully contained example: ```py from flask import Flask, g, abort, current_app, request, url_for from werkzeug.exceptions import HTTPException, InternalServerError from flask_restful import Resource, Api from datetime import datetime from functools import wraps import threading import time import uuid tasks = {} app = Flask(__name__) api = Api(app) @app.before_first_request def before_first_request(): """Start a background thread that cleans up old tasks.""" def clean_old_tasks(): """ This function cleans up old tasks from our in-memory data structure. """ global tasks while True: # Only keep tasks that are running or that finished less than 5 # minutes ago. five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60 tasks = {task_id: task for task_id, task in tasks.items() if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago} time.sleep(60) if not current_app.config['TESTING']: thread = threading.Thread(target=clean_old_tasks) thread.start() def async_api(wrapped_function): @wraps(wrapped_function) def new_function(*args, **kwargs): def task_call(flask_app, environ): # Create a request context similar to that of the original request # so that the task can have access to flask.g, flask.request, etc. with flask_app.request_context(environ): try: tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs) except HTTPException as e: tasks[task_id]['return_value'] = current_app.handle_http_exception(e) except Exception as e: # The function raised an exception, so we set a 500 error tasks[task_id]['return_value'] = InternalServerError() if current_app.debug: # We want to find out if something happened so reraise raise finally: # We record the time of the response, to help in garbage # collecting old tasks tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow()) # close the database session (if any) # Assign an id to the asynchronous task task_id = uuid.uuid4().hex # Record the task, and then launch it tasks[task_id] = {'task_thread': threading.Thread( target=task_call, args=(current_app._get_current_object(), request.environ))} tasks[task_id]['task_thread'].start() # Return a 202 response, with a link that the client can use to # obtain task status print(url_for('gettaskstatus', task_id=task_id)) return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return new_function class GetTaskStatus(Resource): def get(self, task_id): """ Return status about an asynchronous task. If this request returns a 202 status code, it means that task hasn't finished yet. Else, the response from the task is returned. """ task = tasks.get(task_id) if task is None: abort(404) if 'return_value' not in task: return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return task['return_value'] class CatchAll(Resource): @async_api def get(self, path=''): # perform some intensive processing print("starting processing task, path: '%s'" % path) time.sleep(10) print("completed processing task, path: '%s'" % path) return f'The answer is: {path}' api.add_resource(CatchAll, '/<path:path>', '/') api.add_resource(GetTaskStatus, '/status/<task_id>') if __name__ == '__main__': app.run(debug=True) ```
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
I would use [Celery](https://docs.celeryproject.org/en/stable/index.html) to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended). `app.py`: ``` from flask import Flask from celery import Celery broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue app = Flask(__name__) celery = Celery(app.name, broker=broker_url) celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py @celery.task(bind=True) def some_long_task(self, x, y): # Do some long task ... @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables return Response( mimetype='application/json', status=200 ) ``` Run your Flask app, and start another process to run your celery worker. ``` $ celery worker -A app.celery --loglevel=debug ``` I would also refer to Miguel Gringberg's [write up](http://blog.miguelgrinberg.com/post/using-celery-with-flask) for a more in depth guide to using Celery with Flask.
You can also try using [`multiprocessing.Process`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process) with `daemon=True`; the `process.start()` method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background. I experienced similar problem while working with [falcon](https://falcon.readthedocs.io/en/stable/) framework and using `daemon` process helped. You'd need to do the following: ``` from multiprocessing import Process @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... heavy_process = Process( # Create a daemonic process with heavy "my_func" target=my_func, daemon=True ) heavy_process.start() return Response( mimetype='application/json', status=200 ) # Define some heavy function def my_func(): time.sleep(10) print("Process finished") ``` You should get a response immediately and, after 10s you should see a printed message in the console. NOTE: Keep in mind that `daemonic` processes are not allowed to spawn any child processes.
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
I would use [Celery](https://docs.celeryproject.org/en/stable/index.html) to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended). `app.py`: ``` from flask import Flask from celery import Celery broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue app = Flask(__name__) celery = Celery(app.name, broker=broker_url) celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py @celery.task(bind=True) def some_long_task(self, x, y): # Do some long task ... @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables return Response( mimetype='application/json', status=200 ) ``` Run your Flask app, and start another process to run your celery worker. ``` $ celery worker -A app.celery --loglevel=debug ``` I would also refer to Miguel Gringberg's [write up](http://blog.miguelgrinberg.com/post/using-celery-with-flask) for a more in depth guide to using Celery with Flask.
Flask 2.0 ========= Flask 2.0 supports async routes now. You can use the httpx library and use the asyncio coroutines for that. You can change your code a bit like below ``` @app.route('/render/<id>', methods=['POST']) async def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = await asyncio.gather( audio_class.render_audio(data=text_list), do_other_stuff_function() ) # Just make sure that the coroutine should not having any blocking calls inside it. return Response( mimetype='application/json', status=200 ) ``` The above one is just a pseudo code, but you can checkout how asyncio works with flask 2.0 and for HTTP calls you can use httpx. And also make sure the coroutines are only doing some I/O tasks only.
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
I would use [Celery](https://docs.celeryproject.org/en/stable/index.html) to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended). `app.py`: ``` from flask import Flask from celery import Celery broker_url = 'amqp://guest@localhost' # Broker URL for RabbitMQ task queue app = Flask(__name__) celery = Celery(app.name, broker=broker_url) celery.config_from_object('celeryconfig') # Your celery configurations in a celeryconfig.py @celery.task(bind=True) def some_long_task(self, x, y): # Do some long task ... @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) some_long_task.delay(x, y) # Call your async task and pass whatever necessary variables return Response( mimetype='application/json', status=200 ) ``` Run your Flask app, and start another process to run your celery worker. ``` $ celery worker -A app.celery --loglevel=debug ``` I would also refer to Miguel Gringberg's [write up](http://blog.miguelgrinberg.com/post/using-celery-with-flask) for a more in depth guide to using Celery with Flask.
If you are using `redis`, you can use `Pubsub` event to handle background tasks. See more: <https://redis.com/ebook/part-2-core-concepts/chapter-3-commands-in-redis/3-6-publishsubscribe/>
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative. This solution is based on [Miguel Grinberg's PyCon 2016 Flask at Scale presentation](https://youtu.be/tdIIJuPh3SI?t=5070), specifically [slide 41](https://speakerdeck.com/miguelgrinberg/flask-at-scale?slide=41) in his slide deck. His [code is also available on github](https://github.com/miguelgrinberg/flack) for those interested in the original source. From a user perspective the code works as follows: 1. You make a call to the endpoint that performs the long running task. 2. This endpoint returns 202 Accepted with a link to check on the task status. 3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete. To convert an api call to a background task, simply add the @async\_api decorator. Here is a fully contained example: ```py from flask import Flask, g, abort, current_app, request, url_for from werkzeug.exceptions import HTTPException, InternalServerError from flask_restful import Resource, Api from datetime import datetime from functools import wraps import threading import time import uuid tasks = {} app = Flask(__name__) api = Api(app) @app.before_first_request def before_first_request(): """Start a background thread that cleans up old tasks.""" def clean_old_tasks(): """ This function cleans up old tasks from our in-memory data structure. """ global tasks while True: # Only keep tasks that are running or that finished less than 5 # minutes ago. five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60 tasks = {task_id: task for task_id, task in tasks.items() if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago} time.sleep(60) if not current_app.config['TESTING']: thread = threading.Thread(target=clean_old_tasks) thread.start() def async_api(wrapped_function): @wraps(wrapped_function) def new_function(*args, **kwargs): def task_call(flask_app, environ): # Create a request context similar to that of the original request # so that the task can have access to flask.g, flask.request, etc. with flask_app.request_context(environ): try: tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs) except HTTPException as e: tasks[task_id]['return_value'] = current_app.handle_http_exception(e) except Exception as e: # The function raised an exception, so we set a 500 error tasks[task_id]['return_value'] = InternalServerError() if current_app.debug: # We want to find out if something happened so reraise raise finally: # We record the time of the response, to help in garbage # collecting old tasks tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow()) # close the database session (if any) # Assign an id to the asynchronous task task_id = uuid.uuid4().hex # Record the task, and then launch it tasks[task_id] = {'task_thread': threading.Thread( target=task_call, args=(current_app._get_current_object(), request.environ))} tasks[task_id]['task_thread'].start() # Return a 202 response, with a link that the client can use to # obtain task status print(url_for('gettaskstatus', task_id=task_id)) return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return new_function class GetTaskStatus(Resource): def get(self, task_id): """ Return status about an asynchronous task. If this request returns a 202 status code, it means that task hasn't finished yet. Else, the response from the task is returned. """ task = tasks.get(task_id) if task is None: abort(404) if 'return_value' not in task: return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return task['return_value'] class CatchAll(Resource): @async_api def get(self, path=''): # perform some intensive processing print("starting processing task, path: '%s'" % path) time.sleep(10) print("completed processing task, path: '%s'" % path) return f'The answer is: {path}' api.add_resource(CatchAll, '/<path:path>', '/') api.add_resource(GetTaskStatus, '/status/<task_id>') if __name__ == '__main__': app.run(debug=True) ```
You can also try using [`multiprocessing.Process`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process) with `daemon=True`; the `process.start()` method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background. I experienced similar problem while working with [falcon](https://falcon.readthedocs.io/en/stable/) framework and using `daemon` process helped. You'd need to do the following: ``` from multiprocessing import Process @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... heavy_process = Process( # Create a daemonic process with heavy "my_func" target=my_func, daemon=True ) heavy_process.start() return Response( mimetype='application/json', status=200 ) # Define some heavy function def my_func(): time.sleep(10) print("Process finished") ``` You should get a response immediately and, after 10s you should see a printed message in the console. NOTE: Keep in mind that `daemonic` processes are not allowed to spawn any child processes.
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative. This solution is based on [Miguel Grinberg's PyCon 2016 Flask at Scale presentation](https://youtu.be/tdIIJuPh3SI?t=5070), specifically [slide 41](https://speakerdeck.com/miguelgrinberg/flask-at-scale?slide=41) in his slide deck. His [code is also available on github](https://github.com/miguelgrinberg/flack) for those interested in the original source. From a user perspective the code works as follows: 1. You make a call to the endpoint that performs the long running task. 2. This endpoint returns 202 Accepted with a link to check on the task status. 3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete. To convert an api call to a background task, simply add the @async\_api decorator. Here is a fully contained example: ```py from flask import Flask, g, abort, current_app, request, url_for from werkzeug.exceptions import HTTPException, InternalServerError from flask_restful import Resource, Api from datetime import datetime from functools import wraps import threading import time import uuid tasks = {} app = Flask(__name__) api = Api(app) @app.before_first_request def before_first_request(): """Start a background thread that cleans up old tasks.""" def clean_old_tasks(): """ This function cleans up old tasks from our in-memory data structure. """ global tasks while True: # Only keep tasks that are running or that finished less than 5 # minutes ago. five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60 tasks = {task_id: task for task_id, task in tasks.items() if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago} time.sleep(60) if not current_app.config['TESTING']: thread = threading.Thread(target=clean_old_tasks) thread.start() def async_api(wrapped_function): @wraps(wrapped_function) def new_function(*args, **kwargs): def task_call(flask_app, environ): # Create a request context similar to that of the original request # so that the task can have access to flask.g, flask.request, etc. with flask_app.request_context(environ): try: tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs) except HTTPException as e: tasks[task_id]['return_value'] = current_app.handle_http_exception(e) except Exception as e: # The function raised an exception, so we set a 500 error tasks[task_id]['return_value'] = InternalServerError() if current_app.debug: # We want to find out if something happened so reraise raise finally: # We record the time of the response, to help in garbage # collecting old tasks tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow()) # close the database session (if any) # Assign an id to the asynchronous task task_id = uuid.uuid4().hex # Record the task, and then launch it tasks[task_id] = {'task_thread': threading.Thread( target=task_call, args=(current_app._get_current_object(), request.environ))} tasks[task_id]['task_thread'].start() # Return a 202 response, with a link that the client can use to # obtain task status print(url_for('gettaskstatus', task_id=task_id)) return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return new_function class GetTaskStatus(Resource): def get(self, task_id): """ Return status about an asynchronous task. If this request returns a 202 status code, it means that task hasn't finished yet. Else, the response from the task is returned. """ task = tasks.get(task_id) if task is None: abort(404) if 'return_value' not in task: return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return task['return_value'] class CatchAll(Resource): @async_api def get(self, path=''): # perform some intensive processing print("starting processing task, path: '%s'" % path) time.sleep(10) print("completed processing task, path: '%s'" % path) return f'The answer is: {path}' api.add_resource(CatchAll, '/<path:path>', '/') api.add_resource(GetTaskStatus, '/status/<task_id>') if __name__ == '__main__': app.run(debug=True) ```
Flask 2.0 ========= Flask 2.0 supports async routes now. You can use the httpx library and use the asyncio coroutines for that. You can change your code a bit like below ``` @app.route('/render/<id>', methods=['POST']) async def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = await asyncio.gather( audio_class.render_audio(data=text_list), do_other_stuff_function() ) # Just make sure that the coroutine should not having any blocking calls inside it. return Response( mimetype='application/json', status=200 ) ``` The above one is just a pseudo code, but you can checkout how asyncio works with flask 2.0 and for HTTP calls you can use httpx. And also make sure the coroutines are only doing some I/O tasks only.
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative. This solution is based on [Miguel Grinberg's PyCon 2016 Flask at Scale presentation](https://youtu.be/tdIIJuPh3SI?t=5070), specifically [slide 41](https://speakerdeck.com/miguelgrinberg/flask-at-scale?slide=41) in his slide deck. His [code is also available on github](https://github.com/miguelgrinberg/flack) for those interested in the original source. From a user perspective the code works as follows: 1. You make a call to the endpoint that performs the long running task. 2. This endpoint returns 202 Accepted with a link to check on the task status. 3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete. To convert an api call to a background task, simply add the @async\_api decorator. Here is a fully contained example: ```py from flask import Flask, g, abort, current_app, request, url_for from werkzeug.exceptions import HTTPException, InternalServerError from flask_restful import Resource, Api from datetime import datetime from functools import wraps import threading import time import uuid tasks = {} app = Flask(__name__) api = Api(app) @app.before_first_request def before_first_request(): """Start a background thread that cleans up old tasks.""" def clean_old_tasks(): """ This function cleans up old tasks from our in-memory data structure. """ global tasks while True: # Only keep tasks that are running or that finished less than 5 # minutes ago. five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60 tasks = {task_id: task for task_id, task in tasks.items() if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago} time.sleep(60) if not current_app.config['TESTING']: thread = threading.Thread(target=clean_old_tasks) thread.start() def async_api(wrapped_function): @wraps(wrapped_function) def new_function(*args, **kwargs): def task_call(flask_app, environ): # Create a request context similar to that of the original request # so that the task can have access to flask.g, flask.request, etc. with flask_app.request_context(environ): try: tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs) except HTTPException as e: tasks[task_id]['return_value'] = current_app.handle_http_exception(e) except Exception as e: # The function raised an exception, so we set a 500 error tasks[task_id]['return_value'] = InternalServerError() if current_app.debug: # We want to find out if something happened so reraise raise finally: # We record the time of the response, to help in garbage # collecting old tasks tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow()) # close the database session (if any) # Assign an id to the asynchronous task task_id = uuid.uuid4().hex # Record the task, and then launch it tasks[task_id] = {'task_thread': threading.Thread( target=task_call, args=(current_app._get_current_object(), request.environ))} tasks[task_id]['task_thread'].start() # Return a 202 response, with a link that the client can use to # obtain task status print(url_for('gettaskstatus', task_id=task_id)) return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return new_function class GetTaskStatus(Resource): def get(self, task_id): """ Return status about an asynchronous task. If this request returns a 202 status code, it means that task hasn't finished yet. Else, the response from the task is returned. """ task = tasks.get(task_id) if task is None: abort(404) if 'return_value' not in task: return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)} return task['return_value'] class CatchAll(Resource): @async_api def get(self, path=''): # perform some intensive processing print("starting processing task, path: '%s'" % path) time.sleep(10) print("completed processing task, path: '%s'" % path) return f'The answer is: {path}' api.add_resource(CatchAll, '/<path:path>', '/') api.add_resource(GetTaskStatus, '/status/<task_id>') if __name__ == '__main__': app.run(debug=True) ```
If you are using `redis`, you can use `Pubsub` event to handle background tasks. See more: <https://redis.com/ebook/part-2-core-concepts/chapter-3-commands-in-redis/3-6-publishsubscribe/>
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
You can also try using [`multiprocessing.Process`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process) with `daemon=True`; the `process.start()` method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background. I experienced similar problem while working with [falcon](https://falcon.readthedocs.io/en/stable/) framework and using `daemon` process helped. You'd need to do the following: ``` from multiprocessing import Process @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... heavy_process = Process( # Create a daemonic process with heavy "my_func" target=my_func, daemon=True ) heavy_process.start() return Response( mimetype='application/json', status=200 ) # Define some heavy function def my_func(): time.sleep(10) print("Process finished") ``` You should get a response immediately and, after 10s you should see a printed message in the console. NOTE: Keep in mind that `daemonic` processes are not allowed to spawn any child processes.
If you are using `redis`, you can use `Pubsub` event to handle background tasks. See more: <https://redis.com/ebook/part-2-core-concepts/chapter-3-commands-in-redis/3-6-publishsubscribe/>
31,866,796
I am writing an application in Flask, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while control is returned to Flask. My view looks like: ``` @app.route('/render/<id>', methods=['POST']) def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = audio_class.render_audio(data=text_list) # do stuff return Response( mimetype='application/json', status=200 ) ``` Now, what I want to do is have the line ``` final_file = audio_class.render_audio() ``` run and provide a callback to be executed when the method returns, whilst Flask can continue to process requests. This is the only task which I need Flask to run asynchronously, and I would like some advice on how best to implement this. I have looked at Twisted and Klein, but I'm not sure they are overkill, as maybe Threading would suffice. Or maybe Celery is a good choice for this?
2015/08/06
[ "https://Stackoverflow.com/questions/31866796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
Flask 2.0 ========= Flask 2.0 supports async routes now. You can use the httpx library and use the asyncio coroutines for that. You can change your code a bit like below ``` @app.route('/render/<id>', methods=['POST']) async def render_script(id=None): ... data = json.loads(request.data) text_list = data.get('text_list') final_file = await asyncio.gather( audio_class.render_audio(data=text_list), do_other_stuff_function() ) # Just make sure that the coroutine should not having any blocking calls inside it. return Response( mimetype='application/json', status=200 ) ``` The above one is just a pseudo code, but you can checkout how asyncio works with flask 2.0 and for HTTP calls you can use httpx. And also make sure the coroutines are only doing some I/O tasks only.
If you are using `redis`, you can use `Pubsub` event to handle background tasks. See more: <https://redis.com/ebook/part-2-core-concepts/chapter-3-commands-in-redis/3-6-publishsubscribe/>
26,828,549
How to move my actionbar item to the left side of the ACTIONBAR, before the title? I have two items, edit and settings, I need my items placed both on the right and left side, but it places by default on the right, how can i change it?
2014/11/09
[ "https://Stackoverflow.com/questions/26828549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4166426/" ]
in the Activity ActionBar actionBar = getActionBar(); ``` actionBar.setDisplayShowHomeEnabled(false); View mActionBarView = getLayoutInflater().inflate(R.layout.my_action_bar, null); actionBar.setCustomView(mActionBarView); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ``` my\_action\_bar.xml: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/turquoise"> <ImageButton android:id="@+id/btn_slide" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@null" android:scaleType="centerInside" android:src="@drawable/btn_slide" android:paddingRight="50dp" android:onClick="toggleMenu" android:paddingTop="4dp"/> </RelativeLayout> ```
What I would do is hide the actionbar title by following way: ``` getActionBar().setDisplayShowTitleEnabled(false); ``` Then place them in item menu as you wish in your order.
44,119,792
> > We're sorry if it sounds too noob. But this is our life's first encounter with Python. > > > We have [got a python function](https://tio.run/nexus/python2#LY7BCsIwEER/ZY@7ZgOm0AhK/BHx0MYUQs0qsUL79bFtvMzwGGaY8ggDJBQe2bsjnWdenFxymL5ZwEMcQJwbITw/AU4H9FdLrwwpCibEWXW8qJ62sjI0rEnHPUS5oeGGeFW9ma6k/9iw2VVvpivpHe9U3jnKtD6qC4AtW6JioIEW7A8) like this: ``` def m(n,k,c=0):x,y=n;return c if n==k else 7*(c>6)or min(m((x+a,y+b),k,c+1)for a,b in[(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)]) ``` which is being called like this: ``` print m((1,2), (5,6)) ``` In order to understand it we were trying to add line breaks like this: ``` def m(n,k,c=0):x,y=n;return c if n==k else 7*(c>6) or min(m((x+a,y+b),k,c+1)for a,b in[(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)]) ``` We're not understanding why is just a **simple new line** breaking the code Once we understand this, probably we shall be able to convert this program to javascript: ```js function m(n, k, c = 0) { x, y = n; return c if (n == k) { } else { 7 * (c > 6) or Math.min(m((x + a, y + b), k, c + 1) for a, b in [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]) } } ```
2017/05/22
[ "https://Stackoverflow.com/questions/44119792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6664238/" ]
When you define a function, either the function definition must be all on the same line (as in your original example), or the header `def m(n,k,c=0):` must be on the line of its own, and the remaining statements must be on the next line(s). You cannot mix-and-match. ``` def m(n, k, c=0): x, y = n return c if n==k else \ 7 * (c > 6) or min(m((x + a, y + b), k, c + 1) for a,b in [(1,2), (1,-2), (-1,2), (-1,-2), (2,1), (2,-1), (-2,1), (-2,-1)]) m((1,2), 3) #7 ```
The part that goes `return c if n==k else ...` is a ternary conditional operator in Python (similar to the `? :` operator in JS). See [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) for instance. You can't put a line break there, because in Python that's a statement separator.
240,231
I have created an SVN server long time back. I have been storing some binary files (doc files) along with codes. After every edit size increases because SVN saves a new copy of binary file. Now the svn is occupying a lot of space. Q1. I want to delete all previous revision of the binary files, keeping previous revisions of my codes intact, how do I do that? Q2. Also is there any setting in SVN where I can customize it? Like "for specific folder dont store more than 10 revisions".
2011/02/25
[ "https://serverfault.com/questions/240231", "https://serverfault.com", "https://serverfault.com/users/72184/" ]
The only way to destroy data in subversion is to dump the repository to a file; run it through `svndumpfilter` and load it back again. svndumpfilter only works on paths, not revisions, however, so for your purpose, I'd recommend `svn export`ing your binaries folder, before doing the following: ``` svnadmin dump <repo root> > file.dump cat file.dump | svndumpfilter exclude <repo path containing binaries> > file-new.dump svnadmincreate <new repo root> svnadmin load <new repo root> < file-new.dump ``` This will leave you with a copy of your repository, including full history, but without the offending path; and you'll see empty revisions in the history where commits to those paths happened. (There are some options to `svndumpfilter` to remove those, but in most cases you probably want to preserve the revision numbering.) As for automating this, You could use a post-commit hook to script this process, but it's massively time consuming on large repositories. You'd be better off simply not storing binaries in SVN at all, if you don't need the history for them.
i'm affraid you cant do it 'out of the box', what goes in is meant to stay. you can remove files by dumping the repository, filtering files and importing it again - but it's a pain. check this discussions: [1](https://stackoverflow.com/questions/2426056/why-isnt-obliterate-an-essential-feature-of-subversion), [2](https://stackoverflow.com/questions/560684/svn-obliterate).
65,202,015
I recently started using enums for commonly used names in my application. The issue is that enums cannot be inherited. This is the intent: ``` public enum foreignCars { Mazda = 0, Nissan = 1, Peugot = 2 } public enum allCars : foreignCars { BMW = 3, VW = 4, Audi = 5 } ``` Of course, this can't be done. In similar questions I found, people have suggested using classes for this instead, like: ``` public static class foreignCars { int Mazda = 0; int Nissan = 1; int Peugot = 2; } public static class allCars : foreignCars { int BMW = 3; int VW = 4; int Audi = 5; } ``` But static classes can't be inherited either! So I would have to make them non-static and create objects just to be able to reference these names in my application, which defeats the whole purpose. With that in mind, what is the best way to achieve what I want - having inheritable enum-like entities (so that I don't have to repeat car brands in both enums/classes/whatever), and without having to instantiate objects either? What is the proper approach here? This is the part that I couldn't find in any other questions, but if I missed something, please let me know. EDIT: I would like to point out that I have reviewed similar questions asking about enum and static class inheritance, and I am fully aware that is not possible in C#. Therefore, I am looking for an alternative, which was not covered in these similar questions.
2020/12/08
[ "https://Stackoverflow.com/questions/65202015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10243896/" ]
``` using System; namespace Csharp_learning { class MainDemo { public static int ReadNumber(string prompt, int min, int max) { int result = 0; do { Console.Write(prompt); string numberString = Console.ReadLine(); result = int.Parse(numberString); if (result > max || result < min) Console.WriteLine("Please enter a value in the range " + min + " to " + max); else break; } while (true); return result; } } } ``` You have an extra result before if statement. As for the other error you can try the link below. [An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module](https://stackoverflow.com/questions/9729691/an-unhandled-exception-of-type-system-io-filenotfoundexception-occurred-in-unk) A problem also appears saying the program does not contain a Static Main, but the previous replies say the code works as it is. Every c# console program has a static main. I was under the impression you already knew that. That part should look a little like below. ``` using System; namespace Csharp_learning { class Program { static void Main(string[] args) { MainDemo.ReadNumber("Prompt input ", 1, 10); } } } ``` These two different code blocks are most often in different files but you could just try copying in below to see if it works. ``` using System; namespace Csharp_learning { class MainDemo { public static int ReadNumber(string prompt, int min, int max) { int result = 0; do { Console.Write(prompt); string numberString = Console.ReadLine(); result = int.Parse(numberString); if (result > max || result < min) Console.WriteLine("Please enter a value in the range " + min + " to " + max); else break; } while (true); return result; } } } namespace Csharp_learning { class Program { static void Main(string[] args) { MainDemo.ReadNumber("Prompt input ", 1, 10); } } } ```
Your code runs fine for me. It works as expected. The error suggest there is a typo in the project file. Open your CSharp Learning.csproj project file and look for parenthesis that are mismatched or out of place. Another solution would be to create a new project. Then copy your code the the new project.
9,790,243
**UPDATE:** Seems to me like it is pretty much an Apple bug. I tried the following: 1. create a new single-window project 2. create a single UIPickerView like the one shown below, only that the picker just allows for turning the dials. That is, neither variables nor any state is manipulated when interacting the picker. **RESULT:** No matter whether I use the simple titleForRow:forComponent or viewForRow:forComponent, the picker still leaks 48 bytes each time a dial is turned. Further, I even tried having the picker return views previously allocated in an array set up as a class property in the viewController, so that no views are retained or released but for whatever the picker might do internally after or before it calls the delegate methods. And still, the leaks occur. Seems like an Apple bug to me. **ORIGINAL QUESTION** I have a textField whose imputView is set to a UIPickerView with 4 components. The picker is used to select a weight / mass which becomes the text in the textField. Under Instruments, each time I turn a dial / component in the UIPickerView, a leak occurs: ![enter image description here](https://i.stack.imgur.com/BQhV5.png) Here's the stack trace for the 48 byte leak: ![enter image description here](https://i.stack.imgur.com/0YCng.png) The code through which the UIPickerView gets each component view is: ``` - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { if(!view) { view = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 37)] autorelease]; UILabel *label = (UILabel*)view; label.autoresizingMask = UIViewAutoresizingFlexibleWidth; label.textAlignment = UITextAlignmentCenter; label.font = [UIFont boldSystemFontOfSize:24]; label.backgroundColor = [UIColor clearColor]; } ((UILabel*)view).text = [NSString stringWithFormat:@"%@%i", ((component == 3) ? @"." : @""), row]; return view; } - (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return 60; } ``` And the code that updates the textField to the new textual value is: ``` - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSString *newWeight = [NSString stringWithFormat:@"%i%i%i.%i", [pickerView selectedRowInComponent:0], [pickerView selectedRowInComponent:1], [pickerView selectedRowInComponent:2], [pickerView selectedRowInComponent:3]]; self.sampleMassBuffer = [NSDecimalNumber decimalNumberWithString:newWeight]; weightTextField.text = [[numberFormatter stringFromNumber:self.sampleMassBuffer] stringByAppendingFormat:@" %@", currentConfiguration.weightUnits]; } ``` I have no idea how the leaks are originating or if they are even mine! Could it be an Apple bug?
2012/03/20
[ "https://Stackoverflow.com/questions/9790243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949772/" ]
Firstly, I'm impressed that you managed to create an InnoDB table that has FK references to two MyISAM tables! Try creating all three table with InnoDB engine and trying again....
Both the parent and the child tables need to use the InnoDB storage engine, but you're using MyISAM for the parent tables. My guess is that there is already a table named department\_roles\_map, so when you run`CREATE TABLE IF NOT EXISTS` it's failing because the table already exists, and ignoring the error. Then when you try to insert data into the **other** department\_roles\_map, it fails with the FK error. But that's just a guess. I agree with Tom Mac, try creating all 3 tables using InnoDB, but you should also confirm that no other tables with those names already exists.
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
In short: it is in dependence of your context, the data inside your editor. `wp_kses()` is really helpful, and you can define your custom allowed HTML tags. Alternative, you can use the default functions, like [`wp_kses_post`](https://codex.wordpress.org/Function_Reference/wp_kses_post) or [`wp_kses_data`](https://codex.wordpress.org/Function_Reference/wp_kses_data). These functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See <https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments> WordPress defines much more functions to sanitize the input, see <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data> and <https://codex.wordpress.org/Data_Validation> These pages are really helpful. However, in your context should the `wp_kses_post` function, the right choice.
Try ``` //save this in the database $content=sanitize_text_field( htmlentities($_POST['content']) ); //to display, use html_entity_decode($content); ``` 1. `htmlentities()` will convert all characters which have HTML character entity equivalents to their equivalents. 2. `sanitize_text_field()` will then check for invalid UTF-8 characters and strip them off. This can now be stored in the database. 3. `html_entity_decode()` will convert HTML entities to their HTML tag equivalents
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
Try ``` //save this in the database $content=sanitize_text_field( htmlentities($_POST['content']) ); //to display, use html_entity_decode($content); ``` 1. `htmlentities()` will convert all characters which have HTML character entity equivalents to their equivalents. 2. `sanitize_text_field()` will then check for invalid UTF-8 characters and strip them off. This can now be stored in the database. 3. `html_entity_decode()` will convert HTML entities to their HTML tag equivalents
[wp\_slash](https://codex.wordpress.org/Function_Reference/wp_slash) More information. ``` update_post_meta( $post_id, $prefix.'content',wp_slash($_POST['content']) ); ```
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
Try ``` //save this in the database $content=sanitize_text_field( htmlentities($_POST['content']) ); //to display, use html_entity_decode($content); ``` 1. `htmlentities()` will convert all characters which have HTML character entity equivalents to their equivalents. 2. `sanitize_text_field()` will then check for invalid UTF-8 characters and strip them off. This can now be stored in the database. 3. `html_entity_decode()` will convert HTML entities to their HTML tag equivalents
You could do someting like this: ``` /** * Most of the 'post' HTML are excepted accept <textarea> itself. * @link https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html */ $allowed_html = wp_kses_allowed_html( 'post' ); // Remove '<textarea>' tag unset ( $allowed_html['textarea'] ); /** * wp_kses_allowed_html return the wrong values for wp_kses, * need to change "true" -> "array()" */ array_walk_recursive( $allowed_html, function ( &$value ) { if ( is_bool( $value ) ) { $value = array(); } } ); // Run sanitization. $value = wp_kses( $value, $allowed_html ); ``` **@fuxia:** as OP wrote: *"I read a bit about wp\_kses() but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)"* wp\_kses does the following: *"This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string. You have to remove any slashes from PHP's magic quotes before you call this function."* <https://codex.wordpress.org/Function_Reference/wp_kses> My code uses `wp_kses` with "Allowing common tags". What are the common tags? The list available to read in the given link. It is a long list, so I did not paste it here. <https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html> I think textarea itself should not be allowed in textarea. **@bueltge** wp\_kses\_post does the same thing, except allow '<textarea>' tag, which - I think - shouldn't be. <https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/kses.php#L1575> ``` function wp_kses_post( $data ) { return wp_kses( $data, 'post' ); } ```
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
In short: it is in dependence of your context, the data inside your editor. `wp_kses()` is really helpful, and you can define your custom allowed HTML tags. Alternative, you can use the default functions, like [`wp_kses_post`](https://codex.wordpress.org/Function_Reference/wp_kses_post) or [`wp_kses_data`](https://codex.wordpress.org/Function_Reference/wp_kses_data). These functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See <https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments> WordPress defines much more functions to sanitize the input, see <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data> and <https://codex.wordpress.org/Data_Validation> These pages are really helpful. However, in your context should the `wp_kses_post` function, the right choice.
[wp\_slash](https://codex.wordpress.org/Function_Reference/wp_slash) More information. ``` update_post_meta( $post_id, $prefix.'content',wp_slash($_POST['content']) ); ```
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
In short: it is in dependence of your context, the data inside your editor. `wp_kses()` is really helpful, and you can define your custom allowed HTML tags. Alternative, you can use the default functions, like [`wp_kses_post`](https://codex.wordpress.org/Function_Reference/wp_kses_post) or [`wp_kses_data`](https://codex.wordpress.org/Function_Reference/wp_kses_data). These functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See <https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments> WordPress defines much more functions to sanitize the input, see <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data> and <https://codex.wordpress.org/Data_Validation> These pages are really helpful. However, in your context should the `wp_kses_post` function, the right choice.
You could do someting like this: ``` /** * Most of the 'post' HTML are excepted accept <textarea> itself. * @link https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html */ $allowed_html = wp_kses_allowed_html( 'post' ); // Remove '<textarea>' tag unset ( $allowed_html['textarea'] ); /** * wp_kses_allowed_html return the wrong values for wp_kses, * need to change "true" -> "array()" */ array_walk_recursive( $allowed_html, function ( &$value ) { if ( is_bool( $value ) ) { $value = array(); } } ); // Run sanitization. $value = wp_kses( $value, $allowed_html ); ``` **@fuxia:** as OP wrote: *"I read a bit about wp\_kses() but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)"* wp\_kses does the following: *"This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string. You have to remove any slashes from PHP's magic quotes before you call this function."* <https://codex.wordpress.org/Function_Reference/wp_kses> My code uses `wp_kses` with "Allowing common tags". What are the common tags? The list available to read in the given link. It is a long list, so I did not paste it here. <https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html> I think textarea itself should not be allowed in textarea. **@bueltge** wp\_kses\_post does the same thing, except allow '<textarea>' tag, which - I think - shouldn't be. <https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/kses.php#L1575> ``` function wp_kses_post( $data ) { return wp_kses( $data, 'post' ); } ```
262,796
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
You could do someting like this: ``` /** * Most of the 'post' HTML are excepted accept <textarea> itself. * @link https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html */ $allowed_html = wp_kses_allowed_html( 'post' ); // Remove '<textarea>' tag unset ( $allowed_html['textarea'] ); /** * wp_kses_allowed_html return the wrong values for wp_kses, * need to change "true" -> "array()" */ array_walk_recursive( $allowed_html, function ( &$value ) { if ( is_bool( $value ) ) { $value = array(); } } ); // Run sanitization. $value = wp_kses( $value, $allowed_html ); ``` **@fuxia:** as OP wrote: *"I read a bit about wp\_kses() but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)"* wp\_kses does the following: *"This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string. You have to remove any slashes from PHP's magic quotes before you call this function."* <https://codex.wordpress.org/Function_Reference/wp_kses> My code uses `wp_kses` with "Allowing common tags". What are the common tags? The list available to read in the given link. It is a long list, so I did not paste it here. <https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html> I think textarea itself should not be allowed in textarea. **@bueltge** wp\_kses\_post does the same thing, except allow '<textarea>' tag, which - I think - shouldn't be. <https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/kses.php#L1575> ``` function wp_kses_post( $data ) { return wp_kses( $data, 'post' ); } ```
[wp\_slash](https://codex.wordpress.org/Function_Reference/wp_slash) More information. ``` update_post_meta( $post_id, $prefix.'content',wp_slash($_POST['content']) ); ```
25,161,692
After installing opensips(It will be better if i won't have to use opensips control panel) how can add users and can make test call. Note: I am a newbie, and following this guide for installation. <http://www.opensips.org/Documentation/Install-CompileAndInstall-1-11>
2014/08/06
[ "https://Stackoverflow.com/questions/25161692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/937256/" ]
Instead of using the *Control Panel*, you can use *opensipsctl* in order to add new subscribers. All you need to do is: ``` opensipsctl add liviu@opensips.org mypassword ``` For more help on the *opensipsctl*, simply type: ``` opensipsctl ```
For any user that's trying to install the package under Ubuntu by instructions from official manual, please make sure that you also read setup manual from github page, section [C] and [D] > > <https://github.com/OpenSIPS/opensips/blob/master/INSTALL> > > > I've tried to do a fresh setup of opensips on a virtual machine to test the functions. The provided packages on Jessie branch of Debian (which is supported by Ubuntu 14.04) is not included MySQL database deployment. For a quick test I'm using the DBText as DB engine, and using command to add user will not succeed. Because the DBText engine requires email field, however the opensipsctl interface doesn't understand, so we should add some subscribers by adding some lines to Subscriber table, basically is located under path **/usr/local/etc/opensips/dbtext**, e.g: > > 1:brian:192.168.186.129:password:123456:xxx:xxx:xxx > 2:julia:192.168.186.129:password:123456:xxx:xxx:xxx > > > Example above using the ip which is the virtual machine ip. Good luck.
19,533,246
I want to know How to find out difference between normal mkdir directory and svn checkout directory?
2013/10/23
[ "https://Stackoverflow.com/questions/19533246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2866881/" ]
After reading your question and comment, I would suggest you to use one2many relation between two objects and keep one2many list view inside partner, from where one can create the record , does not need to select the partner and record is created only for that partner. Cheers, Parthiv
Google OpenERP \_defaults (a dictionary) and default\_get (a method).
1,255,721
I have installed R in my Ubuntu (18.04) system and when I try to install a package I receive the following message (for example when trying to install `dplyr` package): ``` > install.packages('dplyr') Installing package into ‘/home/giwrikas/R/x86_64-pc-linux-gnu-library/4.0’ (as ‘lib’ is unspecified) Warning: unable to access index for repository https://cloud.r-project.org/src/contrib: cannot open URL 'https://cloud.r-project.org/src/contrib/PACKAGES' Warning message: package ‘dplyr’ is not available (for R version 4.0.2) ``` The same error appears with every package. Does anyone know how to solve that ? It seems that the library is not writable and often appears the following message: ``` Would you like to use a personal library instead? (y/n) y Would you like to create a personal library ~/R/pc-linux-gnu-library/3.2 to install packages into? (y/n) y ``` My R version is 4.0.2. The same R version works fine at windows.Thank you in advance
2020/07/02
[ "https://askubuntu.com/questions/1255721", "https://askubuntu.com", "https://askubuntu.com/users/1058780/" ]
Try to switch to other mirror using the following procedure: 1. Open terminal and launch `R` shell 2. In `R` shell switch the mirror by `chooseCRANmirror()` - in opened window choose nearest mirror 3. In `R` shell retry package installation with `install.packages('dplyr')`
The newest version of R that you seem to want can be installed without adding software sources to the default repositories starting in Ubuntu 20.10 which won't be released until November. An earlier version of r-cran-dplyr can be installed right now from the default repositories in 18.04, but it drags in r-base-core 3.4.4 as a dependency. Since you can't have both ideal conditions at that same time, you need to start think clearly about what your priorities are. Do you really need the latest version of dplyr to be installed in not the latest version of Ubuntu, or do you have room to maneuver between the conflicting requirements of different package versions? In Ubuntu 18.04 and later open the terminal and type: ```none sudo apt update sudo apt install r-cran-dplyr # installs r-base-core 3.4.4 as a dependency ``` This GNU R package provides a fast, consistent tool for working with data frame like objects, both in memory and out of memory. r-base-core 4.0 won't land in the default Ubuntu repositories until Ubuntu 20.10.
1,255,721
I have installed R in my Ubuntu (18.04) system and when I try to install a package I receive the following message (for example when trying to install `dplyr` package): ``` > install.packages('dplyr') Installing package into ‘/home/giwrikas/R/x86_64-pc-linux-gnu-library/4.0’ (as ‘lib’ is unspecified) Warning: unable to access index for repository https://cloud.r-project.org/src/contrib: cannot open URL 'https://cloud.r-project.org/src/contrib/PACKAGES' Warning message: package ‘dplyr’ is not available (for R version 4.0.2) ``` The same error appears with every package. Does anyone know how to solve that ? It seems that the library is not writable and often appears the following message: ``` Would you like to use a personal library instead? (y/n) y Would you like to create a personal library ~/R/pc-linux-gnu-library/3.2 to install packages into? (y/n) y ``` My R version is 4.0.2. The same R version works fine at windows.Thank you in advance
2020/07/02
[ "https://askubuntu.com/questions/1255721", "https://askubuntu.com", "https://askubuntu.com/users/1058780/" ]
Are you behind a firewall ? I had to add the proxy to my Renviron.site before proceeding on various servers: `sudo nano /usr/lib/R/etc/Renviron.site` ``` #add following, edit to your proxy http_proxy=http://myproxy.com:8080 https_proxy=http://myproxy.com:8080 ftp_proxy=http://myproxy.com:8080 ```
Try to switch to other mirror using the following procedure: 1. Open terminal and launch `R` shell 2. In `R` shell switch the mirror by `chooseCRANmirror()` - in opened window choose nearest mirror 3. In `R` shell retry package installation with `install.packages('dplyr')`
1,255,721
I have installed R in my Ubuntu (18.04) system and when I try to install a package I receive the following message (for example when trying to install `dplyr` package): ``` > install.packages('dplyr') Installing package into ‘/home/giwrikas/R/x86_64-pc-linux-gnu-library/4.0’ (as ‘lib’ is unspecified) Warning: unable to access index for repository https://cloud.r-project.org/src/contrib: cannot open URL 'https://cloud.r-project.org/src/contrib/PACKAGES' Warning message: package ‘dplyr’ is not available (for R version 4.0.2) ``` The same error appears with every package. Does anyone know how to solve that ? It seems that the library is not writable and often appears the following message: ``` Would you like to use a personal library instead? (y/n) y Would you like to create a personal library ~/R/pc-linux-gnu-library/3.2 to install packages into? (y/n) y ``` My R version is 4.0.2. The same R version works fine at windows.Thank you in advance
2020/07/02
[ "https://askubuntu.com/questions/1255721", "https://askubuntu.com", "https://askubuntu.com/users/1058780/" ]
Are you behind a firewall ? I had to add the proxy to my Renviron.site before proceeding on various servers: `sudo nano /usr/lib/R/etc/Renviron.site` ``` #add following, edit to your proxy http_proxy=http://myproxy.com:8080 https_proxy=http://myproxy.com:8080 ftp_proxy=http://myproxy.com:8080 ```
The newest version of R that you seem to want can be installed without adding software sources to the default repositories starting in Ubuntu 20.10 which won't be released until November. An earlier version of r-cran-dplyr can be installed right now from the default repositories in 18.04, but it drags in r-base-core 3.4.4 as a dependency. Since you can't have both ideal conditions at that same time, you need to start think clearly about what your priorities are. Do you really need the latest version of dplyr to be installed in not the latest version of Ubuntu, or do you have room to maneuver between the conflicting requirements of different package versions? In Ubuntu 18.04 and later open the terminal and type: ```none sudo apt update sudo apt install r-cran-dplyr # installs r-base-core 3.4.4 as a dependency ``` This GNU R package provides a fast, consistent tool for working with data frame like objects, both in memory and out of memory. r-base-core 4.0 won't land in the default Ubuntu repositories until Ubuntu 20.10.
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
a) The probability that a die does not fall higher than $3$ is given by $$P(X\le3)=\frac{3}{6}=\frac{1}{2}$$ So as each event is independent we can find the probability that no die falls higher than three by raising this result to the power of $4$ $$(P(X\le3))^4=\frac{1}{2^4}=\frac{1}{16}$$ b) Similarly the probability that a die does not fall higher than $4$ is given by $$P(X\le4)=\frac{4}{6}=\frac{2}{3}$$ So the final probability is $$(P(X\le4))^4=\frac{2^4}{3^4}=\frac{16}{81}$$ c) If $4$ is the highest rolled value then every die rolled has a value $\le 4$. But we also need at least one $4$ to be rolled - so we need to subtract the probability of rolling every dice $\le3$. The answer is then $$(P(X\le4))^4-(P(X\le3))^4=\frac{16}{81}-\frac{1}{16}=\frac{175}{1296}$$ which is the difference of the answers from a) and b).
Let $D\_i$ be the outcome of the $i$-th die. Denote $D = (D\_1,\dots,D\_4)$. > > So the denominator/sample space should be 6464 right? > > > * Sample space $\Omega = \{1,\dots,6\}^4$ * We use the *cardinality* of $\Omega$ as the denominator, and that of the desired event $E$ as the numerator for (a) and (b). * (a): take $E = \{1,2,3\}^4$, so $P(D \in E) = |E| / |\Omega| = 3^4/6^4 = 1/2^4 = 1/16$ * (b): take $E = \{1,2,3,4\}^4$, so $P(D \in E) = |E| / |\Omega| = 4^4/6^4 = 2^4/3^4 = 16/81$ * (c): take $E = \{1,2,3,4\}^4 \setminus \{1,2,3\}^4$, so $P(D \in E) = (4^4-3^4)/6^4 = 175/1296$ --- Edit in response to OP's question in comments: $$\begin{aligned} & \{\max(D\_1,\dots,D\_4) = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \exists i \in \{1,\dots,4\}, D\_i = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \ne 4) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\}\} \cap \{(\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \}^\complement \\ &= \{1,2,3,4\}^4 \setminus \{1,2,3\}^4 \end{aligned}$$
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
a) The probability that a die does not fall higher than $3$ is given by $$P(X\le3)=\frac{3}{6}=\frac{1}{2}$$ So as each event is independent we can find the probability that no die falls higher than three by raising this result to the power of $4$ $$(P(X\le3))^4=\frac{1}{2^4}=\frac{1}{16}$$ b) Similarly the probability that a die does not fall higher than $4$ is given by $$P(X\le4)=\frac{4}{6}=\frac{2}{3}$$ So the final probability is $$(P(X\le4))^4=\frac{2^4}{3^4}=\frac{16}{81}$$ c) If $4$ is the highest rolled value then every die rolled has a value $\le 4$. But we also need at least one $4$ to be rolled - so we need to subtract the probability of rolling every dice $\le3$. The answer is then $$(P(X\le4))^4-(P(X\le3))^4=\frac{16}{81}-\frac{1}{16}=\frac{175}{1296}$$ which is the difference of the answers from a) and b).
$a)$ The probability that one dice rolls a number equal to $3$ or lower is $\frac{3}{6}=\frac{1}{2}$. Hence, the probability that all of them roll $3$ or lower is $(\frac{1}{2})^4=\frac{1}{16}$. Can you do the same for $b)$? $c)$ Firstly, There is a probability of $(\frac{4}{6})^4=(\frac{256}{1296})$ that all numbers rolled are $4$ or lower. However, at least one of the numbers must **equal** $4$, so we subtract the probability that they are all 3 or lower. We already calculaties this in $a)$. Hence, the probability that the highest number rolled is $4$, equals $$\frac{256}{1296}-\frac{81}{1296}=\frac{175}{1296}$$
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
a) The probability that a die does not fall higher than $3$ is given by $$P(X\le3)=\frac{3}{6}=\frac{1}{2}$$ So as each event is independent we can find the probability that no die falls higher than three by raising this result to the power of $4$ $$(P(X\le3))^4=\frac{1}{2^4}=\frac{1}{16}$$ b) Similarly the probability that a die does not fall higher than $4$ is given by $$P(X\le4)=\frac{4}{6}=\frac{2}{3}$$ So the final probability is $$(P(X\le4))^4=\frac{2^4}{3^4}=\frac{16}{81}$$ c) If $4$ is the highest rolled value then every die rolled has a value $\le 4$. But we also need at least one $4$ to be rolled - so we need to subtract the probability of rolling every dice $\le3$. The answer is then $$(P(X\le4))^4-(P(X\le3))^4=\frac{16}{81}-\frac{1}{16}=\frac{175}{1296}$$ which is the difference of the answers from a) and b).
I'm trying to address your metholodigal doubts, GNUSupporter 8964民主女神 地下教會 already gave a (very brief) answer to your mathematical questions. Probably it's an urban legend, but there was a dispute between two statisticians: If you throw 2 "normal", 6-sided fair dice and add the values, will you get (in the long run) the sum $11$ or the sum $12$ more often, or do they occur with the same probability? Because addition is commutative, the order of the dice (or any other way to distinguish between them) doesn't matter. So one statistician argued that because both for $11$ and $12$ there is (up to exchange of summands) only one way to express them as the sum of 2 integers in the range of $1$ to $6$ ($11=5+6, 12=6+6$), both $11$ and $12$ will occur with the same probability. The other argued that even though the dice may not be distinguishable, they ares still 2 different entities, so it makes a difference that $11=5+6=6+5$ can be summed in two ways, while $12=6+6$ has only one possible sum. If you think about the dice as distinguishable (say one is red, the other green), then it is clear that the 36 outcomes that can happen upon those 2 dice being thrown are (1 on red, 1 on green), (1 on red, 2 on green), ... (1 on red, 6 on green),(2 on red, 1 on green),......(6 on red, 6 on green). It should also be clear that those 36 outcomes all have the same probability: $1 \over 36$, as each outcome requires the red die to have a given value (proability $1 \over 6$), the green die to have a given value (also proability $1 \over 6$) and those events are independent, so the probablity that both happens is the product of the respective probabilities. Now you can also see that the event "one die is a 5, the other a 6" corresponds to 2 of those outcomes: (red is 5, green is 6) and (red is 6, green is 5). That means the probability of that event (which is just another description for "sum is $11$") is ${2 \over 36}= {1\over 18}$. OTOH, the event "both dice are a 6" is just the outcome (red is 6, green is 6), so the probability is ${1 \over 36}$. The moral of that story is that the "order does not matter" argument only affects one part of the reasoning: To calculate the sum, you do not need to know the order. What it gets wrong is that it makes you wrongly belief that the probabilities of the underlying events are the same. To come back to your problem, this will have the same incorrect calculations when you count things as "not considering order". The moment you (corrctly) said that the denominator of all of your probabilities is $6^4$, this means you are (correctly) considering ordered (or as in my example, colored) dice. Because you only get $6^4$ outcomes if you considered ordered/colored dice. In the case of 2 dice, there are 36 outcomes for the ordered/colored dice. 6 of them have the same value for the red and green dice, the other 30 have different values. If you consider unordered/indistinguishable dice, you get 21 outcomes: The 6 same-value pairs are the same as the ordered/colored outcomes, the 30 different-value pairs get halved to 15 (e.g. (red is 1, green is 2) and (red is 2, green is 1) becomes (one die is 1, the other 2) for the unordered/indistinguishable dice). But as we have seen above, those 21 outcomes dont't have equal probabilities, so basing a simple counting argument on them is impossible. So the result of all this is that in case of dice (and usually always if you have outcomes where things can repeat) it is usually imperative to count ordered/distinguishable outcomes, because they are usually the outcomes that all have equal probability. If you count unordered/indistinguishalble outcomes, you will usually make an error because those outcomes are not equally likely.
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
Let $D\_i$ be the outcome of the $i$-th die. Denote $D = (D\_1,\dots,D\_4)$. > > So the denominator/sample space should be 6464 right? > > > * Sample space $\Omega = \{1,\dots,6\}^4$ * We use the *cardinality* of $\Omega$ as the denominator, and that of the desired event $E$ as the numerator for (a) and (b). * (a): take $E = \{1,2,3\}^4$, so $P(D \in E) = |E| / |\Omega| = 3^4/6^4 = 1/2^4 = 1/16$ * (b): take $E = \{1,2,3,4\}^4$, so $P(D \in E) = |E| / |\Omega| = 4^4/6^4 = 2^4/3^4 = 16/81$ * (c): take $E = \{1,2,3,4\}^4 \setminus \{1,2,3\}^4$, so $P(D \in E) = (4^4-3^4)/6^4 = 175/1296$ --- Edit in response to OP's question in comments: $$\begin{aligned} & \{\max(D\_1,\dots,D\_4) = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \exists i \in \{1,\dots,4\}, D\_i = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \ne 4) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\}\} \cap \{(\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \}^\complement \\ &= \{1,2,3,4\}^4 \setminus \{1,2,3\}^4 \end{aligned}$$
$a)$ The probability that one dice rolls a number equal to $3$ or lower is $\frac{3}{6}=\frac{1}{2}$. Hence, the probability that all of them roll $3$ or lower is $(\frac{1}{2})^4=\frac{1}{16}$. Can you do the same for $b)$? $c)$ Firstly, There is a probability of $(\frac{4}{6})^4=(\frac{256}{1296})$ that all numbers rolled are $4$ or lower. However, at least one of the numbers must **equal** $4$, so we subtract the probability that they are all 3 or lower. We already calculaties this in $a)$. Hence, the probability that the highest number rolled is $4$, equals $$\frac{256}{1296}-\frac{81}{1296}=\frac{175}{1296}$$
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
Let $D\_i$ be the outcome of the $i$-th die. Denote $D = (D\_1,\dots,D\_4)$. > > So the denominator/sample space should be 6464 right? > > > * Sample space $\Omega = \{1,\dots,6\}^4$ * We use the *cardinality* of $\Omega$ as the denominator, and that of the desired event $E$ as the numerator for (a) and (b). * (a): take $E = \{1,2,3\}^4$, so $P(D \in E) = |E| / |\Omega| = 3^4/6^4 = 1/2^4 = 1/16$ * (b): take $E = \{1,2,3,4\}^4$, so $P(D \in E) = |E| / |\Omega| = 4^4/6^4 = 2^4/3^4 = 16/81$ * (c): take $E = \{1,2,3,4\}^4 \setminus \{1,2,3\}^4$, so $P(D \in E) = (4^4-3^4)/6^4 = 175/1296$ --- Edit in response to OP's question in comments: $$\begin{aligned} & \{\max(D\_1,\dots,D\_4) = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \exists i \in \{1,\dots,4\}, D\_i = 4\} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \ne 4) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\} \text{ and } \neg (\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \} \\ &= \{\forall i \in \{1,\dots,4\}, D\_i \in \{1,\dots,4\}\} \cap \{(\forall i \in \{1,\dots,4\}, D\_i \in \{1,2,3\}) \}^\complement \\ &= \{1,2,3,4\}^4 \setminus \{1,2,3\}^4 \end{aligned}$$
I'm trying to address your metholodigal doubts, GNUSupporter 8964民主女神 地下教會 already gave a (very brief) answer to your mathematical questions. Probably it's an urban legend, but there was a dispute between two statisticians: If you throw 2 "normal", 6-sided fair dice and add the values, will you get (in the long run) the sum $11$ or the sum $12$ more often, or do they occur with the same probability? Because addition is commutative, the order of the dice (or any other way to distinguish between them) doesn't matter. So one statistician argued that because both for $11$ and $12$ there is (up to exchange of summands) only one way to express them as the sum of 2 integers in the range of $1$ to $6$ ($11=5+6, 12=6+6$), both $11$ and $12$ will occur with the same probability. The other argued that even though the dice may not be distinguishable, they ares still 2 different entities, so it makes a difference that $11=5+6=6+5$ can be summed in two ways, while $12=6+6$ has only one possible sum. If you think about the dice as distinguishable (say one is red, the other green), then it is clear that the 36 outcomes that can happen upon those 2 dice being thrown are (1 on red, 1 on green), (1 on red, 2 on green), ... (1 on red, 6 on green),(2 on red, 1 on green),......(6 on red, 6 on green). It should also be clear that those 36 outcomes all have the same probability: $1 \over 36$, as each outcome requires the red die to have a given value (proability $1 \over 6$), the green die to have a given value (also proability $1 \over 6$) and those events are independent, so the probablity that both happens is the product of the respective probabilities. Now you can also see that the event "one die is a 5, the other a 6" corresponds to 2 of those outcomes: (red is 5, green is 6) and (red is 6, green is 5). That means the probability of that event (which is just another description for "sum is $11$") is ${2 \over 36}= {1\over 18}$. OTOH, the event "both dice are a 6" is just the outcome (red is 6, green is 6), so the probability is ${1 \over 36}$. The moral of that story is that the "order does not matter" argument only affects one part of the reasoning: To calculate the sum, you do not need to know the order. What it gets wrong is that it makes you wrongly belief that the probabilities of the underlying events are the same. To come back to your problem, this will have the same incorrect calculations when you count things as "not considering order". The moment you (corrctly) said that the denominator of all of your probabilities is $6^4$, this means you are (correctly) considering ordered (or as in my example, colored) dice. Because you only get $6^4$ outcomes if you considered ordered/colored dice. In the case of 2 dice, there are 36 outcomes for the ordered/colored dice. 6 of them have the same value for the red and green dice, the other 30 have different values. If you consider unordered/indistinguishable dice, you get 21 outcomes: The 6 same-value pairs are the same as the ordered/colored outcomes, the 30 different-value pairs get halved to 15 (e.g. (red is 1, green is 2) and (red is 2, green is 1) becomes (one die is 1, the other 2) for the unordered/indistinguishable dice). But as we have seen above, those 21 outcomes dont't have equal probabilities, so basing a simple counting argument on them is impossible. So the result of all this is that in case of dice (and usually always if you have outcomes where things can repeat) it is usually imperative to count ordered/distinguishable outcomes, because they are usually the outcomes that all have equal probability. If you count unordered/indistinguishalble outcomes, you will usually make an error because those outcomes are not equally likely.
3,115,334
Four dice are thrown, what's the probability that: a) None of them fall higher than three? b) None of them fall higher than four? c) That four is the highest number thrown? So for a, I wanna think about the denominator first. There are 6 possible outcomes for each dice, and we have four dice. So we're technically picking r out of n objects, aka picking 4 possible values out of 6. So the denominator/sample space should be $6^4$ right? Now this is where I'm getting tripped up. Order technically shouldn't count, because we only care about the quadruplets that don't have a value higher than 3. I might be wrong, maybe I am, but could someone explain a bit more? My professor stated that typically in the sample space/denominator, we want order to count. So I'm trying to think of the numerator now, so we want to find the probability that no values appear higher than 3, so some events that can occur are: $(1, 1, 2, 3), (1, 2, 2, 3), (1, 1, 1, 1)$ etc. Again, I can't see why order should count here, because if we only are concerned about *what* appears rather than *how* they appear, then we can say $(1, 1, 2, 3)$ is equal to $(1, 2, 1, 3)$? So if order does not count, and we have replacement, then does this lead the case where we use $$\binom{n-1+r}{r}$$to find out the probability? I'm pretty sure if I can do a), I could prob do b), but if someone could maybe lead me in the right direction for c) I would appreciate that too!
2019/02/16
[ "https://math.stackexchange.com/questions/3115334", "https://math.stackexchange.com", "https://math.stackexchange.com/users/416804/" ]
I'm trying to address your metholodigal doubts, GNUSupporter 8964民主女神 地下教會 already gave a (very brief) answer to your mathematical questions. Probably it's an urban legend, but there was a dispute between two statisticians: If you throw 2 "normal", 6-sided fair dice and add the values, will you get (in the long run) the sum $11$ or the sum $12$ more often, or do they occur with the same probability? Because addition is commutative, the order of the dice (or any other way to distinguish between them) doesn't matter. So one statistician argued that because both for $11$ and $12$ there is (up to exchange of summands) only one way to express them as the sum of 2 integers in the range of $1$ to $6$ ($11=5+6, 12=6+6$), both $11$ and $12$ will occur with the same probability. The other argued that even though the dice may not be distinguishable, they ares still 2 different entities, so it makes a difference that $11=5+6=6+5$ can be summed in two ways, while $12=6+6$ has only one possible sum. If you think about the dice as distinguishable (say one is red, the other green), then it is clear that the 36 outcomes that can happen upon those 2 dice being thrown are (1 on red, 1 on green), (1 on red, 2 on green), ... (1 on red, 6 on green),(2 on red, 1 on green),......(6 on red, 6 on green). It should also be clear that those 36 outcomes all have the same probability: $1 \over 36$, as each outcome requires the red die to have a given value (proability $1 \over 6$), the green die to have a given value (also proability $1 \over 6$) and those events are independent, so the probablity that both happens is the product of the respective probabilities. Now you can also see that the event "one die is a 5, the other a 6" corresponds to 2 of those outcomes: (red is 5, green is 6) and (red is 6, green is 5). That means the probability of that event (which is just another description for "sum is $11$") is ${2 \over 36}= {1\over 18}$. OTOH, the event "both dice are a 6" is just the outcome (red is 6, green is 6), so the probability is ${1 \over 36}$. The moral of that story is that the "order does not matter" argument only affects one part of the reasoning: To calculate the sum, you do not need to know the order. What it gets wrong is that it makes you wrongly belief that the probabilities of the underlying events are the same. To come back to your problem, this will have the same incorrect calculations when you count things as "not considering order". The moment you (corrctly) said that the denominator of all of your probabilities is $6^4$, this means you are (correctly) considering ordered (or as in my example, colored) dice. Because you only get $6^4$ outcomes if you considered ordered/colored dice. In the case of 2 dice, there are 36 outcomes for the ordered/colored dice. 6 of them have the same value for the red and green dice, the other 30 have different values. If you consider unordered/indistinguishable dice, you get 21 outcomes: The 6 same-value pairs are the same as the ordered/colored outcomes, the 30 different-value pairs get halved to 15 (e.g. (red is 1, green is 2) and (red is 2, green is 1) becomes (one die is 1, the other 2) for the unordered/indistinguishable dice). But as we have seen above, those 21 outcomes dont't have equal probabilities, so basing a simple counting argument on them is impossible. So the result of all this is that in case of dice (and usually always if you have outcomes where things can repeat) it is usually imperative to count ordered/distinguishable outcomes, because they are usually the outcomes that all have equal probability. If you count unordered/indistinguishalble outcomes, you will usually make an error because those outcomes are not equally likely.
$a)$ The probability that one dice rolls a number equal to $3$ or lower is $\frac{3}{6}=\frac{1}{2}$. Hence, the probability that all of them roll $3$ or lower is $(\frac{1}{2})^4=\frac{1}{16}$. Can you do the same for $b)$? $c)$ Firstly, There is a probability of $(\frac{4}{6})^4=(\frac{256}{1296})$ that all numbers rolled are $4$ or lower. However, at least one of the numbers must **equal** $4$, so we subtract the probability that they are all 3 or lower. We already calculaties this in $a)$. Hence, the probability that the highest number rolled is $4$, equals $$\frac{256}{1296}-\frac{81}{1296}=\frac{175}{1296}$$
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
Accepted answers aren't always right even on Stack Overflow. I've downvoted some that were just plain wrong, leaving comments as to how they were wrong. Presumably they were accepted because their advice happened to work in the original poster's exact situation. The accepted answer gets 15 rep and sits at the top of the answers. The most-voted other answer is right below it, and it's easy to see if the votes suggest that it's better. I don't think wrongly accepted answers are much of a problem. As far as voting goes, we're pretty well stuck with the people we can get, and they will vote as they see fit. We can encourage answers we like with comments and votes, and that's about all we can do (aside from closing/deleting/flagging unsuitable questions and answers). Any deviation from the standard SE model would require enough justification to make the SE team think it worthwhile, which means that coming up with a proposal that would be useful for multiple sites would be almost essential. As a practical matter, I think this unlikely.
I don't see a problem. OPs simply should accept the best answer. See also: [The best posts of Skeptics!](https://skeptics.meta.stackexchange.com/questions/442/the-best-posts-of-skeptics)
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
I think this is rather like going on Wikipedia and telling them that an encyclopedia anyone can edit is a bad idea. That may be so, but that's the entire point of the endeavor. The [Area 51](http://area51.stackexchange.com/) process exists to apply a model that has created [one of the best programming Q&A sites in the world](http://www.stackoverflow.com/) and apply it to [all sorts of crazy new topics](http://stackexchange.com/sites). This is our attempt at applying it to scientific skepticism. If you don't think it works, there are plenty of other websites that attempt different approaches. Remember, accepted answers are not set in stone. [Questioners can change them at any time.](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) I certainly would not hesitate to do so if someone posted a better answer to one of my questions. If you think the accepted answer to a question (or any answer for that matter) is not a good one, all you have to do is *write a better answer*. I can't get behind any major changes until some evidence is produced that indicates the status quo is broken, and I have seen no such evidence. The example you cite doesn't appear to indicate that we're doing something wrong. Quite the contrary, it's an example of a how easily an answer on this site can be improved significantly. ![If it ain't broke, don't fix it.](https://i.stack.imgur.com/Rr82o.jpg) [source](http://www.xtri.com/features/detail/284-itemId.511710351.html)
I don't see a problem. OPs simply should accept the best answer. See also: [The best posts of Skeptics!](https://skeptics.meta.stackexchange.com/questions/442/the-best-posts-of-skeptics)
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
There is, I think, a real problem applying the stack exchange model here and I think the issues is highlighted in the question's summary of how the whole SE process works: > > The basics of the Stack Exchange Model are very simple. > > > * Answer-Acceptance shows that a the Asker of a question **likes an answer** best. > * Answer-Voting shows that other users **like an answer**. > * The usefulness of this Model on a given subject is defined by the **usefulness** of > these two pieces of data. > > > The problem is that scientific skepticism isn't about whether you **like** a particular result but should be about whether *that result can be justified by evidence.* Answers that people like will frequently not overlap with that objective standard. In fact, they will often be the answers that reflect consensus *prejudice* of the day, what C H Waddington described as the COnventional Wisdom of the domiNant Group (or COWDUNG for short, not sure where the "U" comes from) in his great book about how mental models help us understand the world, [Tools For Thought](http://books.google.co.uk/books?id=FntQAAAAMAAJ&q=tools%20for%20thought%20waddington&dq=tools%20for%20thought%20waddington&hl=en&sa=X&ei=-AsMUOutFPK10QXAjYStCg&redir_esc=y). The standard that is most rigorously applied that distinguishes Skeptics from other SE sites is the citation. We don't like answers that don't link to published sources of evidence. But there is a highly significant problem with that rule: selective quotation. The scientific literature is full of perfectly good but contradictory evidence (it is also full of much badly conducted junk that sailed through peer-review unscathed). So it is often very easy to back a particular prejudice with perfectly valid citations. In medical research the counterweight to this is the *meta-analysis* which tries to objectively assess the weight of evidence and the quality of evidence from many sources. The skeptics approach neither demands nor applies extra weight to meta analyses and the pattern of votes on some questions suggests that a meta analysis carries little weight with the voting community. As evidence I refer to this question: [Is routine screening for breast cancer for asymptomatic women worthwhile?](https://skeptics.stackexchange.com/questions/6473/is-routine-screening-for-breast-cancer-for-asymptomatic-women-worthwhile) To be fair I may be biased in the interpretation because i wrote the question and the lowest scored answer, but the comment threads, I think, show the problem I'm referring to. My answer summarised the latest Cochrane review (and those reviews are supposed to be the highest standard of evidence in epidemiology or medicine). But the results of the review challenge a couple of decades of clinical orthodoxy. The top voted answer finds a handful of papers that clearly take the conventional position; the second answer summarises the results of the review by the body who triggered the debate by changing their advice (and really baked down and hedged their bets in the face of public sentiment). Maybe i'm not able to see this clearly because it is my answer, but it seems to me that the voting pattern is more easily explained by voters initial prejudice than by a judgement about the quality of evidence. So that is my view of the problem. I don't have any clear ideas how to fix it.
I don't see a problem. OPs simply should accept the best answer. See also: [The best posts of Skeptics!](https://skeptics.meta.stackexchange.com/questions/442/the-best-posts-of-skeptics)
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
From my point of view, the "Accepted Answer" for questions on this site is a bit of an issue, largely because science does allow for things to change and what may be a perfectly valid accepted answer could be completely negated several months later by new data. However, there is also an answer for this built into science already, namely, peer review of existing data and periodic review of older conclusions to ensure they are still valid when new data is presented. If we were to apply this to the "Accepted Answer" paradigm that is currently in place we could add a sufficient check into place by just adding a new flag to answers, namely, "Flag for Peer Review." If an answer was flagged for peer review, a moderator (or a group of trusted users) could review the question and answer, and if the answer was no longer valid, the "Accepted Answer" flag could be removed. The distribution of reputation is still an issue with the proposal as I don't feel that you should lose reputation for what was once a valid accepted answer; however, by removing the flag we would ensure that new answers could bubble up and replace the previous answer. Furthermore, this would also ensure, that accepted answers are not taken a gospel by someone that is searching for an answer to a question on Google.
I don't see a problem. OPs simply should accept the best answer. See also: [The best posts of Skeptics!](https://skeptics.meta.stackexchange.com/questions/442/the-best-posts-of-skeptics)
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
Accepted answers aren't always right even on Stack Overflow. I've downvoted some that were just plain wrong, leaving comments as to how they were wrong. Presumably they were accepted because their advice happened to work in the original poster's exact situation. The accepted answer gets 15 rep and sits at the top of the answers. The most-voted other answer is right below it, and it's easy to see if the votes suggest that it's better. I don't think wrongly accepted answers are much of a problem. As far as voting goes, we're pretty well stuck with the people we can get, and they will vote as they see fit. We can encourage answers we like with comments and votes, and that's about all we can do (aside from closing/deleting/flagging unsuitable questions and answers). Any deviation from the standard SE model would require enough justification to make the SE team think it worthwhile, which means that coming up with a proposal that would be useful for multiple sites would be almost essential. As a practical matter, I think this unlikely.
I think this is rather like going on Wikipedia and telling them that an encyclopedia anyone can edit is a bad idea. That may be so, but that's the entire point of the endeavor. The [Area 51](http://area51.stackexchange.com/) process exists to apply a model that has created [one of the best programming Q&A sites in the world](http://www.stackoverflow.com/) and apply it to [all sorts of crazy new topics](http://stackexchange.com/sites). This is our attempt at applying it to scientific skepticism. If you don't think it works, there are plenty of other websites that attempt different approaches. Remember, accepted answers are not set in stone. [Questioners can change them at any time.](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) I certainly would not hesitate to do so if someone posted a better answer to one of my questions. If you think the accepted answer to a question (or any answer for that matter) is not a good one, all you have to do is *write a better answer*. I can't get behind any major changes until some evidence is produced that indicates the status quo is broken, and I have seen no such evidence. The example you cite doesn't appear to indicate that we're doing something wrong. Quite the contrary, it's an example of a how easily an answer on this site can be improved significantly. ![If it ain't broke, don't fix it.](https://i.stack.imgur.com/Rr82o.jpg) [source](http://www.xtri.com/features/detail/284-itemId.511710351.html)
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
Accepted answers aren't always right even on Stack Overflow. I've downvoted some that were just plain wrong, leaving comments as to how they were wrong. Presumably they were accepted because their advice happened to work in the original poster's exact situation. The accepted answer gets 15 rep and sits at the top of the answers. The most-voted other answer is right below it, and it's easy to see if the votes suggest that it's better. I don't think wrongly accepted answers are much of a problem. As far as voting goes, we're pretty well stuck with the people we can get, and they will vote as they see fit. We can encourage answers we like with comments and votes, and that's about all we can do (aside from closing/deleting/flagging unsuitable questions and answers). Any deviation from the standard SE model would require enough justification to make the SE team think it worthwhile, which means that coming up with a proposal that would be useful for multiple sites would be almost essential. As a practical matter, I think this unlikely.
There is, I think, a real problem applying the stack exchange model here and I think the issues is highlighted in the question's summary of how the whole SE process works: > > The basics of the Stack Exchange Model are very simple. > > > * Answer-Acceptance shows that a the Asker of a question **likes an answer** best. > * Answer-Voting shows that other users **like an answer**. > * The usefulness of this Model on a given subject is defined by the **usefulness** of > these two pieces of data. > > > The problem is that scientific skepticism isn't about whether you **like** a particular result but should be about whether *that result can be justified by evidence.* Answers that people like will frequently not overlap with that objective standard. In fact, they will often be the answers that reflect consensus *prejudice* of the day, what C H Waddington described as the COnventional Wisdom of the domiNant Group (or COWDUNG for short, not sure where the "U" comes from) in his great book about how mental models help us understand the world, [Tools For Thought](http://books.google.co.uk/books?id=FntQAAAAMAAJ&q=tools%20for%20thought%20waddington&dq=tools%20for%20thought%20waddington&hl=en&sa=X&ei=-AsMUOutFPK10QXAjYStCg&redir_esc=y). The standard that is most rigorously applied that distinguishes Skeptics from other SE sites is the citation. We don't like answers that don't link to published sources of evidence. But there is a highly significant problem with that rule: selective quotation. The scientific literature is full of perfectly good but contradictory evidence (it is also full of much badly conducted junk that sailed through peer-review unscathed). So it is often very easy to back a particular prejudice with perfectly valid citations. In medical research the counterweight to this is the *meta-analysis* which tries to objectively assess the weight of evidence and the quality of evidence from many sources. The skeptics approach neither demands nor applies extra weight to meta analyses and the pattern of votes on some questions suggests that a meta analysis carries little weight with the voting community. As evidence I refer to this question: [Is routine screening for breast cancer for asymptomatic women worthwhile?](https://skeptics.stackexchange.com/questions/6473/is-routine-screening-for-breast-cancer-for-asymptomatic-women-worthwhile) To be fair I may be biased in the interpretation because i wrote the question and the lowest scored answer, but the comment threads, I think, show the problem I'm referring to. My answer summarised the latest Cochrane review (and those reviews are supposed to be the highest standard of evidence in epidemiology or medicine). But the results of the review challenge a couple of decades of clinical orthodoxy. The top voted answer finds a handful of papers that clearly take the conventional position; the second answer summarises the results of the review by the body who triggered the debate by changing their advice (and really baked down and hedged their bets in the face of public sentiment). Maybe i'm not able to see this clearly because it is my answer, but it seems to me that the voting pattern is more easily explained by voters initial prejudice than by a judgement about the quality of evidence. So that is my view of the problem. I don't have any clear ideas how to fix it.
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
Accepted answers aren't always right even on Stack Overflow. I've downvoted some that were just plain wrong, leaving comments as to how they were wrong. Presumably they were accepted because their advice happened to work in the original poster's exact situation. The accepted answer gets 15 rep and sits at the top of the answers. The most-voted other answer is right below it, and it's easy to see if the votes suggest that it's better. I don't think wrongly accepted answers are much of a problem. As far as voting goes, we're pretty well stuck with the people we can get, and they will vote as they see fit. We can encourage answers we like with comments and votes, and that's about all we can do (aside from closing/deleting/flagging unsuitable questions and answers). Any deviation from the standard SE model would require enough justification to make the SE team think it worthwhile, which means that coming up with a proposal that would be useful for multiple sites would be almost essential. As a practical matter, I think this unlikely.
From my point of view, the "Accepted Answer" for questions on this site is a bit of an issue, largely because science does allow for things to change and what may be a perfectly valid accepted answer could be completely negated several months later by new data. However, there is also an answer for this built into science already, namely, peer review of existing data and periodic review of older conclusions to ensure they are still valid when new data is presented. If we were to apply this to the "Accepted Answer" paradigm that is currently in place we could add a sufficient check into place by just adding a new flag to answers, namely, "Flag for Peer Review." If an answer was flagged for peer review, a moderator (or a group of trusted users) could review the question and answer, and if the answer was no longer valid, the "Accepted Answer" flag could be removed. The distribution of reputation is still an issue with the proposal as I don't feel that you should lose reputation for what was once a valid accepted answer; however, by removing the flag we would ensure that new answers could bubble up and replace the previous answer. Furthermore, this would also ensure, that accepted answers are not taken a gospel by someone that is searching for an answer to a question on Google.
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
I think this is rather like going on Wikipedia and telling them that an encyclopedia anyone can edit is a bad idea. That may be so, but that's the entire point of the endeavor. The [Area 51](http://area51.stackexchange.com/) process exists to apply a model that has created [one of the best programming Q&A sites in the world](http://www.stackoverflow.com/) and apply it to [all sorts of crazy new topics](http://stackexchange.com/sites). This is our attempt at applying it to scientific skepticism. If you don't think it works, there are plenty of other websites that attempt different approaches. Remember, accepted answers are not set in stone. [Questioners can change them at any time.](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) I certainly would not hesitate to do so if someone posted a better answer to one of my questions. If you think the accepted answer to a question (or any answer for that matter) is not a good one, all you have to do is *write a better answer*. I can't get behind any major changes until some evidence is produced that indicates the status quo is broken, and I have seen no such evidence. The example you cite doesn't appear to indicate that we're doing something wrong. Quite the contrary, it's an example of a how easily an answer on this site can be improved significantly. ![If it ain't broke, don't fix it.](https://i.stack.imgur.com/Rr82o.jpg) [source](http://www.xtri.com/features/detail/284-itemId.511710351.html)
From my point of view, the "Accepted Answer" for questions on this site is a bit of an issue, largely because science does allow for things to change and what may be a perfectly valid accepted answer could be completely negated several months later by new data. However, there is also an answer for this built into science already, namely, peer review of existing data and periodic review of older conclusions to ensure they are still valid when new data is presented. If we were to apply this to the "Accepted Answer" paradigm that is currently in place we could add a sufficient check into place by just adding a new flag to answers, namely, "Flag for Peer Review." If an answer was flagged for peer review, a moderator (or a group of trusted users) could review the question and answer, and if the answer was no longer valid, the "Accepted Answer" flag could be removed. The distribution of reputation is still an issue with the proposal as I don't feel that you should lose reputation for what was once a valid accepted answer; however, by removing the flag we would ensure that new answers could bubble up and replace the previous answer. Furthermore, this would also ensure, that accepted answers are not taken a gospel by someone that is searching for an answer to a question on Google.
584
I feel like there might be a fundamental issue with the format of this website. Overview -------- The StackExchange model works well for subjects where the question is posed for the purpose of helping the asker, and answers can be deemed "correct" based on how well they help the asker. On a site like StackOverflow, this works very well and produces "good" answers often because the Asker simply selects an answer that fixes his problem--a relatively objective test. When there are multiple answers that satisfy the "fix the problem" constraint, the one that is easiest for the asker to understand is often picked. This produces highly desirable answers--easy to understand, and with verifiable accuracy. In addition, answers with high user-ratings signify answers which are considered "better" by the programming community in most cases. Sites like Programmers.SE use the same model for more subjective questions. In many cases, it is difficult for an asker to select a single "correct" answer, as quite often there is none with subjective questions. On these subjective sites, the availability of multiple highly-user-rated answers seems to be the most useful, as they tend to contain well-written explanations of popular opinions on the subject. We see quite often on Programmers.SE many highly-rated yet contradicting answers. Problem ------- On Skeptics, however, this model seems to fall apart rather quickly. When a user asks his question, ideally, his motive is to seek the truth about some belief. The selected answer, then, is supposed to be the "most true" out of all the answers. Highly rated answers are also supposed to be those considered to be well researched, and filled with facts. These criteria seem incredibly hard to test, though. * An asker of a question cannot ascertain the truth of an answer better than anyone else. * There is no test for the Truth of an answer. Even if we remove "truth" from the equation and simply choose "well-researched" as the criteria, it's difficult to determine that either Answer-Acceptance or Answer-Votes correlates to how well researched an answer is. It is certainly quite hard to correlate either of them to truth. Summary ------- The basics of the Stack Exchange Model are very simple. * Answer-Acceptance shows that a the Asker of a question likes an answer best. * Answer-Voting shows that other users like an answer. * The usefulness of this Model on a given subject is defined by the usefulness of these two pieces of data. On Skeptics, with the current configuration of this model, this data doesn't necessarily correlate to the goal of scientific skepticism. Example ------- Recently the following question was posed on Skeptics. [Do rich companies pay little/no corporate income taxes in the United States?](https://skeptics.stackexchange.com/questions/2059/do-rich-companies-pay-little-no-corporate-income-taxes-in-the-united-states) The original question asks both "Do companies pay little to no taxes in the US?" and "Is it possible for a company to pay little to no taxes in the US?" At the time of its acceptance, the top answer on this question answered neither of these questions. It merely listed a number of ways corporations could reduce their taxes and stated "Yes, it is possible." After an edit, the answer now lists some data about how much money various corporations paid in taxes in recent years, but no comparative scale is given to tell if these are actually "little-to-no taxes." Yet, regardless of the fact that the question asked is not directly answered, the given answer is well-rated, and the answer is accepted by the asker. Possible Fixes -------------- I've been thinking of some possible changes which could be made to fix this issue for skeptics--ranging in difficulty-to-implement. 1. Remove the "Accept Answer" option for question askers. * Questions are asked here because it is hard to verify the answer. No one user should be able to verify an answer. 2. Organize Answers into two categories, as either Proving or Disproving a belief. * We can shift the focus of answering to collecting research, rather than determining truth. * Seeking good data will be rewarded regardless of the conclusions of the data, helping remove bias. 3. Increase reputation amounts for asking questions. * This attempts to make it so the question-asking population is more likely to have the ideals and purpose of Skeptics at heart. Conclusion ---------- The StackExchange model doesn't seem to work for the objective task of Skeptical analysis. The current implementation is flawed, but there may be some things we can do about it. I would love to hear other opinions on this as well.
2011/04/22
[ "https://skeptics.meta.stackexchange.com/questions/584", "https://skeptics.meta.stackexchange.com", "https://skeptics.meta.stackexchange.com/users/1840/" ]
There is, I think, a real problem applying the stack exchange model here and I think the issues is highlighted in the question's summary of how the whole SE process works: > > The basics of the Stack Exchange Model are very simple. > > > * Answer-Acceptance shows that a the Asker of a question **likes an answer** best. > * Answer-Voting shows that other users **like an answer**. > * The usefulness of this Model on a given subject is defined by the **usefulness** of > these two pieces of data. > > > The problem is that scientific skepticism isn't about whether you **like** a particular result but should be about whether *that result can be justified by evidence.* Answers that people like will frequently not overlap with that objective standard. In fact, they will often be the answers that reflect consensus *prejudice* of the day, what C H Waddington described as the COnventional Wisdom of the domiNant Group (or COWDUNG for short, not sure where the "U" comes from) in his great book about how mental models help us understand the world, [Tools For Thought](http://books.google.co.uk/books?id=FntQAAAAMAAJ&q=tools%20for%20thought%20waddington&dq=tools%20for%20thought%20waddington&hl=en&sa=X&ei=-AsMUOutFPK10QXAjYStCg&redir_esc=y). The standard that is most rigorously applied that distinguishes Skeptics from other SE sites is the citation. We don't like answers that don't link to published sources of evidence. But there is a highly significant problem with that rule: selective quotation. The scientific literature is full of perfectly good but contradictory evidence (it is also full of much badly conducted junk that sailed through peer-review unscathed). So it is often very easy to back a particular prejudice with perfectly valid citations. In medical research the counterweight to this is the *meta-analysis* which tries to objectively assess the weight of evidence and the quality of evidence from many sources. The skeptics approach neither demands nor applies extra weight to meta analyses and the pattern of votes on some questions suggests that a meta analysis carries little weight with the voting community. As evidence I refer to this question: [Is routine screening for breast cancer for asymptomatic women worthwhile?](https://skeptics.stackexchange.com/questions/6473/is-routine-screening-for-breast-cancer-for-asymptomatic-women-worthwhile) To be fair I may be biased in the interpretation because i wrote the question and the lowest scored answer, but the comment threads, I think, show the problem I'm referring to. My answer summarised the latest Cochrane review (and those reviews are supposed to be the highest standard of evidence in epidemiology or medicine). But the results of the review challenge a couple of decades of clinical orthodoxy. The top voted answer finds a handful of papers that clearly take the conventional position; the second answer summarises the results of the review by the body who triggered the debate by changing their advice (and really baked down and hedged their bets in the face of public sentiment). Maybe i'm not able to see this clearly because it is my answer, but it seems to me that the voting pattern is more easily explained by voters initial prejudice than by a judgement about the quality of evidence. So that is my view of the problem. I don't have any clear ideas how to fix it.
From my point of view, the "Accepted Answer" for questions on this site is a bit of an issue, largely because science does allow for things to change and what may be a perfectly valid accepted answer could be completely negated several months later by new data. However, there is also an answer for this built into science already, namely, peer review of existing data and periodic review of older conclusions to ensure they are still valid when new data is presented. If we were to apply this to the "Accepted Answer" paradigm that is currently in place we could add a sufficient check into place by just adding a new flag to answers, namely, "Flag for Peer Review." If an answer was flagged for peer review, a moderator (or a group of trusted users) could review the question and answer, and if the answer was no longer valid, the "Accepted Answer" flag could be removed. The distribution of reputation is still an issue with the proposal as I don't feel that you should lose reputation for what was once a valid accepted answer; however, by removing the flag we would ensure that new answers could bubble up and replace the previous answer. Furthermore, this would also ensure, that accepted answers are not taken a gospel by someone that is searching for an answer to a question on Google.
2,876,672
I have 2 different controller actions. As seen below, one calls the same view as the other one. The fitness version has a bunch of jquery ui tabs. ``` public ActionResult FitnessByTab(string tab, DateTime entryDate) { return View("Fitness", GetFitnessVM(DateTime.Today.Date)); } public ActionResult Fitness() { return View(GetFitnessVM(DateTime.Today.Date)); } private FitnessVM GetFitnessVM(DateTime dt) { FitnessVM vm = new FitnessVM(); vm.Date = dt; // a bunch of other date that comes from a database return vm; } ``` the issue is that on the action FitnessByTab() the tabs dont load correctly but on the Fitness() it loads fine. How could this be as my understanding is that they would be going through the same code path at that point. As you can see i am hard coded both to the same date to make sure its not a different date causing the issue. EDIT ---- Issues has been solved. It was the relative referencing of all my links. I didn't get any issues until i used firebug that highlighted some missing references due to **"../../"** instead of **Url.Content("**
2010/05/20
[ "https://Stackoverflow.com/questions/2876672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
This is just a function that uses the `XMLHttpRequest` object to perform asynchronous requests for HTML in order to update the existing document. Its not a pattern per se, its just one of many ways to dynamically update the document. Its not 'server-side Ajax' (whats that?), its just plain simple ajax used to update the page. Why you would use it? To avoid to have to refresh the entire page when only a small section needs to be updated. No competent developer would use this to obfuscate. If you can use the same? Sure.. if thats what you need. If you should? Why not - if thats what you need.
What's the problem? It seems to me it is just someone's home rolled ajax update helper function. Many of us have written lots of those through the times.
2,876,672
I have 2 different controller actions. As seen below, one calls the same view as the other one. The fitness version has a bunch of jquery ui tabs. ``` public ActionResult FitnessByTab(string tab, DateTime entryDate) { return View("Fitness", GetFitnessVM(DateTime.Today.Date)); } public ActionResult Fitness() { return View(GetFitnessVM(DateTime.Today.Date)); } private FitnessVM GetFitnessVM(DateTime dt) { FitnessVM vm = new FitnessVM(); vm.Date = dt; // a bunch of other date that comes from a database return vm; } ``` the issue is that on the action FitnessByTab() the tabs dont load correctly but on the Fitness() it loads fine. How could this be as my understanding is that they would be going through the same code path at that point. As you can see i am hard coded both to the same date to make sure its not a different date causing the issue. EDIT ---- Issues has been solved. It was the relative referencing of all my links. I didn't get any issues until i used firebug that highlighted some missing references due to **"../../"** instead of **Url.Content("**
2010/05/20
[ "https://Stackoverflow.com/questions/2876672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Not sure what you're exactly asking here, but the function given is actually fairly simple. Decoding the variables / parameters: * e = AJAX request object * c = Page to send AJAX request to * f = Loading text to be displayed in specified element b * b = id of element to display result in * a = Function to call if ajax request succeeds * d = boolean - if true, display an error on failure Exactly why they're using this particular method I can't really say - seeing the complete page that uses this functionality may help. I don't think it's hiding any design details. It does look a slightly odd way of doing things to me, but as I said above, there may be specific reasons for this in the way the page it's being used in works. Can you use this code? Certainly. Should you use this code? The answer to that is: Is it the right tool for the job? How difficult would it be to convert your existing code to use this method? That depends on your existing code and whether this is the right tool for the job.
This is just a function that uses the `XMLHttpRequest` object to perform asynchronous requests for HTML in order to update the existing document. Its not a pattern per se, its just one of many ways to dynamically update the document. Its not 'server-side Ajax' (whats that?), its just plain simple ajax used to update the page. Why you would use it? To avoid to have to refresh the entire page when only a small section needs to be updated. No competent developer would use this to obfuscate. If you can use the same? Sure.. if thats what you need. If you should? Why not - if thats what you need.
2,876,672
I have 2 different controller actions. As seen below, one calls the same view as the other one. The fitness version has a bunch of jquery ui tabs. ``` public ActionResult FitnessByTab(string tab, DateTime entryDate) { return View("Fitness", GetFitnessVM(DateTime.Today.Date)); } public ActionResult Fitness() { return View(GetFitnessVM(DateTime.Today.Date)); } private FitnessVM GetFitnessVM(DateTime dt) { FitnessVM vm = new FitnessVM(); vm.Date = dt; // a bunch of other date that comes from a database return vm; } ``` the issue is that on the action FitnessByTab() the tabs dont load correctly but on the Fitness() it loads fine. How could this be as my understanding is that they would be going through the same code path at that point. As you can see i am hard coded both to the same date to make sure its not a different date causing the issue. EDIT ---- Issues has been solved. It was the relative referencing of all my links. I didn't get any issues until i used firebug that highlighted some missing references due to **"../../"** instead of **Url.Content("**
2010/05/20
[ "https://Stackoverflow.com/questions/2876672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Not sure what you're exactly asking here, but the function given is actually fairly simple. Decoding the variables / parameters: * e = AJAX request object * c = Page to send AJAX request to * f = Loading text to be displayed in specified element b * b = id of element to display result in * a = Function to call if ajax request succeeds * d = boolean - if true, display an error on failure Exactly why they're using this particular method I can't really say - seeing the complete page that uses this functionality may help. I don't think it's hiding any design details. It does look a slightly odd way of doing things to me, but as I said above, there may be specific reasons for this in the way the page it's being used in works. Can you use this code? Certainly. Should you use this code? The answer to that is: Is it the right tool for the job? How difficult would it be to convert your existing code to use this method? That depends on your existing code and whether this is the right tool for the job.
What's the problem? It seems to me it is just someone's home rolled ajax update helper function. Many of us have written lots of those through the times.
2,876,672
I have 2 different controller actions. As seen below, one calls the same view as the other one. The fitness version has a bunch of jquery ui tabs. ``` public ActionResult FitnessByTab(string tab, DateTime entryDate) { return View("Fitness", GetFitnessVM(DateTime.Today.Date)); } public ActionResult Fitness() { return View(GetFitnessVM(DateTime.Today.Date)); } private FitnessVM GetFitnessVM(DateTime dt) { FitnessVM vm = new FitnessVM(); vm.Date = dt; // a bunch of other date that comes from a database return vm; } ``` the issue is that on the action FitnessByTab() the tabs dont load correctly but on the Fitness() it loads fine. How could this be as my understanding is that they would be going through the same code path at that point. As you can see i am hard coded both to the same date to make sure its not a different date causing the issue. EDIT ---- Issues has been solved. It was the relative referencing of all my links. I didn't get any issues until i used firebug that highlighted some missing references due to **"../../"** instead of **Url.Content("**
2010/05/20
[ "https://Stackoverflow.com/questions/2876672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
[AJAX](http://en.wikipedia.org/wiki/Ajax_(programming)) is just a buzz word for using [`XMLHttpRequest`](http://en.wikipedia.org/wiki/XMLHttpRequest) to load web content asynchronously from the server into your web document. That function call is a plain `XMLHttpRequest` call that requests data from `page.php` (asynchronously without reloading the page) and puts all the response text into `document.getElementById(b).innerHTML`. Finally it appears to call the `LoadSamples()` callback, when the response is received.
What's the problem? It seems to me it is just someone's home rolled ajax update helper function. Many of us have written lots of those through the times.
2,876,672
I have 2 different controller actions. As seen below, one calls the same view as the other one. The fitness version has a bunch of jquery ui tabs. ``` public ActionResult FitnessByTab(string tab, DateTime entryDate) { return View("Fitness", GetFitnessVM(DateTime.Today.Date)); } public ActionResult Fitness() { return View(GetFitnessVM(DateTime.Today.Date)); } private FitnessVM GetFitnessVM(DateTime dt) { FitnessVM vm = new FitnessVM(); vm.Date = dt; // a bunch of other date that comes from a database return vm; } ``` the issue is that on the action FitnessByTab() the tabs dont load correctly but on the Fitness() it loads fine. How could this be as my understanding is that they would be going through the same code path at that point. As you can see i am hard coded both to the same date to make sure its not a different date causing the issue. EDIT ---- Issues has been solved. It was the relative referencing of all my links. I didn't get any issues until i used firebug that highlighted some missing references due to **"../../"** instead of **Url.Content("**
2010/05/20
[ "https://Stackoverflow.com/questions/2876672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
Not sure what you're exactly asking here, but the function given is actually fairly simple. Decoding the variables / parameters: * e = AJAX request object * c = Page to send AJAX request to * f = Loading text to be displayed in specified element b * b = id of element to display result in * a = Function to call if ajax request succeeds * d = boolean - if true, display an error on failure Exactly why they're using this particular method I can't really say - seeing the complete page that uses this functionality may help. I don't think it's hiding any design details. It does look a slightly odd way of doing things to me, but as I said above, there may be specific reasons for this in the way the page it's being used in works. Can you use this code? Certainly. Should you use this code? The answer to that is: Is it the right tool for the job? How difficult would it be to convert your existing code to use this method? That depends on your existing code and whether this is the right tool for the job.
[AJAX](http://en.wikipedia.org/wiki/Ajax_(programming)) is just a buzz word for using [`XMLHttpRequest`](http://en.wikipedia.org/wiki/XMLHttpRequest) to load web content asynchronously from the server into your web document. That function call is a plain `XMLHttpRequest` call that requests data from `page.php` (asynchronously without reloading the page) and puts all the response text into `document.getElementById(b).innerHTML`. Finally it appears to call the `LoadSamples()` callback, when the response is received.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
The OP provided the solution in a comment: > > I've found the solution. I shouldn't have used the open source Xorg > driver instead of the proprietary Nvidia driver that seems to work > correctly. > > > – [user278680](https://askubuntu.com/users/278680/user278680) [May 11 at 16:42](https://askubuntu.com/questions/461872/ubuntu-14-04-freezes-after-wake-up#comment612900_461872)
I had the same problem. I've installed the latest nvidia drivers from [here](http://www.binarytides.com/install-nvidia-drivers-ubuntu-14-04/), and now everything works fine.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
The OP provided the solution in a comment: > > I've found the solution. I shouldn't have used the open source Xorg > driver instead of the proprietary Nvidia driver that seems to work > correctly. > > > – [user278680](https://askubuntu.com/users/278680/user278680) [May 11 at 16:42](https://askubuntu.com/questions/461872/ubuntu-14-04-freezes-after-wake-up#comment612900_461872)
I had a similar problem on Ubuntu Gnome 15.10. This is what worked for me: ``` sudo gedit /etc/default/grub ``` Edit the line: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash'" Replace it with: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash acpi\_backlight=vendor acpi\_osi='!Windows 2013' acpi\_osi='!Windows 2012'" ``` sudo update-grub ``` Then you have to reboot twice. I know. You have to do it twice, though. That fixed the issue for me, hopefully, this helps someone else.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I also had the same problem. Using HUD-->additional drivers, I was able to switch from the Xorg driver to the NVIDIA driver. (The number was different for mine than the 331.38 but this makes sense, I guess). Solved my problem of the login screen being frozen after waking from suspend.
Has anyone thought the problem might be suspending with unmounted drives (partitions or USB drives) showing. I had this problem recently, and no other changes than having unmounted drives @ suspend caused the problem. When any detected drives/partitions were mounted, the suspend feature worked flawlessly. This is probably a duplicate but I'm not searching for it. Thanks.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I'm running Ubuntu 14.10 on GA-H81M-D3H motherboard without any separate GPU, and it's frozen after suspending randomly. All that remains is the log-in screen that you can neither move your mouse nor enter the tty mode. I figured out that the problem happened every time I triggered the audio on the system. ~~Then I went to the bios setup -> peripherals -> audio controller, and changed its settings from "auto" to "enabled". It's now working!~~
Has anyone thought the problem might be suspending with unmounted drives (partitions or USB drives) showing. I had this problem recently, and no other changes than having unmounted drives @ suspend caused the problem. When any detected drives/partitions were mounted, the suspend feature worked flawlessly. This is probably a duplicate but I'm not searching for it. Thanks.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I'm running Ubuntu 14.10 on GA-H81M-D3H motherboard without any separate GPU, and it's frozen after suspending randomly. All that remains is the log-in screen that you can neither move your mouse nor enter the tty mode. I figured out that the problem happened every time I triggered the audio on the system. ~~Then I went to the bios setup -> peripherals -> audio controller, and changed its settings from "auto" to "enabled". It's now working!~~
I've had a similar problem, after wake up sometime i could move the mouse but the GUI was freezed and only when i pressed CTRL+ALT+F1 i could use the terminal. Other times instead it freezed totally. After long research ( changing bios settings, grub settings, graphic drivers , DMs etc) i tried both lxde and gnome with metacity and both didn't had problems with suspend. So i have to think that compiz is bugged with suspend mode. Try to use another desktop manager or change compiz with metacity if you can.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
The OP provided the solution in a comment: > > I've found the solution. I shouldn't have used the open source Xorg > driver instead of the proprietary Nvidia driver that seems to work > correctly. > > > – [user278680](https://askubuntu.com/users/278680/user278680) [May 11 at 16:42](https://askubuntu.com/questions/461872/ubuntu-14-04-freezes-after-wake-up#comment612900_461872)
I'm running Ubuntu 14.10 on GA-H81M-D3H motherboard without any separate GPU, and it's frozen after suspending randomly. All that remains is the log-in screen that you can neither move your mouse nor enter the tty mode. I figured out that the problem happened every time I triggered the audio on the system. ~~Then I went to the bios setup -> peripherals -> audio controller, and changed its settings from "auto" to "enabled". It's now working!~~
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
The OP provided the solution in a comment: > > I've found the solution. I shouldn't have used the open source Xorg > driver instead of the proprietary Nvidia driver that seems to work > correctly. > > > – [user278680](https://askubuntu.com/users/278680/user278680) [May 11 at 16:42](https://askubuntu.com/questions/461872/ubuntu-14-04-freezes-after-wake-up#comment612900_461872)
I've had a similar problem, after wake up sometime i could move the mouse but the GUI was freezed and only when i pressed CTRL+ALT+F1 i could use the terminal. Other times instead it freezed totally. After long research ( changing bios settings, grub settings, graphic drivers , DMs etc) i tried both lxde and gnome with metacity and both didn't had problems with suspend. So i have to think that compiz is bugged with suspend mode. Try to use another desktop manager or change compiz with metacity if you can.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I'm running Ubuntu 14.10 on GA-H81M-D3H motherboard without any separate GPU, and it's frozen after suspending randomly. All that remains is the log-in screen that you can neither move your mouse nor enter the tty mode. I figured out that the problem happened every time I triggered the audio on the system. ~~Then I went to the bios setup -> peripherals -> audio controller, and changed its settings from "auto" to "enabled". It's now working!~~
found another thread where a workaround is "sudo pm-suspend". Seems to work well for me. I'm using Intel Ivy Bridge graphics.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I also had the same problem. Using HUD-->additional drivers, I was able to switch from the Xorg driver to the NVIDIA driver. (The number was different for mine than the 331.38 but this makes sense, I guess). Solved my problem of the login screen being frozen after waking from suspend.
I had a similar problem on Ubuntu Gnome 15.10. This is what worked for me: ``` sudo gedit /etc/default/grub ``` Edit the line: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash'" Replace it with: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash acpi\_backlight=vendor acpi\_osi='!Windows 2013' acpi\_osi='!Windows 2012'" ``` sudo update-grub ``` Then you have to reboot twice. I know. You have to do it twice, though. That fixed the issue for me, hopefully, this helps someone else.
461,872
After wake up the login screen appears, but I cannot type the password to log in. Furthermore, the buttons on the system panel (e. g. to shut down) are disabled, so clicking does not take effect. I'm using Samsung RV509, 64 bit.
2014/05/06
[ "https://askubuntu.com/questions/461872", "https://askubuntu.com", "https://askubuntu.com/users/278680/" ]
I'm running Ubuntu 14.10 on GA-H81M-D3H motherboard without any separate GPU, and it's frozen after suspending randomly. All that remains is the log-in screen that you can neither move your mouse nor enter the tty mode. I figured out that the problem happened every time I triggered the audio on the system. ~~Then I went to the bios setup -> peripherals -> audio controller, and changed its settings from "auto" to "enabled". It's now working!~~
I had a similar problem on Ubuntu Gnome 15.10. This is what worked for me: ``` sudo gedit /etc/default/grub ``` Edit the line: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash'" Replace it with: GRUB\_CMDLINE\_LINUX\_DEFAULT="quiet splash acpi\_backlight=vendor acpi\_osi='!Windows 2013' acpi\_osi='!Windows 2012'" ``` sudo update-grub ``` Then you have to reboot twice. I know. You have to do it twice, though. That fixed the issue for me, hopefully, this helps someone else.
104,074
I need lightest simplest windows tool like combination of notepad and calender in a fashion of sticky notes , and want to keep always open but should have minimize button.
2010/02/03
[ "https://superuser.com/questions/104074", "https://superuser.com", "https://superuser.com/users/15114/" ]
Figuring out which packages to install to satisfy dependencies is not an exact science. But there are some tips that might help you: * When you're working with satisfying dependencies to compile something, you nearly always want the package that ends in `-dev`. This is short for development. For example, the `openssl` package contains command line tools and libraries for working with encryption. `libssl-dev` contains header files and libraries for openssl development. * To search for a package by keyword using apt, use `apt-cache search`. For example, I didn't actually know that libssl-dev was what the name of the openssl dev package was. I found that using this command: `apt-cache search openssl | grep dev` and then going with the one that didn't seem to be related to another language/library. * You can see what packages you have installed using `dpkg -l`, but, in general, just find the package you want and tell apt to install it, if you already have it then apt will tell you. Another good tip is if you want to know what package owns a file, use `dpkg -S /path/to/thefile` * If you end up needing to build a package from source, there's no easy way to resolve the dependency tree. `./configure` should tell you, or the README file. Often they will even name the exact package required. * For figuring out what to link, usually that's related to the name of the package or the most general name for what you want. For our libssl example, you would just pass `-lssl` to gcc. If you don't know what the options for `-l` are, take a look in /lib/ (just remove the "lib" from the front and the ".so..." from the back to get the 'middle' which is passed to gcc).
Nobody mentioned ``` aptitude build-dep ``` The man-page entry is pretty comprehensive.