qid int64 1 74.6M | question stringlengths 45 24.2k | date stringlengths 10 10 | metadata stringlengths 101 178 | response_j stringlengths 32 23.2k | response_k stringlengths 21 13.2k |
|---|---|---|---|---|---|
2,057,227 | In order to comply with [HIPAA](http://en.wikipedia.org/wiki/Health_Insurance_Portability_and_Accountability_Act) regulations, we need to send email from an external site (outside the firewall) to an internal Exchange server (inside the firewall). Our Exchange admins tell us we need to use TLS encryption to send mail from the web server to the email server.
I've never used TLS before and I'm not very familiar with it. Searching on Google as brought up numerous paid-for-use libraries. Is there anything native to .NET that will accomplish this? If so, how do I configure it? If not, is there something free or open source?
Current Configuration:
* ASP.NET C# Web Application
* 2.0 Framework
* Using System.Net.Mail to send email and attachments via SMTP
* IIS 6.0 | 2010/01/13 | ['https://Stackoverflow.com/questions/2057227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249861/'] | TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL. | I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.
```
SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);
```
I had to use the Port 587, which is of course the default port over TSL and the did the authentication. |
5,889,596 | I am hosting 3 WCF services inside windows services.Each WCF service contains Multiple endpoints. Right now, i am host all my endpoints thru TCP binding on different ports.
Is there any way to host all these end points from different wcf services on same port? | 2011/05/04 | ['https://Stackoverflow.com/questions/5889596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736743/'] | Sure is! You can use the Net.TCP Port Sharing service.
[Net.TCP Port Sharing](http://msdn.microsoft.com/en-us/library/ms734772.aspx) on MSDN | As far as I know you not only have to enable port sharing on the configuration (or via code), you also have to manually start the Windows Port Sharing service.
That's the reason why I (having similar problem) didn't want to use port sharing, to make it easier for deployment rather than having to mess with other things the user may or may not know. |
5,889,596 | I am hosting 3 WCF services inside windows services.Each WCF service contains Multiple endpoints. Right now, i am host all my endpoints thru TCP binding on different ports.
Is there any way to host all these end points from different wcf services on same port? | 2011/05/04 | ['https://Stackoverflow.com/questions/5889596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736743/'] | I just looked into that, out of curiosity. The behavior I discovered seems so strange that I almost don't want to put it here. But it worked in my case, so maybe it's doing the same for you:
I am getting the *AddressAlreadyInUseException* when I'm trying to host 2 services (i.e., 2 separate ServiceHost instances) on the same net.tcp port with `portSharingEnabled="True"` set on the netTcpBinding for both. That happens with or without the Net.Tcp Port Sharing Service running. The exception is thrown even if I only start one of the services (and I verified via `netstat` that there was no other listener on that same port on the machine, plus, I ran the app with elevated privileges).
Now, the funny thing is, the *AddressAlreadyInUseException* is not thrown when I set PortSharingEnabled = False, and yet both services are fully working!! Once again, with or without the Port Sharing Service running. I could even successfully connect to those services from a different machine.
An important note to make, however, is that the above only applies if the services are hosted within the SAME PROCESS! It does blow up if I try to start another instance of the app that's listening on the same port, but a different base address. But I'm assuming you're hosting those 3 WCF services inside the same Windows Service?
So, even though it doesn't seem right, my answer would be to **disable** `PortSharingEnabled` and see if it works with different BaseAddresses on the same port (provided they're all inside the same process). | As far as I know you not only have to enable port sharing on the configuration (or via code), you also have to manually start the Windows Port Sharing service.
That's the reason why I (having similar problem) didn't want to use port sharing, to make it easier for deployment rather than having to mess with other things the user may or may not know. |
31,235,227 | I have a long vector and I need to divide it into segments according to a threshold. A segment is consecutive values over the threshold. When values drop below the threshold, the segment ends and the next segment begins where the values once again cross above the threshold. I need to record the start and end indices of each segment.
Below is an inefficient implementation. What's the fastest and most appropriate way to write this? This is pretty ugly, I have to assume that there's a cleaner implementation.
```
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
```
**EDIT: Runtime of all solutions**
Thanks for all the replies, this has been helpful and very instructive. A small test of all five solutions is below (the four provided plus the original example). As you can see, all four are a huge improvement over the original solution, but Khashaa's solution is by far the fastest.
```
set.seed(1)
test.vec <- rnorm(1e6, 8, 10);threshold <- 0
originalFunction <- function(x, threshold){
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
segments
}
SimonG <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
Rcpp::cppFunction('DataFrame Khashaa(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
bgoldst <- function(x, threshold){
with(rle(x>threshold),
t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,])
}
ClausWilke <- function(x, threshold){
suppressMessages(require(dplyr, quietly = TRUE))
in.segment <- (x > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
data.frame(start, end)
}
system.time({ originalFunction(test.vec, threshold); })
## user system elapsed
## 66.539 1.232 67.770
system.time({ SimonG(test.vec, threshold); })
## user system elapsed
## 0.028 0.008 0.036
system.time({ Khashaa(test.vec, threshold); })
## user system elapsed
## 0.008 0.000 0.008
system.time({ bgoldst(test.vec, threshold); })
## user system elapsed
## 0.065 0.000 0.065
system.time({ ClausWilke(test.vec, threshold); })
## user system elapsed
## 0.274 0.012 0.285
``` | 2015/07/05 | ['https://Stackoverflow.com/questions/31235227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2048407/'] | Here's another option, mostly using `which`. The start and end points are determined by finding the non-consecutive elements of the `hit` sequence.
```
test.vec <- rnorm(100, 8, 10)
threshold <- 0
findSegments <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
findSegments(test.vec, threshold=0)
```
This gives something like:
```
> findSegments(test.vec, threshold=0)
starts ends
[1,] 1 3
[2,] 5 7
[3,] 9 11
[4,] 13 28
[5,] 30 30
[6,] 32 32
[7,] 34 36
[8,] 38 39
[9,] 41 41
[10,] 43 43
[11,] 46 51
[12,] 54 54
[13,] 56 61
[14,] 63 67
[15,] 69 72
[16,] 76 77
[17,] 80 81
[18,] 83 84
[19,] 86 88
[20,] 90 92
[21,] 94 95
[22,] 97 97
[23,] 100 100
```
Compare that to the original sequence:
```
> round(test.vec,1)
[1] 20.7 15.7 4.3 -15.1 24.6 9.4 23.2 -4.5 16.9 20.9 13.2 -1.2
[13] 22.6 7.7 6.0 6.6 4.1 21.3 5.3 16.7 11.4 16.7 19.6 16.7
[25] 11.6 7.3 3.7 8.4 -4.5 11.7 -7.1 8.4 -18.5 12.8 22.5 11.0
[37] -3.3 11.1 6.9 -7.9 22.9 -3.7 3.5 -7.1 -5.9 3.5 13.2 20.0
[49] 13.2 23.4 15.9 -5.0 -6.3 10.0 -6.2 4.7 2.1 26.4 5.9 27.3
[61] 14.3 -12.4 28.4 30.9 18.2 11.4 5.7 -4.5 6.2 12.0 10.9 11.1
[73] -2.0 -9.0 -1.4 15.4 19.1 -1.6 -5.4 5.4 7.8 -5.6 15.2 13.8
[85] -18.8 7.1 17.1 9.3 -3.9 22.6 1.7 28.9 -21.3 21.2 8.2 -15.4
[97] 3.2 -10.2 -6.2 14.1
``` | ```
with(rle(test.vec>threshold),t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,]);
## [,1] [,2]
## [1,] 1 8
## [2,] 10 13
## [3,] 16 17
## [4,] 20 26
## [5,] 28 28
## [6,] 30 34
## [7,] 36 38
## [8,] 41 46
## [9,] 48 49
## [10,] 51 53
## [11,] 55 81
## [12,] 84 90
## [13,] 92 100
```
---
Explanation
===========
```
test.vec>threshold
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
```
Compute which elements in the input vector are above the threshold using vectorized comparison.
---
```
rle(...)
## Run Length Encoding
## lengths: int [1:25] 8 1 4 2 2 2 7 1 1 1 ...
## values : logi [1:25] TRUE FALSE TRUE FALSE TRUE FALSE ...
```
Compute the run-length encoding of the logical vector. This returns a list classed as `'rle'` which contains two named components: `lengths`, containing the lengths of each run-length, and `values`, containing the value that ran that length, which in this case will be `TRUE` or `FALSE`, with the former representing a segment of interest, and the latter representing a non-segment run length.
---
```
with(...,...)
```
The first argument is the run-length encoding as described above. This will evaluate the second argument in a virtual environment consisting of the `'rle'`-classed list, thus making the `lengths` and `values` components accessible as lexical variables.
Below I dive into the contents of the second argument.
---
```
cumsum(lengths)
## [1] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
Compute the cumulative sum of the `lengths`. This will form the basis for computing both the start indexes and end indexes of each run-length. Critical point: Each element of the cumsum represents the end index of that run-length.
---
```
rep(...,2L)
## [1] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
Duplicate the cumulative sum. The first repetition will serve as the basis for the start indexes, the second the end. I will henceforth refer to these repetitions as the "start-index repetition" and the "end-index repetition".
---
```
c(0L,...[-length(lengths)])
## [1] 0 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
This removes the last element at the end of the start-index repetition, and prepends a zero to the beginning of it. This effectively lags the start-index repetition by one element. This is necessary because we need to compute each start index by adding one to the *previous* run-length's end index, taking zero as the end index of the non-existent run-length prior to the first.
---
```
matrix(...,2L,byrow=T)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
## [1,] 0 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91
## [2,] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
This builds a two-row matrix out of the previous result. The lagged start-index repetition is the top row, the end-index repetition is the bottom row.
---
```
...+1:0
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
## [1,] 1 9 10 14 16 18 20 27 28 29 30 35 36 39 41 47 48 50 51 54 55 82 84 91 92
## [2,] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
R cycles this two-element addend across rows first, then across columns, thus this adds one to the top row. This completes the computation of the start indexes.
---
```
t(...)
## [,1] [,2]
## [1,] 1 8
## [2,] 9 9
## [3,] 10 13
## [4,] 14 15
## [5,] 16 17
## [6,] 18 19
## [7,] 20 26
## [8,] 27 27
## [9,] 28 28
## [10,] 29 29
## [11,] 30 34
## [12,] 35 35
## [13,] 36 38
## [14,] 39 40
## [15,] 41 46
## [16,] 47 47
## [17,] 48 49
## [18,] 50 50
## [19,] 51 53
## [20,] 54 54
## [21,] 55 81
## [22,] 82 83
## [23,] 84 90
## [24,] 91 91
## [25,] 92 100
```
Transpose to a two-column matrix. This is not entirely necessary, if you're ok with getting the result as a two-row matrix.
---
```
...[values,]
## [,1] [,2]
## [1,] 1 8
## [2,] 10 13
## [3,] 16 17
## [4,] 20 26
## [5,] 28 28
## [6,] 30 34
## [7,] 36 38
## [8,] 41 46
## [9,] 48 49
## [10,] 51 53
## [11,] 55 81
## [12,] 84 90
## [13,] 92 100
```
Subset just the segments of interest. Since `values` is a logical vector representing which run-lengths surpassed the threshold, we can use it directly as a row index vector.
---
Performance
===========
I guess I'm screwing myself here, but SimonG's solution performs about twice as well as mine:
```
bgoldst <- function() with(rle(test.vec>threshold),t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,]);
simong <- function() findSegments(test.vec,threshold);
set.seed(1); test.vec <- rnorm(1e7,8,10); threshold <- 0;
identical(bgoldst(),unname(simong()));
## [1] TRUE
system.time({ bgoldst(); })
## user system elapsed
## 1.344 0.204 1.551
system.time({ simong(); })
## user system elapsed
## 0.656 0.109 0.762
```
+1 from me... |
31,235,227 | I have a long vector and I need to divide it into segments according to a threshold. A segment is consecutive values over the threshold. When values drop below the threshold, the segment ends and the next segment begins where the values once again cross above the threshold. I need to record the start and end indices of each segment.
Below is an inefficient implementation. What's the fastest and most appropriate way to write this? This is pretty ugly, I have to assume that there's a cleaner implementation.
```
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
```
**EDIT: Runtime of all solutions**
Thanks for all the replies, this has been helpful and very instructive. A small test of all five solutions is below (the four provided plus the original example). As you can see, all four are a huge improvement over the original solution, but Khashaa's solution is by far the fastest.
```
set.seed(1)
test.vec <- rnorm(1e6, 8, 10);threshold <- 0
originalFunction <- function(x, threshold){
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
segments
}
SimonG <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
Rcpp::cppFunction('DataFrame Khashaa(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
bgoldst <- function(x, threshold){
with(rle(x>threshold),
t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,])
}
ClausWilke <- function(x, threshold){
suppressMessages(require(dplyr, quietly = TRUE))
in.segment <- (x > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
data.frame(start, end)
}
system.time({ originalFunction(test.vec, threshold); })
## user system elapsed
## 66.539 1.232 67.770
system.time({ SimonG(test.vec, threshold); })
## user system elapsed
## 0.028 0.008 0.036
system.time({ Khashaa(test.vec, threshold); })
## user system elapsed
## 0.008 0.000 0.008
system.time({ bgoldst(test.vec, threshold); })
## user system elapsed
## 0.065 0.000 0.065
system.time({ ClausWilke(test.vec, threshold); })
## user system elapsed
## 0.274 0.012 0.285
``` | 2015/07/05 | ['https://Stackoverflow.com/questions/31235227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2048407/'] | I like `for loops` for translation to `Rcpp` is straightforward.
```
Rcpp::cppFunction('DataFrame findSegment(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
set.seed(1); test.vec <- rnorm(1e7,8,10); threshold <- 0;
system.time(findSegment(test.vec, threshold))
# user system elapsed
# 0.045 0.000 0.045
# @SimonG's solution
system.time(findSegments(test.vec, threshold))
# user system elapsed
# 0.533 0.012 0.548
``` | ```
with(rle(test.vec>threshold),t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,]);
## [,1] [,2]
## [1,] 1 8
## [2,] 10 13
## [3,] 16 17
## [4,] 20 26
## [5,] 28 28
## [6,] 30 34
## [7,] 36 38
## [8,] 41 46
## [9,] 48 49
## [10,] 51 53
## [11,] 55 81
## [12,] 84 90
## [13,] 92 100
```
---
Explanation
===========
```
test.vec>threshold
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
```
Compute which elements in the input vector are above the threshold using vectorized comparison.
---
```
rle(...)
## Run Length Encoding
## lengths: int [1:25] 8 1 4 2 2 2 7 1 1 1 ...
## values : logi [1:25] TRUE FALSE TRUE FALSE TRUE FALSE ...
```
Compute the run-length encoding of the logical vector. This returns a list classed as `'rle'` which contains two named components: `lengths`, containing the lengths of each run-length, and `values`, containing the value that ran that length, which in this case will be `TRUE` or `FALSE`, with the former representing a segment of interest, and the latter representing a non-segment run length.
---
```
with(...,...)
```
The first argument is the run-length encoding as described above. This will evaluate the second argument in a virtual environment consisting of the `'rle'`-classed list, thus making the `lengths` and `values` components accessible as lexical variables.
Below I dive into the contents of the second argument.
---
```
cumsum(lengths)
## [1] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
Compute the cumulative sum of the `lengths`. This will form the basis for computing both the start indexes and end indexes of each run-length. Critical point: Each element of the cumsum represents the end index of that run-length.
---
```
rep(...,2L)
## [1] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
Duplicate the cumulative sum. The first repetition will serve as the basis for the start indexes, the second the end. I will henceforth refer to these repetitions as the "start-index repetition" and the "end-index repetition".
---
```
c(0L,...[-length(lengths)])
## [1] 0 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
This removes the last element at the end of the start-index repetition, and prepends a zero to the beginning of it. This effectively lags the start-index repetition by one element. This is necessary because we need to compute each start index by adding one to the *previous* run-length's end index, taking zero as the end index of the non-existent run-length prior to the first.
---
```
matrix(...,2L,byrow=T)
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
## [1,] 0 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91
## [2,] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
This builds a two-row matrix out of the previous result. The lagged start-index repetition is the top row, the end-index repetition is the bottom row.
---
```
...+1:0
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
## [1,] 1 9 10 14 16 18 20 27 28 29 30 35 36 39 41 47 48 50 51 54 55 82 84 91 92
## [2,] 8 9 13 15 17 19 26 27 28 29 34 35 38 40 46 47 49 50 53 54 81 83 90 91 100
```
R cycles this two-element addend across rows first, then across columns, thus this adds one to the top row. This completes the computation of the start indexes.
---
```
t(...)
## [,1] [,2]
## [1,] 1 8
## [2,] 9 9
## [3,] 10 13
## [4,] 14 15
## [5,] 16 17
## [6,] 18 19
## [7,] 20 26
## [8,] 27 27
## [9,] 28 28
## [10,] 29 29
## [11,] 30 34
## [12,] 35 35
## [13,] 36 38
## [14,] 39 40
## [15,] 41 46
## [16,] 47 47
## [17,] 48 49
## [18,] 50 50
## [19,] 51 53
## [20,] 54 54
## [21,] 55 81
## [22,] 82 83
## [23,] 84 90
## [24,] 91 91
## [25,] 92 100
```
Transpose to a two-column matrix. This is not entirely necessary, if you're ok with getting the result as a two-row matrix.
---
```
...[values,]
## [,1] [,2]
## [1,] 1 8
## [2,] 10 13
## [3,] 16 17
## [4,] 20 26
## [5,] 28 28
## [6,] 30 34
## [7,] 36 38
## [8,] 41 46
## [9,] 48 49
## [10,] 51 53
## [11,] 55 81
## [12,] 84 90
## [13,] 92 100
```
Subset just the segments of interest. Since `values` is a logical vector representing which run-lengths surpassed the threshold, we can use it directly as a row index vector.
---
Performance
===========
I guess I'm screwing myself here, but SimonG's solution performs about twice as well as mine:
```
bgoldst <- function() with(rle(test.vec>threshold),t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,]);
simong <- function() findSegments(test.vec,threshold);
set.seed(1); test.vec <- rnorm(1e7,8,10); threshold <- 0;
identical(bgoldst(),unname(simong()));
## [1] TRUE
system.time({ bgoldst(); })
## user system elapsed
## 1.344 0.204 1.551
system.time({ simong(); })
## user system elapsed
## 0.656 0.109 0.762
```
+1 from me... |
31,235,227 | I have a long vector and I need to divide it into segments according to a threshold. A segment is consecutive values over the threshold. When values drop below the threshold, the segment ends and the next segment begins where the values once again cross above the threshold. I need to record the start and end indices of each segment.
Below is an inefficient implementation. What's the fastest and most appropriate way to write this? This is pretty ugly, I have to assume that there's a cleaner implementation.
```
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
```
**EDIT: Runtime of all solutions**
Thanks for all the replies, this has been helpful and very instructive. A small test of all five solutions is below (the four provided plus the original example). As you can see, all four are a huge improvement over the original solution, but Khashaa's solution is by far the fastest.
```
set.seed(1)
test.vec <- rnorm(1e6, 8, 10);threshold <- 0
originalFunction <- function(x, threshold){
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
segments
}
SimonG <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
Rcpp::cppFunction('DataFrame Khashaa(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
bgoldst <- function(x, threshold){
with(rle(x>threshold),
t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,])
}
ClausWilke <- function(x, threshold){
suppressMessages(require(dplyr, quietly = TRUE))
in.segment <- (x > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
data.frame(start, end)
}
system.time({ originalFunction(test.vec, threshold); })
## user system elapsed
## 66.539 1.232 67.770
system.time({ SimonG(test.vec, threshold); })
## user system elapsed
## 0.028 0.008 0.036
system.time({ Khashaa(test.vec, threshold); })
## user system elapsed
## 0.008 0.000 0.008
system.time({ bgoldst(test.vec, threshold); })
## user system elapsed
## 0.065 0.000 0.065
system.time({ ClausWilke(test.vec, threshold); })
## user system elapsed
## 0.274 0.012 0.285
``` | 2015/07/05 | ['https://Stackoverflow.com/questions/31235227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2048407/'] | Here's another option, mostly using `which`. The start and end points are determined by finding the non-consecutive elements of the `hit` sequence.
```
test.vec <- rnorm(100, 8, 10)
threshold <- 0
findSegments <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
findSegments(test.vec, threshold=0)
```
This gives something like:
```
> findSegments(test.vec, threshold=0)
starts ends
[1,] 1 3
[2,] 5 7
[3,] 9 11
[4,] 13 28
[5,] 30 30
[6,] 32 32
[7,] 34 36
[8,] 38 39
[9,] 41 41
[10,] 43 43
[11,] 46 51
[12,] 54 54
[13,] 56 61
[14,] 63 67
[15,] 69 72
[16,] 76 77
[17,] 80 81
[18,] 83 84
[19,] 86 88
[20,] 90 92
[21,] 94 95
[22,] 97 97
[23,] 100 100
```
Compare that to the original sequence:
```
> round(test.vec,1)
[1] 20.7 15.7 4.3 -15.1 24.6 9.4 23.2 -4.5 16.9 20.9 13.2 -1.2
[13] 22.6 7.7 6.0 6.6 4.1 21.3 5.3 16.7 11.4 16.7 19.6 16.7
[25] 11.6 7.3 3.7 8.4 -4.5 11.7 -7.1 8.4 -18.5 12.8 22.5 11.0
[37] -3.3 11.1 6.9 -7.9 22.9 -3.7 3.5 -7.1 -5.9 3.5 13.2 20.0
[49] 13.2 23.4 15.9 -5.0 -6.3 10.0 -6.2 4.7 2.1 26.4 5.9 27.3
[61] 14.3 -12.4 28.4 30.9 18.2 11.4 5.7 -4.5 6.2 12.0 10.9 11.1
[73] -2.0 -9.0 -1.4 15.4 19.1 -1.6 -5.4 5.4 7.8 -5.6 15.2 13.8
[85] -18.8 7.1 17.1 9.3 -3.9 22.6 1.7 28.9 -21.3 21.2 8.2 -15.4
[97] 3.2 -10.2 -6.2 14.1
``` | Here is another solution that I think is simpler. Note that you have to use `set.seed(10)`, not `set.seed <- 10`, to set the seed of the random number generator.
```
require(dplyr) # for lead() and lag()
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
in.segment <- (test.vec > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
segments <- data.frame(start, end)
head(segments)
## start end
## 1 1 2
## 2 4 6
## 3 8 8
## 4 10 16
## 5 18 21
## 6 23 23
```
In general, in R, if you find yourself writing complicated loops and if statements you're probably doing it wrong. Most problems can be solved in a vectorized form. |
31,235,227 | I have a long vector and I need to divide it into segments according to a threshold. A segment is consecutive values over the threshold. When values drop below the threshold, the segment ends and the next segment begins where the values once again cross above the threshold. I need to record the start and end indices of each segment.
Below is an inefficient implementation. What's the fastest and most appropriate way to write this? This is pretty ugly, I have to assume that there's a cleaner implementation.
```
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
```
**EDIT: Runtime of all solutions**
Thanks for all the replies, this has been helpful and very instructive. A small test of all five solutions is below (the four provided plus the original example). As you can see, all four are a huge improvement over the original solution, but Khashaa's solution is by far the fastest.
```
set.seed(1)
test.vec <- rnorm(1e6, 8, 10);threshold <- 0
originalFunction <- function(x, threshold){
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
segments
}
SimonG <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
Rcpp::cppFunction('DataFrame Khashaa(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
bgoldst <- function(x, threshold){
with(rle(x>threshold),
t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,])
}
ClausWilke <- function(x, threshold){
suppressMessages(require(dplyr, quietly = TRUE))
in.segment <- (x > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
data.frame(start, end)
}
system.time({ originalFunction(test.vec, threshold); })
## user system elapsed
## 66.539 1.232 67.770
system.time({ SimonG(test.vec, threshold); })
## user system elapsed
## 0.028 0.008 0.036
system.time({ Khashaa(test.vec, threshold); })
## user system elapsed
## 0.008 0.000 0.008
system.time({ bgoldst(test.vec, threshold); })
## user system elapsed
## 0.065 0.000 0.065
system.time({ ClausWilke(test.vec, threshold); })
## user system elapsed
## 0.274 0.012 0.285
``` | 2015/07/05 | ['https://Stackoverflow.com/questions/31235227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2048407/'] | I like `for loops` for translation to `Rcpp` is straightforward.
```
Rcpp::cppFunction('DataFrame findSegment(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
set.seed(1); test.vec <- rnorm(1e7,8,10); threshold <- 0;
system.time(findSegment(test.vec, threshold))
# user system elapsed
# 0.045 0.000 0.045
# @SimonG's solution
system.time(findSegments(test.vec, threshold))
# user system elapsed
# 0.533 0.012 0.548
``` | Here's another option, mostly using `which`. The start and end points are determined by finding the non-consecutive elements of the `hit` sequence.
```
test.vec <- rnorm(100, 8, 10)
threshold <- 0
findSegments <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
findSegments(test.vec, threshold=0)
```
This gives something like:
```
> findSegments(test.vec, threshold=0)
starts ends
[1,] 1 3
[2,] 5 7
[3,] 9 11
[4,] 13 28
[5,] 30 30
[6,] 32 32
[7,] 34 36
[8,] 38 39
[9,] 41 41
[10,] 43 43
[11,] 46 51
[12,] 54 54
[13,] 56 61
[14,] 63 67
[15,] 69 72
[16,] 76 77
[17,] 80 81
[18,] 83 84
[19,] 86 88
[20,] 90 92
[21,] 94 95
[22,] 97 97
[23,] 100 100
```
Compare that to the original sequence:
```
> round(test.vec,1)
[1] 20.7 15.7 4.3 -15.1 24.6 9.4 23.2 -4.5 16.9 20.9 13.2 -1.2
[13] 22.6 7.7 6.0 6.6 4.1 21.3 5.3 16.7 11.4 16.7 19.6 16.7
[25] 11.6 7.3 3.7 8.4 -4.5 11.7 -7.1 8.4 -18.5 12.8 22.5 11.0
[37] -3.3 11.1 6.9 -7.9 22.9 -3.7 3.5 -7.1 -5.9 3.5 13.2 20.0
[49] 13.2 23.4 15.9 -5.0 -6.3 10.0 -6.2 4.7 2.1 26.4 5.9 27.3
[61] 14.3 -12.4 28.4 30.9 18.2 11.4 5.7 -4.5 6.2 12.0 10.9 11.1
[73] -2.0 -9.0 -1.4 15.4 19.1 -1.6 -5.4 5.4 7.8 -5.6 15.2 13.8
[85] -18.8 7.1 17.1 9.3 -3.9 22.6 1.7 28.9 -21.3 21.2 8.2 -15.4
[97] 3.2 -10.2 -6.2 14.1
``` |
31,235,227 | I have a long vector and I need to divide it into segments according to a threshold. A segment is consecutive values over the threshold. When values drop below the threshold, the segment ends and the next segment begins where the values once again cross above the threshold. I need to record the start and end indices of each segment.
Below is an inefficient implementation. What's the fastest and most appropriate way to write this? This is pretty ugly, I have to assume that there's a cleaner implementation.
```
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
```
**EDIT: Runtime of all solutions**
Thanks for all the replies, this has been helpful and very instructive. A small test of all five solutions is below (the four provided plus the original example). As you can see, all four are a huge improvement over the original solution, but Khashaa's solution is by far the fastest.
```
set.seed(1)
test.vec <- rnorm(1e6, 8, 10);threshold <- 0
originalFunction <- function(x, threshold){
segments <- list()
in.segment <- FALSE
for(i in 1:length(test.vec)){
# If we're in a segment
if(in.segment){
if(test.vec[i] > threshold){
next
}else{
end.ind <- i - 1
in.segment <- FALSE
segments[[length(segments) + 1]] <- c(start.ind, end.ind)
}
}
# if not in segment
else{
if(test.vec[i] > threshold){
start.ind <- i
in.segment <- TRUE
}
}
}
segments
}
SimonG <- function(x, threshold){
hit <- which(x > threshold)
n <- length(hit)
ind <- which(hit[-1] - hit[-n] > 1)
starts <- c(hit[1], hit[ ind+1 ])
ends <- c(hit[ ind ], hit[n])
cbind(starts,ends)
}
Rcpp::cppFunction('DataFrame Khashaa(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
bgoldst <- function(x, threshold){
with(rle(x>threshold),
t(matrix(c(0L,rep(cumsum(lengths),2L)[-length(lengths)]),2L,byrow=T)+1:0)[values,])
}
ClausWilke <- function(x, threshold){
suppressMessages(require(dplyr, quietly = TRUE))
in.segment <- (x > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
data.frame(start, end)
}
system.time({ originalFunction(test.vec, threshold); })
## user system elapsed
## 66.539 1.232 67.770
system.time({ SimonG(test.vec, threshold); })
## user system elapsed
## 0.028 0.008 0.036
system.time({ Khashaa(test.vec, threshold); })
## user system elapsed
## 0.008 0.000 0.008
system.time({ bgoldst(test.vec, threshold); })
## user system elapsed
## 0.065 0.000 0.065
system.time({ ClausWilke(test.vec, threshold); })
## user system elapsed
## 0.274 0.012 0.285
``` | 2015/07/05 | ['https://Stackoverflow.com/questions/31235227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2048407/'] | I like `for loops` for translation to `Rcpp` is straightforward.
```
Rcpp::cppFunction('DataFrame findSegment(NumericVector x, double threshold) {
x.push_back(-1);
int n = x.size(), startind, endind;
std::vector<int> startinds, endinds;
bool insegment = false;
for(int i=0; i<n; i++){
if(!insegment){
if(x[i] > threshold){
startind = i + 1;
insegment = true; }
}else{
if(x[i] < threshold){
endind = i;
insegment = false;
startinds.push_back(startind);
endinds.push_back(endind);
}
}
}
return DataFrame::create(_["start"]= startinds, _["end"]= endinds);
}')
set.seed(1); test.vec <- rnorm(1e7,8,10); threshold <- 0;
system.time(findSegment(test.vec, threshold))
# user system elapsed
# 0.045 0.000 0.045
# @SimonG's solution
system.time(findSegments(test.vec, threshold))
# user system elapsed
# 0.533 0.012 0.548
``` | Here is another solution that I think is simpler. Note that you have to use `set.seed(10)`, not `set.seed <- 10`, to set the seed of the random number generator.
```
require(dplyr) # for lead() and lag()
set.seed(10)
test.vec <- rnorm(100, 8, 10)
threshold <- 0
in.segment <- (test.vec > threshold)
start <- which(c(FALSE, in.segment) == TRUE & lag(c(FALSE, in.segment) == FALSE)) - 1
end <- which(c(in.segment, FALSE) == TRUE & lead(c(in.segment, FALSE) == FALSE))
segments <- data.frame(start, end)
head(segments)
## start end
## 1 1 2
## 2 4 6
## 3 8 8
## 4 10 16
## 5 18 21
## 6 23 23
```
In general, in R, if you find yourself writing complicated loops and if statements you're probably doing it wrong. Most problems can be solved in a vectorized form. |
21,790 | Can you explain why the answer to the following question is *approximately 4.5%*:
>
> An investor buys a bond that has a Macaulay duration of 3.0 and a
> yield to maturity of 4.5%. The investor plans to sell the bond after
> three years. If the yield curve has a parallel downward shift of 100
> basis points immediately after the investor buys the bond, her
> annualized horizon return is most likely to be:
>
>
> **Answer: approximately 4.5%**
>
>
> | 2015/11/17 | ['https://quant.stackexchange.com/questions/21790', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/18320/'] | Duration (of which Macaualy is one type) is only a linear **approximation** of how the bond value will change with a small change in yield. | I went on a rant below, but this is actually a trick question.
If the time to maturity of the bond is 3 years, if its current yield to maturity is 4.5%, and if you hold the bond to maturity, then the annualized horizon return will be 4.5%, **assuming all interim cash flows can be reinvested at the 4.5% yield**. If cash flows cannot be reinvested at 4.5%, then the holding period return will drift away from 4.5% somewhat.
Given that the position is held to maturity, the instantaneous 100 bp change in yield is irrelevant, since any unrealized losses/gains because of the yield shift will be subsequently offset. Consider the simpler scenario of a zero coupon bond which has no coupon payments and only a principal payment on the maturity date. If yield increases substantially, you may encounter a substantial unrealized loss initially. But at maturity, if the bond doesn't default, you'll still get back the full principal amount, and that's the only quantity relevant for computing the total return over this time period.
However, the question uses a "Macauley duration" of 3. The only case where mac duration equals time to maturity is for zero coupon bonds and when yields are continuously compounded. In other cases, this 4.5% annualized return is a further approximation.
So the approximation comes from two fronts: 1) cash flows may not be reinvested at 4.5%, and 2) the time to maturity may not be the same as the mac duration.
---
Original rant below:
This is in my mind an extremely misleading question.
First of all, Macauley duration as a concept has historical value, but virtually no value in practical applications. By contrast, modified duration describes the percentage change in price for a small change in yield. Modified duration can be computed easily given Macauley duration and yield to maturity:
$$ \text{modified duration} = \frac{\text{Macauley duration}}{1 + \text{yield} / \text{compounding frequency}}. $$
In this case, assuming compounding frequency is semiannual (as is the case for virtually all bonds issued int he US), then the modified duration is
$$ D\_\text{mod} = \frac{3.0}{1 + 4.5\% / 2} = 2.93 $$.
So if yield changes by 100 bp, the linear approximation of percentage change in bond price should be 2.93% -- not approximately 4.5% and not 3%.
As to the "approximately" part, this is because bond price is not a linear function of yield, rather a convex function. A better approximation requires "convexity":
$$ \text{percentage change in price} = -\text{mod duration}\times \Delta y + \frac{1}{2} \times \text{convexity} \times (\Delta y)^2. $$ |
21,790 | Can you explain why the answer to the following question is *approximately 4.5%*:
>
> An investor buys a bond that has a Macaulay duration of 3.0 and a
> yield to maturity of 4.5%. The investor plans to sell the bond after
> three years. If the yield curve has a parallel downward shift of 100
> basis points immediately after the investor buys the bond, her
> annualized horizon return is most likely to be:
>
>
> **Answer: approximately 4.5%**
>
>
> | 2015/11/17 | ['https://quant.stackexchange.com/questions/21790', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/18320/'] | If the bonds yield goes down by $100 \text{bps}$ and the duration is $3$, the bond price will increase by *approximately* $3\%$.
Without any subsequent movement over the next three years, the bond should yield 3.5% p.a. after the yield rate movement.
The return during the total holding period of three years would be *approximately*:
$$ 3\% \text{(yield rate shift)} + 3\cdot 3.5\% \text{(annual bond yield)} = 13.5\%. $$
Lets approximate again and divide that by three to get the annual value: $4.5\%$.
---
Please be aware that there are several assumptions and simplifications made here.
First of all, the Macaulay Duration is only a linear approximation of the bonds price sensitivity to yield price changes.
The other is that we simply assume all given interest rates to be continuously compounded values when we add, multiply and divide them to scale the returns over time. This is only a good approximation for small rates $r$, where $\ln (1+r) \approx r$. In particular, this definitely an approximation for the duration impact term because the duration formula gives us the price impact in terms of discrete returns.
We also assume that there either are no coupons at all or they can be reinvested at exactly the yield of the bond (without transaction costs or even market impact).
The third assumption whe have to make is that after the initial yield movement, the bonds yield will remain constant during the holding period. | I went on a rant below, but this is actually a trick question.
If the time to maturity of the bond is 3 years, if its current yield to maturity is 4.5%, and if you hold the bond to maturity, then the annualized horizon return will be 4.5%, **assuming all interim cash flows can be reinvested at the 4.5% yield**. If cash flows cannot be reinvested at 4.5%, then the holding period return will drift away from 4.5% somewhat.
Given that the position is held to maturity, the instantaneous 100 bp change in yield is irrelevant, since any unrealized losses/gains because of the yield shift will be subsequently offset. Consider the simpler scenario of a zero coupon bond which has no coupon payments and only a principal payment on the maturity date. If yield increases substantially, you may encounter a substantial unrealized loss initially. But at maturity, if the bond doesn't default, you'll still get back the full principal amount, and that's the only quantity relevant for computing the total return over this time period.
However, the question uses a "Macauley duration" of 3. The only case where mac duration equals time to maturity is for zero coupon bonds and when yields are continuously compounded. In other cases, this 4.5% annualized return is a further approximation.
So the approximation comes from two fronts: 1) cash flows may not be reinvested at 4.5%, and 2) the time to maturity may not be the same as the mac duration.
---
Original rant below:
This is in my mind an extremely misleading question.
First of all, Macauley duration as a concept has historical value, but virtually no value in practical applications. By contrast, modified duration describes the percentage change in price for a small change in yield. Modified duration can be computed easily given Macauley duration and yield to maturity:
$$ \text{modified duration} = \frac{\text{Macauley duration}}{1 + \text{yield} / \text{compounding frequency}}. $$
In this case, assuming compounding frequency is semiannual (as is the case for virtually all bonds issued int he US), then the modified duration is
$$ D\_\text{mod} = \frac{3.0}{1 + 4.5\% / 2} = 2.93 $$.
So if yield changes by 100 bp, the linear approximation of percentage change in bond price should be 2.93% -- not approximately 4.5% and not 3%.
As to the "approximately" part, this is because bond price is not a linear function of yield, rather a convex function. A better approximation requires "convexity":
$$ \text{percentage change in price} = -\text{mod duration}\times \Delta y + \frac{1}{2} \times \text{convexity} \times (\Delta y)^2. $$ |
36,694,963 | I want to clear my local notification in notification tray. For this to be
implemented, I am thinking to use the silent push notification. So I want
to confirm when the device receives it and which things I can do with it? | 2016/04/18 | ['https://Stackoverflow.com/questions/36694963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4706130/'] | They can be used to inform the application of new content without having the user informed. Instead of displaying a notification alert, the application will be awakened in background (iOS does not automatically launch your app if the user has force-quit it) and [application:didReceiveRemoteNotification:fetchCompletionHandler:](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application) will be called. You then have the opportunity to process any information transparently for the user :
* Download some content
* Synchronize some elements,
* Inform the user directly within the application when he opens it back
Note that your time is limited to 30s.
To configure silent notifications
>
> To support silent remote notifications, add the remote-notification value to the UIBackgroundModes array in your Info.plist file. To learn more about this array, see UIBackgroundModes.
>
>
>
```
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
```
>
> Configuring a Silent Notification
>
>
> The aps dictionary can also contain the content-available property. The content- available property with a value of 1 lets the remote notification act as a silent notification. When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing. Users aren’t told about the new or changed information that results from a silent notification, but they can find out about it the next time they open your app.
>
>
> For a silent notification, take care to ensure there is no alert, sound, or badge payload in the aps dictionary. If you don’t follow this guidance, the incorrectly-configured notification might be throttled and not delivered to the app in the background, and instead of being silent is displayed to the user
>
>
> | When you send a silent push notification and if app is suspended then the system wakes up or launches your app and puts it into the background running state before calling the method but if the app is killed by user manually then it will not wakeup.
**application:didReceiveRemoteNotification:fetchCompletionHandler:**
This method is called when you send a silent push notification and your app has up to 30 seconds of wall-clock time to perform the download or any other kind of operation and call the specified completion handler block. If the handler is not called in time, your app will be suspended.
If you want to send a silent push notification then your notification payload should be like this :
```
{
"aps" = {
"content-available" : 1,
"sound" : ""
};
// You can add custom key-value pair here...
}
``` |
18,260,784 | I have an Array of a few hundred JSON Objects...
```
var self.collection = [Object, Object, Object, Object, Object, Object…]
```
Each one looks like this...
```
0: Object
id: "25093712"
name: "John Haberstich"
```
I'm iterating through the Array searching each Array.id to see if it matches any ids in a second Array...
```
var fbContactIDs = ["1072980313", "2502342", "2509374", "2524864", "2531941"]
$.each(self.collection, function(index, k) {
if (fbContactIDs.indexOf(k.id) > -1) {
self.collection.splice(index, 1);
};
});
```
However this code only works to splice three of the Objects from the self.collection array and then it breaks and gives the following error:
```
Uncaught TypeError: Cannot read property 'id' of undefined
```
The line that is causing the error is this one...
```
if (fbContactIDs.indexOf(k.id) > -1) {
```
Could anyone tell me what I'm dong wrong here? | 2013/08/15 | ['https://Stackoverflow.com/questions/18260784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1686562/'] | Because the length of collection will change, the trick is to loop from rear to front
```
for (var index = self.collection.length - 1; index >= 0; index--) {
k = self.collection[index];
if (fbContactIDs.indexOf(k.id) > -1) {
self.collection.splice(index, 1);
};
}
``` | You should not change the length of an array while iterating over it.
What you're trying to do is **filtering** and there's a specific function for that. For example:
```
[1,2,3,4,5,6,7,8,9,10].filter(function(x){ return (x&1) == 0; })
```
will return only even numbers.
In your case the solution could then simply be:
```
self.collection = self.collection.filter(function(k){
return fbContactIDs.indexOf(k.id) > -1;
});
```
or, if others are keeping a reference to `self.collection` and you need to mutate it inplace:
```
self.collection.splice(0, self.collection.length,
self.collection.filter(function(k){
return fbContactIDs.indexOf(k.id) > -1;
}));
```
If for some reason you like to process elements one at a time instead of using `filter` and you need to do this inplace a simple approach is the read-write one:
```
var wp = 0; // Write ptr
for (var rp=0; rp<L.length; rp++) {
if (... i want to keep L[x] ...) {
L[wp++] = L[rp];
}
}
L.splice(wp);
```
removing elements from an array one at a time is an `O(n**2)` operation (because for each element you remove also all the following ones must be slided down a place), the read-write approach is instead `O(n)`. |
17,708,537 | When I try to run
```
$ rails console
```
I get the following error
```
/usr/local/lib/ruby/gems/2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/core_ext/module/aliasing.rb:32:in `alias_method': undefined method `arel_attributes_values' for class `ActiveRecord::Base' (NameError)
```
.............
Other errors follow... that are just tracebacks
My versions are as follows
```
$ gem -v
2.0.5
$ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41647) [x86_64-linux]
$ rails -v
Rails 4.0.0
$ rvm -v
rvm 1.21.11 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]
$ uname -a
Linux cdv-web01 2.6.18-274.el5 #1 SMP Fri Jul 8 17:36:59 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux
```
Do I have to install a gem that I don't know about?
UPDATE: Included is the whole traceback...
```
Warning: NLS_LANG is not set. fallback to US7ASCII.
/home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/core_ext/module/aliasing.rb:32:in `alias_method': undefined method `arel_attributes_values' for class `ActiveRecord::Base' (NameError)
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/core_ext/module/aliasing.rb:32:in `alias_method_chain'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-oracle_enhanced-adapter-1.4.2/lib/active_record/connection_adapters/oracle_enhanced_base_ext.rb:116:in `<class:Base>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-oracle_enhanced-adapter-1.4.2/lib/active_record/connection_adapters/oracle_enhanced_base_ext.rb:2:in `<module:ActiveRecord>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-oracle_enhanced-adapter-1.4.2/lib/active_record/connection_adapters/oracle_enhanced_base_ext.rb:1:in `<top (required)>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `block in require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:211:in `block in load_dependency'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:615:in `new_constants_in'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:211:in `load_dependency'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-oracle_enhanced-adapter-1.4.2/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb:38:in `<top (required)>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `block in require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:211:in `block in load_dependency'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:615:in `new_constants_in'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:211:in `load_dependency'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-oracle_enhanced-adapter-1.4.2/lib/activerecord-oracle_enhanced-adapter.rb:12:in `block in <class:OracleEnhancedRailtie>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `instance_eval'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:38:in `execute_hook'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:45:in `block in run_load_hooks'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:44:in `each'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/lazy_load_hooks.rb:44:in `run_load_hooks'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/base.rb:322:in `<module:ActiveRecord>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/base.rb:22:in `<top (required)>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/maintenance_scheduler/app/models/cmts_device.rb:1:in `<top (required)>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `load'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `block in load_file'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:615:in `new_constants_in'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:422:in `load_file'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:323:in `require_or_load'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:288:in `depend_on'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:206:in `require_dependency'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:465:in `block (2 levels) in eager_load!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:464:in `each'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:464:in `block in eager_load!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:462:in `each'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:462:in `eager_load!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/engine.rb:347:in `eager_load!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/finisher.rb:56:in `each'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `instance_exec'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:30:in `run'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:55:in `block in run_initializers'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:180:in `each'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'
from /home/aayerd200/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/initializable.rb:54:in `run_initializers'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:215:in `initialize!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/maintenance_scheduler/config/environment.rb:7:in `<top (required)>'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:189:in `require'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application.rb:189:in `require_environment!'
from /home/aayerd200/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands.rb:63:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
```
With ReadyForRails4...
Input as...
```
source 'http://rubygems.org'
gem 'rails', '4.0.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'activerecord-oracle_enhanced-adapter'
gem 'ruby-oci8'
gem 'mysql2'
gem 'prototype-rails'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
```
 | 2013/07/17 | ['https://Stackoverflow.com/questions/17708537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/924501/'] | It seems the gem `activerecord-oracle_enhanced-adapter` is not compatible with Rails 4.
This is the file which should have that method `arel_attributes_value`:
>
> <http://github.com/rails/rails/blob/master/activerecord/lib/>…
>
>
>
And here is the file at 3.2-stable branch.
>
> <http://github.com/rails/rails/blob/3-2-stable/activerecord/lib/>…
>
>
>
The method is there at the second file (3.2-stable), but it's not in the first (master). So it was probably removed in Rails 4.
If I were you I'd just revert back to 3.2 for now, but if you want to use Rails 4 anyway, it seems there's a branch for Rails 4.
So you go to your Gemfile and change the line
>
> gem 'activerecord-oracle\_enhanced-adapter'
>
>
>
to
>
> gem 'activerecord-oracle\_enhanced-adapter', github: 'rsim/oracle-enhanced', branch: 'rails4'
>
>
>
and `bundle update`. And that should do it. | The updated version of the **activerecord-oracle\_enhanced-adapter** gem supports Rails 4.
Add this to your gem file
```
gem "activerecord-oracle_enhanced-adapter", "~> 1.5.0"
```
This worked for me for Rails 4.0.2
Hope this helps.
PS: Here is the [github link](https://github.com/rsim/oracle-enhanced) for the gem. |
21,895,556 | I have a OData WCF Data Service and I use Reflection Provider to expose data. Currently I expose collection of, say, Environments, which have the following structure:
***{Environments}***
-Name
-Id
-Description
-***{UpdateTime}***
--StartTime
--EndTime
, where {UpdateTime} - ComplexType, is the collection of times, when Environment was updated and relationship here is 1:N.
I'm using Excel to generate some reports from that OData service. After I imported data UpdateTime collection is not showing in a table. I've also tried $expand on the Environment collection, but it doesn't work for me as well. The only way I think of is to expose related collection as an entity type and set relationships, but {UpdateTime} collection doesn't make sense on it's own.
**Question:** Is there any way to make ComplexTypes be shown in Excel?
Thank you! | 2014/02/20 | ['https://Stackoverflow.com/questions/21895556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1547228/'] | I'm not sure which functionality are you using to import data from your OData service. But I guess you are not using Power Query for Excel since I've been using it a lot to import data containing such expanding requirements, and it works just perfect.
Power Query for Excel is an extension of Excel officially made by Microsoft and you can download it here: <http://www.microsoft.com/en-in/download/details.aspx?id=39379>. It is more powerful than the "DATA" tab installed with Excel by default that you can do a lot of shaping and merging of your datasets.
After you've installed it, it will show up on Excel as a new tab and you can easily import data from an OData feed and expand complex type containing collections in the Power Query query editor.
Sorry I don't have enough reputation to attach an image. But you can navigate to this page as an example: <http://office.microsoft.com/en-in/excel-help/expand-a-column-containing-a-related-table-HA103993865.aspx> | Excel should be able to import complex values without an issue as far as I know. Here's what I did:
1. In Excel, go to Data->From Other Sources->From OData Data Feed
2. For the location of the data feed, I entered `http://services.odata.org/v3/odata/odata.svc/Suppliers`, a test service. Each Supplier has a complex type called Address.
In Excel, all the address stuff showed up fine.
So I'm guessing there's a problem with your service or the URL you're providing to Excel. If you request your feed from a browser, do the complex values show up correctly? |
28,202,116 | I have sqoopd data from Netezza table and output file is in HDFS, but one column is a timestamp and I want to load it as a date column in my hive table. Using that column I want to create partition on date. How can i do that?
Example: in HDFS data is like = 2013-07-30 11:08:36
In hive I want to load only date (2013-07-30) not timestamps. I want to partition on that column DAILY.
How can I pass partition by column as dynamically?
I have tried with loading data into one table as source. In final table I will do insert overwrite table partition by (date\_column=dynamic date) select \* from table1 | 2015/01/28 | ['https://Stackoverflow.com/questions/28202116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103077/'] | I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding! | your car class could imlpement the Comparable interface :
```
public class Car implements Comparable<Car>
@Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
```
and the you can sort your array at the end of your while:
```
Arrays.sort(carList);
```
this should somehow work i guess :) |
28,202,116 | I have sqoopd data from Netezza table and output file is in HDFS, but one column is a timestamp and I want to load it as a date column in my hive table. Using that column I want to create partition on date. How can i do that?
Example: in HDFS data is like = 2013-07-30 11:08:36
In hive I want to load only date (2013-07-30) not timestamps. I want to partition on that column DAILY.
How can I pass partition by column as dynamically?
I have tried with loading data into one table as source. In final table I will do insert overwrite table partition by (date\_column=dynamic date) select \* from table1 | 2015/01/28 | ['https://Stackoverflow.com/questions/28202116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103077/'] | Ideally you should avoid the problem of having to sort two arrays simultaneously by adding the currentDistance field to the Car class. Then you can sort the carList using currentDistance.
For example, using java 8 you can get the first 3 places with:
```
Arrays.stream(carList)
.sorted((c1, c2) -> c2.currentDistance - c1.currentDistance)
.map(c -> c.getName())
.limit(3);
``` | your car class could imlpement the Comparable interface :
```
public class Car implements Comparable<Car>
@Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
```
and the you can sort your array at the end of your while:
```
Arrays.sort(carList);
```
this should somehow work i guess :) |
28,202,116 | I have sqoopd data from Netezza table and output file is in HDFS, but one column is a timestamp and I want to load it as a date column in my hive table. Using that column I want to create partition on date. How can i do that?
Example: in HDFS data is like = 2013-07-30 11:08:36
In hive I want to load only date (2013-07-30) not timestamps. I want to partition on that column DAILY.
How can I pass partition by column as dynamically?
I have tried with loading data into one table as source. In final table I will do insert overwrite table partition by (date\_column=dynamic date) select \* from table1 | 2015/01/28 | ['https://Stackoverflow.com/questions/28202116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103077/'] | Hava a look at this custom Comparator,
put this code after your `while` loop,
```
Collections.sort(Arrays.asList(carList), new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
return Float.compare(o2.myDistance(), o1.myDistance());
}
});
```
to print the sorted names along with their rank,
```
for (Car s : carList){
System.out.println(s.myDistance() + " " + s.myName());
}
```
**Output:**
```
THE WINNER OF THE RACE IS: Andrew Johnson For team: CocaCola
100.004135 Andrew Johnson
99.623375 Jesus Defualt
99.23477 Andrew Smith
99.20563 Andrew Andrew
98.94183 Jesus Defualt
98.87631 Blondey Gold
98.86331 Jesus Defualt
98.64405 steave smith
98.54269 Jason seglad
98.24685 Bob Joe
98.23995 Andrew Kosevsky
98.06155 Ricky Bobby
97.81364 Jess TheHellItIs
97.77215 Blondey Gold
97.72567 Ashey GirslCanDriveTo
97.57001 Ashey GirslCanDriveTo
97.54619 Cheese farlin
97.29426 Andrew Kralovec
96.68102 Andrew Kosevsky
96.018654 Ashey GirslCanDriveTo
```
to list the first 5 places, use this instead,
```
for (int i=0; i<5; i++){
System.out.println(carList[i].myDistance() + " " + carList[i].myName() + ", -- Rank: " + (i+1));
}
```
This could be done more easily if you are using Java 8,
```
Arrays.stream(carList)
.sorted((a, b) -> Float.compare(b.myDistance(), a.myDistance()))
.map(c -> c.myDistance() + " " + c.myName())
.forEachOrdered(System.out::println);
```
This will get you the ranks of all the drivers in descending order along with their respective speed. | your car class could imlpement the Comparable interface :
```
public class Car implements Comparable<Car>
@Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
```
and the you can sort your array at the end of your while:
```
Arrays.sort(carList);
```
this should somehow work i guess :) |
28,202,116 | I have sqoopd data from Netezza table and output file is in HDFS, but one column is a timestamp and I want to load it as a date column in my hive table. Using that column I want to create partition on date. How can i do that?
Example: in HDFS data is like = 2013-07-30 11:08:36
In hive I want to load only date (2013-07-30) not timestamps. I want to partition on that column DAILY.
How can I pass partition by column as dynamically?
I have tried with loading data into one table as source. In final table I will do insert overwrite table partition by (date\_column=dynamic date) select \* from table1 | 2015/01/28 | ['https://Stackoverflow.com/questions/28202116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103077/'] | Ideally you should avoid the problem of having to sort two arrays simultaneously by adding the currentDistance field to the Car class. Then you can sort the carList using currentDistance.
For example, using java 8 you can get the first 3 places with:
```
Arrays.stream(carList)
.sorted((c1, c2) -> c2.currentDistance - c1.currentDistance)
.map(c -> c.getName())
.limit(3);
``` | I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding! |
28,202,116 | I have sqoopd data from Netezza table and output file is in HDFS, but one column is a timestamp and I want to load it as a date column in my hive table. Using that column I want to create partition on date. How can i do that?
Example: in HDFS data is like = 2013-07-30 11:08:36
In hive I want to load only date (2013-07-30) not timestamps. I want to partition on that column DAILY.
How can I pass partition by column as dynamically?
I have tried with loading data into one table as source. In final table I will do insert overwrite table partition by (date\_column=dynamic date) select \* from table1 | 2015/01/28 | ['https://Stackoverflow.com/questions/28202116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103077/'] | Hava a look at this custom Comparator,
put this code after your `while` loop,
```
Collections.sort(Arrays.asList(carList), new Comparator<Car>() {
@Override
public int compare(Car o1, Car o2) {
return Float.compare(o2.myDistance(), o1.myDistance());
}
});
```
to print the sorted names along with their rank,
```
for (Car s : carList){
System.out.println(s.myDistance() + " " + s.myName());
}
```
**Output:**
```
THE WINNER OF THE RACE IS: Andrew Johnson For team: CocaCola
100.004135 Andrew Johnson
99.623375 Jesus Defualt
99.23477 Andrew Smith
99.20563 Andrew Andrew
98.94183 Jesus Defualt
98.87631 Blondey Gold
98.86331 Jesus Defualt
98.64405 steave smith
98.54269 Jason seglad
98.24685 Bob Joe
98.23995 Andrew Kosevsky
98.06155 Ricky Bobby
97.81364 Jess TheHellItIs
97.77215 Blondey Gold
97.72567 Ashey GirslCanDriveTo
97.57001 Ashey GirslCanDriveTo
97.54619 Cheese farlin
97.29426 Andrew Kralovec
96.68102 Andrew Kosevsky
96.018654 Ashey GirslCanDriveTo
```
to list the first 5 places, use this instead,
```
for (int i=0; i<5; i++){
System.out.println(carList[i].myDistance() + " " + carList[i].myName() + ", -- Rank: " + (i+1));
}
```
This could be done more easily if you are using Java 8,
```
Arrays.stream(carList)
.sorted((a, b) -> Float.compare(b.myDistance(), a.myDistance()))
.map(c -> c.myDistance() + " " + c.myName())
.forEachOrdered(System.out::println);
```
This will get you the ranks of all the drivers in descending order along with their respective speed. | I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding! |
14,216 | [This is my $3^{rd}$ question](https://physics.stackexchange.com/questions/731736/why-2d-lvert-v-1-v-2-rvert-while-overtaking) being closed.
I don't know what "concepts" are any more! The basic concepts are available just about on any site and if one is not good at them then they should mostly revise their texts/notes, etc., but what mostly the issue is their application that is hard and one needs help in. The basics of Newtonian physics are its three laws. Is it really the case one won't ever get stuck after reading and understanding them? I don't think so.
Just marking every question as a "homework" question and then judging the users from that lens is utterly distasteful. None of my questions are homework questions per se and when someone responds while saying that "they expect you to do it this way", I'm asking myself who are "they" (and neither is anybody expecting anything) and though many questions come here might have that as their origin, not in my case and each case really must be looked at that way and trying to not err on the closing side, but the opposite.
I'm new here and in all the closed $3$ questions I've been pestered that my questions are not conceptual. Why have the questions been asked to be shaped according to the answers? It's really topsy-turvy and shouldn't be how the things should be.
My $3$ questions are related. First, I asked while mentioning my working related to it and where I was struggling. It was closed. Then I asked it as an open-ended question, so no one had to really bother with my working which I was anyway mentioning without being the focus (but that's how not it was being seen). Lastly, my recent post I added after I received an answer on another SE site and in that I was unable to understand something from a physics' perspective, but again it was closed!
If someone is not in the mood of helping, kindly don't spend your time instead of some other recreational activity than to in review queues; it's really not adding value. It's just too much curation, imho. Probably the view has shifted from instead of looking for dirt to now establishing some gold-standard which is too far and counterproductive from what the actual intention must be.
If you still think I'm wrong, kindly just tell me how to correct at all? And also if you think I came out harsh in the above, I was really not meaning to. If you think all the $3$ posts were correct to be closed or that the post can't be corrected and is simply irrelevant that would be fine as an answer too as I'll get the takeaway from the site and might rarely post anything which if I feel is really "conceptual" (and trivial).
It's just that there are a thousand users here and many I feel might be interested in helping users like me and even find the question itself interesting, but some users are too keen on doing a service to them which I think is a disservice or over-service at least.
Also, considering the following which is present in one of the links that is now above my question for which it got closed is:
[](https://i.stack.imgur.com/zHb4R.png)
And that *is* my case, but feel free to just trying your best to trying to paint or prove that that's not the case. It would have been much better and constructive that even if that's the case if not 100% but 60% and so allowing and rather having a discussion on that!
***Edit:***
Pleased to inform that the post is now opened. Kindly feel free to try and take a jab at it. It's really is mind-boggling. Special thanks to Jim, David Bailey, Jacopo Tissino, Kshitij Kumar and also thanks to all those who pay heed to my concerns. And last but not the least, thanks (and congrats) to PSE. :) | 2022/10/12 | ['https://physics.meta.stackexchange.com/questions/14216', 'https://physics.meta.stackexchange.com', 'https://physics.meta.stackexchange.com/users/347808/'] | Why not take a deep breath here.
You have been member for all of three days, whereas the site has been around for 11+ years, yet you are comfortable in declaring that it "shouldn't how the things should be." and there are too many closures.
Have you considered an alternative scenario whereby people value the site precisely because "things are the way they are"?
Part of the difficulty with many new users is they see the purpose of the site as one where their *specific* questions are answered. Yet the purpose of the site is precisely NOT that: we strive instead to answer questions that are of interest to users beyond the original poster, i.e. to provide value *to the site* rather than merely to the OP.
I will admit that your specific question is not without conceptual interest but I respect the opinion of those who thought it was a homework-like or "do my work" question, especially as your two previous attempts with posting this question resulted in closure. I certainly *do not agree* with your statement that there is too much closing on this site.
A constructive approach to re-opening any closed question after it is closed the *first time* is not to repost it without improvements but instead to edit it and try to resolve the issue. It is not easy and it takes time to write good questions, and honestly after 3 helpings of the same question over slightly more than 48hrs it's difficult to believe you took time to write a good question or make useful edits. If you are in a rush, don't blame others for closing your question quickly: this is not an answering service.
In your case, you could consider digesting the answer from MSE, making your own graphs and try isolate from the graphs the origin of the disputed $\vert v\_1-v\_2\vert$ factor. Does this factor make sense if both velocities are the same? How would you see this graphically? You can always use chat to discuss how to best clarify your post. | Users here don't want to "brain-storm". They simply want to see questions that they can solve "easily" without taking any pains. "What is momentum?" or "What is the difference between momentum and kinetic energy?" - "Oh my! such a pitiful confusion, let me get my pillow, lie on the sofa and spread my legs... yup, so here the solution..." - while this might not be the case at all but that's how things came across to me.
It is indeed much more uncomfortable (relatively) when someone asks an application (which is not strictly that either in my case, but users here don't want to see the "concepts" in it) based question which seems in "your" opinion is devoid of any concepts. In my case, for example, the working I got from a user on MSE was all apparently correct but the physics wasn't fitting well. This should have been a really interesting problem here but I was disappointed to know the reality.
The pic attached in the question (in the OP's question above) says exactly that but NO! Once some 2 or 3 users have decided that the post must be closed, like sheep, all huddle together and support that decision in one voice. Note that it's not how your question is that matters, in the end, it is that:
1. whether you have spent enough time. (Minimum 24 hours just to frame a question though 48 would be apt)
2. whether site is having a tough time.
3. whether the user who posted the question has been around particularly on PSE (not on any other related site as we our just something else). Of course, we safely assume you never visited this site ever before for any post whatsoever.
4. whether the question cries of having some confusion in a "concept" and that too directly (indirectly is just too much pain to figure out).
Reviewers here don't have the attitude to search for which questions could be saved but the exact opposite.
Why did you (that is, me) come here again? Well I got a comment from a user which again lead me to ponder over this issue so ya in all likelihood this is not really worth it but anyways, most likely the last time.
Well, before we feel to start some discussion, why not take a deep breath here. |
416,967 | Is there a program or utility that allows me to connect a touchscreen to my desktop PC and use it as a keyboard input device? My plan is to upgrade the screen on my laptop, pair the old screen with a touchscreen overlay and an inverter, connect it as another monitor to my desktop, and then lay it flat on my desk and use it for a keyboard.
I know that devices like the iPad have a virtual keyboard that is used to type on-screen, and my plan is to have a virtual keyboard like this running on the touchscreen all the time.
P.S. If there were any way to also use a portion of the touchscreen as a laptop-style touchpad, this would be very nice also. Thanks! | 2012/04/26 | ['https://superuser.com/questions/416967', 'https://superuser.com', 'https://superuser.com/users/130312/'] | There are many [Virtual Keyboards](http://en.wikipedia.org/wiki/Virtual_keyboard) you could use for this purpose.
Some options:
* **Windows** has a built-in one called [On Screen Keyboard](http://windows.microsoft.com/en-us/windows7/Type-without-using-the-keyboard-On-Screen-Keyboard).
* **Mac OS X** can use a [Dashboard widget](http://www.apple.com/downloads/dashboard/reference/onscreenkeyboard.html). There may be a built-in one, but I'm unaware of it.
* **Linux** in general has many different programs, typically matching their desktop environments and often included as part of the distribution. A popular one for GNOME is [Florence](http://florence.sourceforge.net/english.html).
* Ubuntu, at least several versions ago, [came with one called onboard](https://www.combibo.net/articles/using_an_onscreen_keyboard_in_ubuntu/)
---
There is a (proposed) program called [Virtual Touchpad](http://code.google.com/p/virtual-touchpad/) that, funnily enough, allows you to use a virtual touchpad. Unfortunately, it looks like an abandoned project with no real work done. There is no shortage of phone or tablet applications that provide similar functionality, however, [as Lèse majesté points out](https://superuser.com/a/416992/117590).
The problem with trying to find such a program (aside from the utter rubbish that Google comes up with when searching for this) is most people tend to use a touchscreen directly, not with an indirect virtual touchpad. Of course, if you could get your OS to recognise your screen overlay as a tablet, that may help. It would probably make virtual keyboard use more difficult, however. (By tablet I mean the [input device](http://en.wikipedia.org/wiki/Graphics_tablet), not the underpowered computers/oversized phones.) | Bob's suggestion is probably best for keyboard, but if you want to use an Android touchscreen device as a mouse, you can use [RemoteDroid](http://remotedroid.net/) or [premotedroid](http://code.google.com/p/premotedroid/). Each requires a server app you run on your computer as well as the Android app client that you run on your phone/tablet.
As I understand it, you can only use the touchscreen as a laptop-style touchpad, not as an actual tablet device (i.e. you can't map the device to an area of the screen and draw on the tablet like a digitizer tablet), but you can at least use it as a mouse substitute. |
416,967 | Is there a program or utility that allows me to connect a touchscreen to my desktop PC and use it as a keyboard input device? My plan is to upgrade the screen on my laptop, pair the old screen with a touchscreen overlay and an inverter, connect it as another monitor to my desktop, and then lay it flat on my desk and use it for a keyboard.
I know that devices like the iPad have a virtual keyboard that is used to type on-screen, and my plan is to have a virtual keyboard like this running on the touchscreen all the time.
P.S. If there were any way to also use a portion of the touchscreen as a laptop-style touchpad, this would be very nice also. Thanks! | 2012/04/26 | ['https://superuser.com/questions/416967', 'https://superuser.com', 'https://superuser.com/users/130312/'] | Bob's suggestion is probably best for keyboard, but if you want to use an Android touchscreen device as a mouse, you can use [RemoteDroid](http://remotedroid.net/) or [premotedroid](http://code.google.com/p/premotedroid/). Each requires a server app you run on your computer as well as the Android app client that you run on your phone/tablet.
As I understand it, you can only use the touchscreen as a laptop-style touchpad, not as an actual tablet device (i.e. you can't map the device to an area of the screen and draw on the tablet like a digitizer tablet), but you can at least use it as a mouse substitute. | ### Use android-vnc-viewer to mirror the desktop PC screen, and control the desktop
I had another question on android.stackexchange.com: ([In using a VNC to control a computer, is it possible to have the cursor go to where you touch?](https://android.stackexchange.com/questions/34668/in-using-a-vnc-to-control-a-computer-is-it-possible-to-have-the-cursor-go-to-wh))
In the question, I included a [video](http://www.youtube.com/watch?v=sTKX6QMBgck#t=0m30s): Remote control of Ubuntu with android-vnc-viewer
android-vnc-viewer
>
> “See and control your computer's desktop from your phone, from
> anywhere. androidVNC is the Open Source (GPL) remote desktop program
> for Android devices. Connects to most VNC servers: incl TightVNC,
> RealVNC on Win and Linux, x11vnc, and Apple Remote Desktop on OS/X.”.
>
>
>
In the video, I don't know the input mode that is being demonstrated at 0:30, but it looks like the mouse cursor goes to where he touches.
<http://code.google.com/p/android-vnc-viewer/>
I'm guessing that the input mode in the video was either:
>
> Touch Mouse Pan and Zoom
>
> This is the default input mode and is
> designed to work like the Android browser. You can both pan the
> display and control the mouse using the touchscreen and gestures. You
> pan by dragging or flicking on the touchscreen; you click the mouse by
> tapping on it. You right-click by double-tapping (or by holding down
> the camera button while tapping). You drag the mouse by doing a long
> press on the display, and then dragging. In this mode the trackball or
> DPad (if your phone has one) can also be used to control the mouse;
> this may give you finer control. You can zoom the screen size with the
> +/- buttons, or, if your device supports multi-touch and has Android 2.0+, you can pinch to zoom out and spread to zoom in.
>
>
>
or:
>
> Mouse Control Mode
>
> In this mode, use the touchscreen to control the
> mouse. Touching the screen generates a mouse click at that point;
> dragging on the screen creates a mouse drag. Keyboard events are sent
> as normal. The trackball is used to send arrow-key events to the VNC
> server. Pressing the trackball toggles between Mouse Pointer Control
> and Desktop Panning modes.
>
>
>
Port forwarding
>
> If the PC you're connecting to accesses the internet through a router,
> this will be the WAN address assigned to the router by your ISP;
> you'll also need to forward the VNC port (5900) from the router to
> your PC (exactly how you do this depends on the details of your
> router, so I can't give more explicit instructions here).
>
>
>
### Hacker's Keyboard - use a full soft keyboard on Android
From what I've read, the stock android keyboard doesn't have buttons such as Ctrl, Alt, Esc, arrow keys, Home, End, and Delete.
You can use the free, open source, app call Hacker's Keyboard to gain access to the buttons of a full keyboard:
>
> “Are you missing the key layout you're used to from your computer?
> This keyboard has separate number keys, punctuation in the usual
> places, and arrow keys. It is based on the AOSP Gingerbread soft
> keyboard, so it supports multitouch for the modifier keys.
>
>
> This keyboard is especially useful if you use ConnectBot for SSH
> access. It provides working Tab/Ctrl/Esc keys, and the arrow keys are
> essential for devices such as the Xoom tablet or Nexus S that don't
> have a trackball or D-Pad.”
>
>
>
<http://code.google.com/p/hackerskeyboard/>
### A patch that allows android-vnc-viewer to recognize all the keys of Hacker's Keyboard
In “Frequently Asked Questions” of Hacker's Keyboard, there's a section called “Android VNC Viewer doesn't recognize the extra keys”.
It directs you to an issue called “[Issue 238: Support additional keys, fix modifier handling](http://code.google.com/p/android-vnc-viewer/issues/detail?id=238)”. The patch there will make it so that Android VNC Viewer recognizes buttons of a full keyboard.
### Update: bVNC
>
> bVNC is a secure, open source VNC client.
>
>
> * Tested with Hackerskeyboard. Using it is recommended (get hackers keyboard from Google Play).
>
>
>
play[dot]google[dot]com/store/apps/details?id=com.iiordanov.freebVNC&hl=en |
416,967 | Is there a program or utility that allows me to connect a touchscreen to my desktop PC and use it as a keyboard input device? My plan is to upgrade the screen on my laptop, pair the old screen with a touchscreen overlay and an inverter, connect it as another monitor to my desktop, and then lay it flat on my desk and use it for a keyboard.
I know that devices like the iPad have a virtual keyboard that is used to type on-screen, and my plan is to have a virtual keyboard like this running on the touchscreen all the time.
P.S. If there were any way to also use a portion of the touchscreen as a laptop-style touchpad, this would be very nice also. Thanks! | 2012/04/26 | ['https://superuser.com/questions/416967', 'https://superuser.com', 'https://superuser.com/users/130312/'] | There are many [Virtual Keyboards](http://en.wikipedia.org/wiki/Virtual_keyboard) you could use for this purpose.
Some options:
* **Windows** has a built-in one called [On Screen Keyboard](http://windows.microsoft.com/en-us/windows7/Type-without-using-the-keyboard-On-Screen-Keyboard).
* **Mac OS X** can use a [Dashboard widget](http://www.apple.com/downloads/dashboard/reference/onscreenkeyboard.html). There may be a built-in one, but I'm unaware of it.
* **Linux** in general has many different programs, typically matching their desktop environments and often included as part of the distribution. A popular one for GNOME is [Florence](http://florence.sourceforge.net/english.html).
* Ubuntu, at least several versions ago, [came with one called onboard](https://www.combibo.net/articles/using_an_onscreen_keyboard_in_ubuntu/)
---
There is a (proposed) program called [Virtual Touchpad](http://code.google.com/p/virtual-touchpad/) that, funnily enough, allows you to use a virtual touchpad. Unfortunately, it looks like an abandoned project with no real work done. There is no shortage of phone or tablet applications that provide similar functionality, however, [as Lèse majesté points out](https://superuser.com/a/416992/117590).
The problem with trying to find such a program (aside from the utter rubbish that Google comes up with when searching for this) is most people tend to use a touchscreen directly, not with an indirect virtual touchpad. Of course, if you could get your OS to recognise your screen overlay as a tablet, that may help. It would probably make virtual keyboard use more difficult, however. (By tablet I mean the [input device](http://en.wikipedia.org/wiki/Graphics_tablet), not the underpowered computers/oversized phones.) | ### Use android-vnc-viewer to mirror the desktop PC screen, and control the desktop
I had another question on android.stackexchange.com: ([In using a VNC to control a computer, is it possible to have the cursor go to where you touch?](https://android.stackexchange.com/questions/34668/in-using-a-vnc-to-control-a-computer-is-it-possible-to-have-the-cursor-go-to-wh))
In the question, I included a [video](http://www.youtube.com/watch?v=sTKX6QMBgck#t=0m30s): Remote control of Ubuntu with android-vnc-viewer
android-vnc-viewer
>
> “See and control your computer's desktop from your phone, from
> anywhere. androidVNC is the Open Source (GPL) remote desktop program
> for Android devices. Connects to most VNC servers: incl TightVNC,
> RealVNC on Win and Linux, x11vnc, and Apple Remote Desktop on OS/X.”.
>
>
>
In the video, I don't know the input mode that is being demonstrated at 0:30, but it looks like the mouse cursor goes to where he touches.
<http://code.google.com/p/android-vnc-viewer/>
I'm guessing that the input mode in the video was either:
>
> Touch Mouse Pan and Zoom
>
> This is the default input mode and is
> designed to work like the Android browser. You can both pan the
> display and control the mouse using the touchscreen and gestures. You
> pan by dragging or flicking on the touchscreen; you click the mouse by
> tapping on it. You right-click by double-tapping (or by holding down
> the camera button while tapping). You drag the mouse by doing a long
> press on the display, and then dragging. In this mode the trackball or
> DPad (if your phone has one) can also be used to control the mouse;
> this may give you finer control. You can zoom the screen size with the
> +/- buttons, or, if your device supports multi-touch and has Android 2.0+, you can pinch to zoom out and spread to zoom in.
>
>
>
or:
>
> Mouse Control Mode
>
> In this mode, use the touchscreen to control the
> mouse. Touching the screen generates a mouse click at that point;
> dragging on the screen creates a mouse drag. Keyboard events are sent
> as normal. The trackball is used to send arrow-key events to the VNC
> server. Pressing the trackball toggles between Mouse Pointer Control
> and Desktop Panning modes.
>
>
>
Port forwarding
>
> If the PC you're connecting to accesses the internet through a router,
> this will be the WAN address assigned to the router by your ISP;
> you'll also need to forward the VNC port (5900) from the router to
> your PC (exactly how you do this depends on the details of your
> router, so I can't give more explicit instructions here).
>
>
>
### Hacker's Keyboard - use a full soft keyboard on Android
From what I've read, the stock android keyboard doesn't have buttons such as Ctrl, Alt, Esc, arrow keys, Home, End, and Delete.
You can use the free, open source, app call Hacker's Keyboard to gain access to the buttons of a full keyboard:
>
> “Are you missing the key layout you're used to from your computer?
> This keyboard has separate number keys, punctuation in the usual
> places, and arrow keys. It is based on the AOSP Gingerbread soft
> keyboard, so it supports multitouch for the modifier keys.
>
>
> This keyboard is especially useful if you use ConnectBot for SSH
> access. It provides working Tab/Ctrl/Esc keys, and the arrow keys are
> essential for devices such as the Xoom tablet or Nexus S that don't
> have a trackball or D-Pad.”
>
>
>
<http://code.google.com/p/hackerskeyboard/>
### A patch that allows android-vnc-viewer to recognize all the keys of Hacker's Keyboard
In “Frequently Asked Questions” of Hacker's Keyboard, there's a section called “Android VNC Viewer doesn't recognize the extra keys”.
It directs you to an issue called “[Issue 238: Support additional keys, fix modifier handling](http://code.google.com/p/android-vnc-viewer/issues/detail?id=238)”. The patch there will make it so that Android VNC Viewer recognizes buttons of a full keyboard.
### Update: bVNC
>
> bVNC is a secure, open source VNC client.
>
>
> * Tested with Hackerskeyboard. Using it is recommended (get hackers keyboard from Google Play).
>
>
>
play[dot]google[dot]com/store/apps/details?id=com.iiordanov.freebVNC&hl=en |
87,257 | Is there any pros and cons for using of Unicode (and vice versa) in LaTeX equations?
Consider two examples:
```
\lim_{h→0}∫_{x_0}^{x_0 + h}\frac{f(t)}{h} = f(x_0)
x_0 ⇔ ∀ > 0, ∃ > 0,(|x-x_0| < ⇒ |f(x)-f(x_0)| < )
```
And without Unicode:
```
\lim\limits_{h \to 0}\int\limits_{x_0}^{x_0+h}\frac{f(t)}{h}=f(x_0)
x_0 \Leftrightarrow \forall\epsilon > 0, \exists\delta>0,(|x-x_0|<\delta \Rightarrow |f(x)-f(x_0)|<\epsilon)
```
With latest XeLaTeX the result is the same, so!, what's better? | 2012/12/16 | ['https://tex.stackexchange.com/questions/87257', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/9790/'] | The pros and cons are pretty much the same as they ever were. Old timers like myself have a built in familiarity with ascii based markup, but I suspect that this will seem increasingly anachronistic as we move further in to the 21st century. Web based tools (and as Count Zero noted) Word processing systems and increasingly command line shells of common operating systems have a natural Unicode handling, and I suspect newer users will find it harder to accept restricting to an ascii character set.
There was a time that the general feeling was that people should use `\"{o}` or `\'e` markup "for portability and ease of editing tools" rather than use `ö` or `é` but now I suspect that more or less anyone writing non English documents uses `[latin1]` or `[utf8]` with `inputenc` or uses `xelatex` or `luatex` and native Unicode input.
Despite the above, there are some advantages to using markup over direct character input, other than just familiarity for people who grew up using punched cards. One example that it is much easier to check that various document norms and conventions are upheld. For example if you want a particular arrow style it's probably easier (by eye) to spot (say) `\longrightarrow` than to recognise the multitude of different Unicode arrows. Also it depends on your tools, but for most of the tools I have it is still quicker and easier to type `\longrightarrow` than `⟶`. But note that editing tools can completely lose the distinction, allowing you to type `\longrightarrow` but entering `⟶`which is one reason why I suspect, as noted above that Unicode in files will become the norm. | I’ll focus on Greek in this answer because many of the issues this question raises apply more to Greek than any other alphabet: a lot of math symbols and other scripts are derived directly from Greek letters.
If you look at [an example of a Greek mathematical text](https://web.archive.org/web/20171115223949/http://myria.math.aegean.gr/~atsol/newpage/lecturenotes/convex-geometry/cga.pdf), the original source is not going to write “ΚΥΡΤΗ ΓΕWΜΕΤΡΙΚΗ ΑΝΑΛΥΣΗ” as `\textKappa\textUpsilon\textRho\textTau\textEta` .... The source in UTF-8 would be human-readable. It’d be ridiculous to tell the authors, that’s fine, and we have to be able to display Greek letters to read your document anyway, but it’s taboo to type any Greek letter between dollar signs. Probably the only people in the world who’d even take that as up for debate are monolingual English-speakers.
As egreg correctly points out in his comment, “ε (U+03B5, GREEK SMALL LETTER EPSILON) should really be (U+1D700, MATHEMATICAL ITALIC SMALL EPSILON).” But of course that’s exactly the same as how x (U+0078 LATIN SMALL LETTER X) should really be (U+1D465, MATHEMATICAL ITALIC SMALL X). And when I test, `unicode-math` is smart enough to handle it the same way: `ε` in math mode becomes , `\symbfup{ε}` becomes (U+1D6C6 MATHEMATICAL BOLD SMALL EPSILON), and so on. There’s even an option to replace these with MATHEMATICAL EPSILON SYMBOL instead.
One good reason to prefer macros to direct Unicode input is to avoid mixing up symbols that look the same, such as Latin A and Greek Α. [There are no distinct Greek letters Α, Β, Η, Μ, Ν, Ο, Ρ or so on in the legacy OML encoding](http://tug.ctan.org/macros/latex/doc/encguide.pdf), so traditionally these were identical to their Latin lookalikes. You wouldn’t define two identical symbols in the same context with separate meanings! Today, though, it’s possible that different symbols might look different on the screen but the same in the editor, and it’s now possible to copy from and search a PDF that uses a Unicode math font.
(By the way, I just found out that copying and pasting from the official PDF code charts at unicode.org gives you mojibake.)
And, of course, some symbol that works in my editor might not display in yours. Especially some obscure mathematical symbol from the supplementary plane.
One could, on the other hand, argue that if two symbols are so similar that I’m likely to get them mixed up in the editor, a reader who doesn’t already know what I meant might have the same problem. So it might be easier to see right away that ϵ∊ is a problem than that `\epsilon\in` is. |
72,969,048 | I want 3 pictures aligned horizontally, and I want them all to sit next to one another. When I try to use the code below though, the pictures end up on separate lines. Here's what I've got:
**HTML**
```
<section class="features">
<figures>
<img scr="....jpg" alt="...">
<figcaption>...<figcaption>
<img scr="...jpg" alt="...">
<figcaption>...<figcaption>
<img scr="...jpg" alt="...">
<figcaption>...<figcaption>
</figures>
</section>
```
**CSS**
```
.features{
background: white;
color: burlywood;
padding: 28px;
display: flex;
flex-direction: row;
}
.features figure{
margin: auto;
width: 200px;
text-align: center;
text-transform: uppercase;
}
.features figure img{
border-radius: 100px;
width: 200px;
}
``` | 2022/07/13 | ['https://Stackoverflow.com/questions/72969048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19543068/'] | Is `<figures>` a valid HTML tag? Either way, flex on .features and that's mostly all you need
This will also accept images that aren't perfect square and crop them accordingly
```css
* { box-sizing: border-box } body { font: 16px sans-serif; margin: 0 }
.features {
background: white;
color: burlywood;
display: flex;
gap: 28px;
padding: 28px;
}
.features figure {
flex: 1 0 0%;
margin: 0;
text-align: center;
text-transform: uppercase;
}
.features figure img {
aspect-ratio: 1 / 1;
border-radius: 50%;
object-fit: cover;
width: 100%;
}
```
```html
<section class="features">
<figure>
<img src="https://picsum.photos/250/500?random=1" alt="random image 1">
<figcaption>First Image<br><small>(250px X 500px)</small></figcaption>
</figure>
<figure>
<img src="https://picsum.photos/500/250?random=2" alt="random image 2">
<figcaption>Second Image<br><small>(500px X 250px)</small></figcaption>
</figure>
<figure>
<img src="https://picsum.photos/500?random=3" alt="random image 3">
<figcaption>Third Image<br><small>(500px X 500px)</small></figcaption>
</figure>
</section>
``` | I would advise that you put the images and captions in a div element ie:
```
<figures>
<div>
<img 1>
<figcaptions>...<figcaption>
</div>
<div>
<img 2>
<figcaptions>...<figcaption>
</div>
<div>
<img 3>
<figcaptions>...<figcaption>
</div>
</figures>
```
figures should have disply: flex; and justify-content: flex-center;
Hope it helps |
50,211,752 | When trying to use the Bootstrap 4 modal in a block it fails to display correctly. It kinda displays the modal but it is still in a "fade in" mode and then you are unable to close the modal - the only way to exit is by refreshing the browser.
```
<div class="modal fade" id="cartConfirm" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-lg-12 confrm-cart-box">
<div class="close-btn" data-dismiss="modal"><i class="fa fa-times"></i></div>
<h3>order confirmation</h3>
<br>
<br>
<p>Order number <span class="green">123456</span> is now confirmed<br> You can check your order and its progress at any time.<br> By logging into your account</p>
<a href="#" data-toggle="modal" data-target="#multi-login" data-dismiss="modal">Log In</a>
<p>We have emailed you the order details for your convenience.</p>
<p>If you have any queries please contact us.</p>
<p><span class="green">This order is covered by our 100% No Quibble Money Back Guarantee</span></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button data-toggle="modal" data-dismiss="modal" data-target="#cartConfirm">BUY</button>
```
[](https://i.stack.imgur.com/f3Tdy.png) | 2018/05/07 | ['https://Stackoverflow.com/questions/50211752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7378295/'] | Add this css in your file in the tag
`<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">`
It worked for me ! | You just have to add the close button. By this code after `<div class='modal-content'>`
```
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
```
Try this code,
```
<div class="modal fade" id="cartConfirm" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="container">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<div class="row">
<div class="col-lg-12 confrm-cart-box">
<div class="close-btn" data-dismiss="modal"><i class="fa fa-times"></i></div>
<h3>order confirmation</h3>
<br>
<br>
<p>Order number <span class="green">123456</span> is now confirmed<br> You can check your order and its progress at any time.<br> By logging into your account</p>
<a href="#" data-toggle="modal" data-target="#multi-login" data-dismiss="modal">Log In</a>
<p>We have emailed you the order details for your convenience.</p>
<p>If you have any queries please contact us.</p>
<p><span class="green">This order is covered by our 100% No Quibble Money Back Guarantee</span></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button data-toggle="modal" data-dismiss="modal" data-target="#cartConfirm">BUY</button>
```
Here is the fiddle,
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<div class="modal fade" id="cartConfirm" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="container">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<div class="row">
<div class="col-lg-12 confrm-cart-box">
<div class="close-btn" data-dismiss="modal"><i class="fa fa-times"></i></div>
<h3>order confirmation</h3>
<br>
<br>
<p>Order number <span class="green">123456</span> is now confirmed<br> You can check your order and its progress at any time.<br> By logging into your account</p>
<a href="#" data-toggle="modal" data-target="#multi-login" data-dismiss="modal">Log In</a>
<p>We have emailed you the order details for your convenience.</p>
<p>If you have any queries please contact us.</p>
<p><span class="green">This order is covered by our 100% No Quibble Money Back Guarantee</span></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button data-toggle="modal" data-dismiss="modal" data-target="#cartConfirm">BUY</button>
```
I hope this will help you. |
22,313,429 | So one of my latest side projects is developing a application detection and populating assistant. Programmatically I am absolutely fine populating the backend code for what I want accomplished. But I've run into a road block on the GUI. I need a GUI that is a Quarter circle that extends from the task bar to the bottom right of a standard windows operating system. When the user doubleclicks on the application, the circle rotates into view. I can do this with a typical windows form that has a transparent background and a fancy background image. But the square properties of the form will still apply when the user has the application open. And I do not want to block the user from higher priority apps when the circle is open.

I'm not really stuck on any one specific programming language. Although, I would prefer that it not contain much 3d rendering as it is supposed to be a computing assistant and should not maintain heavy RAM/CPU consumption whilst the user is browsing around.
Secondarily, I would like the notches of the outer rings to be mobile and extend beyond the gui a mere centimeter or so.
I would not be here if I hadn't had scoured the internet for direction on this capability. But what I've found is application GUI's of this nature tend to be most used in mobile environments.
So my questions are: How can I accomplish this? What programming language can I write this in? Is this a capability currently available? Will I have to sacrifice user control for design? | 2014/03/10 | ['https://Stackoverflow.com/questions/22313429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1031929/'] | I wrote out some code doing something close to what you described.
I’m not sure to understand how you do want the circle to appear, so I just let a part of it always visible.
And I didn’t get the part about the mobile outer ring.

Creating and placing the window
-------------------------------
The XAML is very simple, it just needs a grid to host the circle’s pieces, and some attributes to remove window decorations and taskbar icon:
```
<Window x:Class="circle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Circle"
Width="250"
Height="250"
AllowsTransparency="True"
Background="Transparent"
MouseDown="WindowClicked"
ShowInTaskbar="False"
WindowStyle="None">
<Grid Name="Container"/>
</Window>
```
To place the window in the bottom right corner, you can use SystemParameters.WorkArea in the constructor:
```
public MainWindow()
{
InitializeComponent();
var desktopDim = SystemParameters.WorkArea;
Left = desktopDim.Right - Width;
Top = desktopDim.Bottom - Height;
}
```
Creating the shape
------------------
I build the circle as a bunch of circle pieces that I generate from code behind:
```
private Path CreateCirclePart()
{
var circle = new CombinedGeometry
{
GeometryCombineMode = GeometryCombineMode.Exclude,
Geometry1 = new EllipseGeometry { Center = _center, RadiusX = _r2, RadiusY = _r2 },
Geometry2 = new EllipseGeometry { Center = _center, RadiusX = _r1, RadiusY = _r1 }
};
var sideLength = _r2 / Math.Cos((Math.PI/180) * (ItemAngle / 2.0));
var x = _center.X - Math.Abs(sideLength * Math.Cos(ItemAngle * Math.PI / 180));
var y = _center.Y - Math.Abs(sideLength * Math.Sin(ItemAngle * Math.PI / 180));
var triangle = new PathGeometry(
new PathFigureCollection(new List<PathFigure>{
new PathFigure(
_center,
new List<PathSegment>
{
new LineSegment(new Point(_center.X - Math.Abs(sideLength),_center.Y), true),
new LineSegment(new Point(x,y), true)
},
true)
}));
var path = new Path
{
Fill = new SolidColorBrush(Colors.Cyan),
Stroke = new SolidColorBrush(Colors.Black),
StrokeThickness = 1,
RenderTransformOrigin = new Point(1, 1),
RenderTransform = new RotateTransform(0),
Data = new CombinedGeometry
{
GeometryCombineMode = GeometryCombineMode.Intersect,
Geometry1 = circle,
Geometry2 = triangle
}
};
return path;
}
```
First step is to build two concentric circles and to combine them in a CombinedGeometry with CombineMode set to exclude. Then I create a triangle just tall enough to contain the section of the ring that I want, and I keep the intersection of these shapes.
Seeing it with the second CombineMode set to xor may clarify:

Building the circle
-------------------
The code above uses some instance fields that make it generic: you can change the number of pieces in the circle or their radius; it will always fill the corner.
I then populate a list with the required number of shape, and add them to the grid:
```
private const double MenuWidth = 80;
private const int ItemCount = 6;
private const double AnimationDelayInSeconds = 0.3;
private readonly Point _center;
private readonly double _r1, _r2;
private const double ItemSpacingAngle = 2;
private const double ItemAngle = (90.0 - (ItemCount - 1) * ItemSpacingAngle) / ItemCount;
private readonly List<Path> _parts = new List<Path>();
private bool _isOpen;
public MainWindow()
{
InitializeComponent();
// window in the lower right desktop corner
var desktopDim = SystemParameters.WorkArea;
Left = desktopDim.Right - Width;
Top = desktopDim.Bottom - Height;
_center = new Point(Width, Height);
_r2 = Width;
_r1 = _r2 - MenuWidth;
Loaded += (s, e) => CreateMenu();
}
private void CreateMenu()
{
for (var i = 0; i < ItemCount; ++i)
{
var part = CreateCirclePart();
_parts.Add(part);
Container.Children.Add(part);
}
}
```
ItemSpacingAngle define the blank between two consecutive pieces.
Animating the circle
--------------------
The final step is to unfold the circle. Using a rotateAnimation over the path rendertransform make it easy.
Remember this part of the CreateCirclePart function:
```
RenderTransformOrigin = new Point(1, 1),
RenderTransform = new RotateTransform(0),
```
The RenderTransform tells that the animation we want to perform is a rotation, and RenderTransformOrigin set the rotation origin to the lower right corner of the shape (unit is percent).
We can now animate it on click event:
```
private void WindowClicked(object sender, MouseButtonEventArgs e)
{
for (var i = 0; i < ItemCount; ++i)
{
if (!_isOpen)
UnfoldPart(_parts[i], i);
else
FoldPart(_parts[i], i);
}
_isOpen = !_isOpen;
}
private void UnfoldPart(Path part, int pos)
{
var newAngle = pos * (ItemAngle + ItemSpacingAngle);
var rotateAnimation = new DoubleAnimation(newAngle, TimeSpan.FromSeconds(AnimationDelayInSeconds));
var tranform = (RotateTransform)part.RenderTransform;
tranform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
}
private void FoldPart(Path part, int pos)
{
var rotateAnimation = new DoubleAnimation(0, TimeSpan.FromSeconds(AnimationDelayInSeconds));
var tranform = (RotateTransform)part.RenderTransform;
tranform.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
}
``` | Not actually answering this, but I liked your question enough that I wanted to get a minimal proof of concept together for fun and I really enjoyed doing it so i thought I'd share my xaml with you:
```
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" x:Class="WpfApplication1.Window2"
Title="Window2" Height="150" Width="150" Topmost="True" MouseLeftButtonDown="Window2_OnMouseLeftButtonDown"
AllowsTransparency="True"
OpacityMask="White"
WindowStyle="None"
Background="Transparent" >
<Grid>
<ed:Arc ArcThickness="40"
ArcThicknessUnit="Pixel" EndAngle="0" Fill="Blue" HorizontalAlignment="Left"
Height="232" Margin="33,34,-115,-116" Stretch="None"
StartAngle="270" VerticalAlignment="Top" Width="232" RenderTransformOrigin="0.421,0.471"/>
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Width="41" Margin="51.515,71.385,0,0" Click="Button_Click" RenderTransformOrigin="0.5,0.5">
<Button.Template>
<ControlTemplate>
<Path Data="M50.466307,88.795148 L61.75233,73.463763 89.647286,102.42368 81.981422,113.07109 z"
Fill="DarkBlue" HorizontalAlignment="Left" Height="39.606"
Stretch="Fill" VerticalAlignment="Top" Width="39.181"/>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</Window>
```
And it looks like this:
 |
7,564,865 | is there a public algorithm that formats German phone numbers (mobile and landlines)? I saw there is a method to format phone numbers `PhoneNumberUtils.getFormatTypeForLocale(Locale locale)` but this is only for NANP countries, [see here](http://en.wikipedia.org/wiki/NANPA). | 2011/09/27 | ['https://Stackoverflow.com/questions/7564865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/517558/'] | You are missing the keyword `ON`, placed after the table name.
```
INNER JOIN tablename ON condition...
``` | ```
SELECT * FROM CARD INNER JOIN PGMeCode ON PGMeCode.Code = CARD.Code AND PGMeCode.CC = CARD.CC INNER JOIN PGM ON PGM.Code = Card.Code WHERE Card.ID = 'SomeThing';
```
Try this query |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Just tell your players to stop it.
----------------------------------
You're making a solution that isn't needed to fix your problem.
Your problem (X) is that players are using mechanics to do things that you don't want them to do. You've come up with a new magic item (Y) as a solution and are asking about that. I'm telling you that isn't solving your problem, and suggesting how you can solve your actual problem.
If the problem is players having the bag do more than it really intends, then the solution is asking the players not to do those things. We're clever people and we'll figure out things no one has thought of. If that thing is disrupting the game, you simply ask for that thing to stop.
You've stated that there is a small problem in the mis-use of additional clauses - so just ask them not to do that. Don't create a new item that is specifically created for them not to do that - just talk to your players.
We're all playing a game together and if someone is doing something that is ruining the fun for others, then it's best to talk about it and find a solution there rather than stick a band-aid on the issue and hope it doesn't come up somewhere else.
### If you really want the bag, then talk to the players
If the bag is the solution, then talk with your players about what their needs are for the bag and what you're actually willing to give them. You'll find a balance between the two only by communicating with the whole table. You'll also likely uncover more things about what everyone would like clarified about mechanics at your actual table. | ### I want a clear way to determine what fits into the bag and what doesn't.
You've touched on some of the problems with the Bag of Holding, but you have missed my single greatest pet peeve about the item: *I have no consistent method of ruling what fits through the mouth of the bag and what doesn't.* Does it stretch to accommodate oddly proportioned objects or creatures that meet the weight and volume requirements? I'm just tired of not having a good answer to "will X fit through the mouth of the bag?" I don't really have a good idea for a solution here, if I did I would have implemented it already. "Magically accommodates anything that meets the weight/volume limit" seems like the easiest thing to work with.
### I don't know the volume of a horse, or anything that isn't an elementary solid.
Related to the last point, *I don't know the volume of stuff*. Sure, I can convert gallons to cubic feet and tell you how much water the bag will hold. But what's the volume of a 359 pound pony? I don't know, *and I shouldn't have to know to tell you what a magic item can do*. I would do away with the interior volume limit and just use weight, because I am much better at knowing the weights of things. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Where does the stuff go? How big does the bag get?
--------------------------------------------------
Without the interdimensional space, putting 12 cubic feet of stuff would result in a bag that is 12 cubic feet in size -- because there is nowhere for the things to go. The item as written decreases the weight, but not the size of the item. So, the party looks like they stole Santa's bag.
Let's think about this a bit more. If the bag doesn't shrink items, then it is decreasing mass but not volume, decreasing the density of the items. Thus the bag becomes less dense the more volume you give it, and so if it becomes less dense than water, it can be abused as a flotation device, and if it becomes less dense than air, it becomes a balloon.
If you update it to shrink the items, you run into some other problems I'll address later.
How long does it take to get something out?
-------------------------------------------
Without the clauses about pulling out the right object, you won't be able to pull the right object out quickly, so you'd have to dump out the entire 12 cubic feet of troll parts to find the 3 silver pieces rattling around the bottom of the bag.
What happens if the bag is ripped?
----------------------------------
Is the item able to be ripped? Magic items, by default, are indestructible by normal means, and without a clause about the bag is open to weird abuse, especially if things don't shrink on their way into the bag. Because you can push the indestructible 12 cubic foot bag that only weighs 5 pounds against a door, or hide behind it.
If it can be ripped. Do the items that leave the bag through the rip remain less dense? And if you add shrinking to address the first question, do they also remain small if they fall through the rip? Or do they suddenly regain their weight and size?
Frame of Reference Challenge
----------------------------
The issues you have with the Bag of Holding can be solved in other ways. Such as not giving it out in tier one play (or at all) or simply forbidding its misuse and abuse. Your item is poorly thought out patch to a problem that isn't about the item, it is about your players -- or at least how you think your players will use the bag.
>
> [C]lauses about bad stuff that happens if you put it into another extradimensional space
>
>
>
If that is a problem at your table don't give them any other extradimensional items if you give them a bag of holding. Spells that create extradimensional effects are higher level spells.
>
> they can also can use it to hide items from divination spells that are limited to the same plane
>
>
>
Then BBEG uses different divination spells, or the BBEG knows who took the items and scry/trace/track the players instead of the item. That isn't about railroading either, it is thinking about what the BBEG would resond to the parties use of the bag to hide the item they want.
The argument that putting the stuff into an extradimensional space is "less complex" than instantly changing the mass (and potentially size) of the item in this plane is weird to me. The extradimensional bag of holding just makes the item go somewhere else, where your bag changes the mass (and potentially volume) of the items inside which if you play with real-world physics can create even more and unexpected abuse than the play-tested and tried and true item from the DMG. But at the end of the day, it is your table, and if you feel a need for the item go for it. | Just tell your players to stop it.
----------------------------------
You're making a solution that isn't needed to fix your problem.
Your problem (X) is that players are using mechanics to do things that you don't want them to do. You've come up with a new magic item (Y) as a solution and are asking about that. I'm telling you that isn't solving your problem, and suggesting how you can solve your actual problem.
If the problem is players having the bag do more than it really intends, then the solution is asking the players not to do those things. We're clever people and we'll figure out things no one has thought of. If that thing is disrupting the game, you simply ask for that thing to stop.
You've stated that there is a small problem in the mis-use of additional clauses - so just ask them not to do that. Don't create a new item that is specifically created for them not to do that - just talk to your players.
We're all playing a game together and if someone is doing something that is ruining the fun for others, then it's best to talk about it and find a solution there rather than stick a band-aid on the issue and hope it doesn't come up somewhere else.
### If you really want the bag, then talk to the players
If the bag is the solution, then talk with your players about what their needs are for the bag and what you're actually willing to give them. You'll find a balance between the two only by communicating with the whole table. You'll also likely uncover more things about what everyone would like clarified about mechanics at your actual table. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Just tell your players to stop it.
----------------------------------
You're making a solution that isn't needed to fix your problem.
Your problem (X) is that players are using mechanics to do things that you don't want them to do. You've come up with a new magic item (Y) as a solution and are asking about that. I'm telling you that isn't solving your problem, and suggesting how you can solve your actual problem.
If the problem is players having the bag do more than it really intends, then the solution is asking the players not to do those things. We're clever people and we'll figure out things no one has thought of. If that thing is disrupting the game, you simply ask for that thing to stop.
You've stated that there is a small problem in the mis-use of additional clauses - so just ask them not to do that. Don't create a new item that is specifically created for them not to do that - just talk to your players.
We're all playing a game together and if someone is doing something that is ruining the fun for others, then it's best to talk about it and find a solution there rather than stick a band-aid on the issue and hope it doesn't come up somewhere else.
### If you really want the bag, then talk to the players
If the bag is the solution, then talk with your players about what their needs are for the bag and what you're actually willing to give them. You'll find a balance between the two only by communicating with the whole table. You'll also likely uncover more things about what everyone would like clarified about mechanics at your actual table. | It feels **reasonably balanced**, but feel free to add the fixes suggested by Thomas Markov. Stricter definitions removes the necessity for arbitrary judgements.
However, J. A. Streich makes a valid comment - **where does things go**, without a portal of some sort? As far as I understand your description, you're planning on not making things "go" anywhere, per se, just **lose all mass and volume** while inside the bag. Since that seems a bit weird in the D&D magic paradigm, I propose a fix:
>
> **Sack of Reduction**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold up to 360 pounds, pre-reduction. Anything placed into the sack will, once fully inside, be subject to a Reduce effect, decreasing its size by one category, until removed from the sack or the sack is destroyed. Creatures in the sack can breathe normally. Putting held objects or physically compliant creatures into the sack or taking them out requires an Action. The mouth of the sack is malleable with a maximum circumference of 3 feet, and the depth of the bag is 4 feet.
>
>
>
Now we're **using the existing magical ideas** of D&D, though the effects are significantly less than the Bag of Holding - the sack will grow in size and weight as you fill it, though not commensurate to what you stuff inside. I specified the mouth, and added the limitation that things must fit wholly inside before being Reduced. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Just tell your players to stop it.
----------------------------------
You're making a solution that isn't needed to fix your problem.
Your problem (X) is that players are using mechanics to do things that you don't want them to do. You've come up with a new magic item (Y) as a solution and are asking about that. I'm telling you that isn't solving your problem, and suggesting how you can solve your actual problem.
If the problem is players having the bag do more than it really intends, then the solution is asking the players not to do those things. We're clever people and we'll figure out things no one has thought of. If that thing is disrupting the game, you simply ask for that thing to stop.
You've stated that there is a small problem in the mis-use of additional clauses - so just ask them not to do that. Don't create a new item that is specifically created for them not to do that - just talk to your players.
We're all playing a game together and if someone is doing something that is ruining the fun for others, then it's best to talk about it and find a solution there rather than stick a band-aid on the issue and hope it doesn't come up somewhere else.
### If you really want the bag, then talk to the players
If the bag is the solution, then talk with your players about what their needs are for the bag and what you're actually willing to give them. You'll find a balance between the two only by communicating with the whole table. You'll also likely uncover more things about what everyone would like clarified about mechanics at your actual table. | Your wording will be confusing to anyone used to D&D's ubiquitous 'bag of holding' and similar items.
-----------------------------------------------------------------------------------------------------
Instead something like this will make it clearer to your players what you are aiming for.
>
> **Sack of Lightness**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears as a normal, large sack with a weight of 5 pounds. It can hold an amount of goods typical for a large sack, 12 cubic feet or so. Items placed entirely inside the sack no longer have weight, allowing the wielder to carry the sack without adding the weight of the items inside it to their carrying capacity. Although the weight is not added, the sack if filled with its full allowance of space is still quite large, so an adventurer carrying multiple of these sacks may look quite comical, or run into problems squeezing through tight spaces.
>
>
> Although used for a similar purpose to a bag of holding, the sack of lightness does not make use of extradimensional spaces and retrieving or adding an item to the sack functions as it would with any nonmagical sack of non-lightness.
>
>
>
Wording is a bit colloquial/chatty there, but it should provide a guide. Provided you make it clear that this isn't a sack of holding or carrying or whatever, it's just a sack that makes items inside not weigh anything in the title and spell it out a few times in the text, your players should get the message. If you don't, they might just assume based on similarity of purpose to another, extremely well known item. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Where does the stuff go? How big does the bag get?
--------------------------------------------------
Without the interdimensional space, putting 12 cubic feet of stuff would result in a bag that is 12 cubic feet in size -- because there is nowhere for the things to go. The item as written decreases the weight, but not the size of the item. So, the party looks like they stole Santa's bag.
Let's think about this a bit more. If the bag doesn't shrink items, then it is decreasing mass but not volume, decreasing the density of the items. Thus the bag becomes less dense the more volume you give it, and so if it becomes less dense than water, it can be abused as a flotation device, and if it becomes less dense than air, it becomes a balloon.
If you update it to shrink the items, you run into some other problems I'll address later.
How long does it take to get something out?
-------------------------------------------
Without the clauses about pulling out the right object, you won't be able to pull the right object out quickly, so you'd have to dump out the entire 12 cubic feet of troll parts to find the 3 silver pieces rattling around the bottom of the bag.
What happens if the bag is ripped?
----------------------------------
Is the item able to be ripped? Magic items, by default, are indestructible by normal means, and without a clause about the bag is open to weird abuse, especially if things don't shrink on their way into the bag. Because you can push the indestructible 12 cubic foot bag that only weighs 5 pounds against a door, or hide behind it.
If it can be ripped. Do the items that leave the bag through the rip remain less dense? And if you add shrinking to address the first question, do they also remain small if they fall through the rip? Or do they suddenly regain their weight and size?
Frame of Reference Challenge
----------------------------
The issues you have with the Bag of Holding can be solved in other ways. Such as not giving it out in tier one play (or at all) or simply forbidding its misuse and abuse. Your item is poorly thought out patch to a problem that isn't about the item, it is about your players -- or at least how you think your players will use the bag.
>
> [C]lauses about bad stuff that happens if you put it into another extradimensional space
>
>
>
If that is a problem at your table don't give them any other extradimensional items if you give them a bag of holding. Spells that create extradimensional effects are higher level spells.
>
> they can also can use it to hide items from divination spells that are limited to the same plane
>
>
>
Then BBEG uses different divination spells, or the BBEG knows who took the items and scry/trace/track the players instead of the item. That isn't about railroading either, it is thinking about what the BBEG would resond to the parties use of the bag to hide the item they want.
The argument that putting the stuff into an extradimensional space is "less complex" than instantly changing the mass (and potentially size) of the item in this plane is weird to me. The extradimensional bag of holding just makes the item go somewhere else, where your bag changes the mass (and potentially volume) of the items inside which if you play with real-world physics can create even more and unexpected abuse than the play-tested and tried and true item from the DMG. But at the end of the day, it is your table, and if you feel a need for the item go for it. | ### I want a clear way to determine what fits into the bag and what doesn't.
You've touched on some of the problems with the Bag of Holding, but you have missed my single greatest pet peeve about the item: *I have no consistent method of ruling what fits through the mouth of the bag and what doesn't.* Does it stretch to accommodate oddly proportioned objects or creatures that meet the weight and volume requirements? I'm just tired of not having a good answer to "will X fit through the mouth of the bag?" I don't really have a good idea for a solution here, if I did I would have implemented it already. "Magically accommodates anything that meets the weight/volume limit" seems like the easiest thing to work with.
### I don't know the volume of a horse, or anything that isn't an elementary solid.
Related to the last point, *I don't know the volume of stuff*. Sure, I can convert gallons to cubic feet and tell you how much water the bag will hold. But what's the volume of a 359 pound pony? I don't know, *and I shouldn't have to know to tell you what a magic item can do*. I would do away with the interior volume limit and just use weight, because I am much better at knowing the weights of things. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | ### I want a clear way to determine what fits into the bag and what doesn't.
You've touched on some of the problems with the Bag of Holding, but you have missed my single greatest pet peeve about the item: *I have no consistent method of ruling what fits through the mouth of the bag and what doesn't.* Does it stretch to accommodate oddly proportioned objects or creatures that meet the weight and volume requirements? I'm just tired of not having a good answer to "will X fit through the mouth of the bag?" I don't really have a good idea for a solution here, if I did I would have implemented it already. "Magically accommodates anything that meets the weight/volume limit" seems like the easiest thing to work with.
### I don't know the volume of a horse, or anything that isn't an elementary solid.
Related to the last point, *I don't know the volume of stuff*. Sure, I can convert gallons to cubic feet and tell you how much water the bag will hold. But what's the volume of a 359 pound pony? I don't know, *and I shouldn't have to know to tell you what a magic item can do*. I would do away with the interior volume limit and just use weight, because I am much better at knowing the weights of things. | It feels **reasonably balanced**, but feel free to add the fixes suggested by Thomas Markov. Stricter definitions removes the necessity for arbitrary judgements.
However, J. A. Streich makes a valid comment - **where does things go**, without a portal of some sort? As far as I understand your description, you're planning on not making things "go" anywhere, per se, just **lose all mass and volume** while inside the bag. Since that seems a bit weird in the D&D magic paradigm, I propose a fix:
>
> **Sack of Reduction**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold up to 360 pounds, pre-reduction. Anything placed into the sack will, once fully inside, be subject to a Reduce effect, decreasing its size by one category, until removed from the sack or the sack is destroyed. Creatures in the sack can breathe normally. Putting held objects or physically compliant creatures into the sack or taking them out requires an Action. The mouth of the sack is malleable with a maximum circumference of 3 feet, and the depth of the bag is 4 feet.
>
>
>
Now we're **using the existing magical ideas** of D&D, though the effects are significantly less than the Bag of Holding - the sack will grow in size and weight as you fill it, though not commensurate to what you stuff inside. I specified the mouth, and added the limitation that things must fit wholly inside before being Reduced. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | ### I want a clear way to determine what fits into the bag and what doesn't.
You've touched on some of the problems with the Bag of Holding, but you have missed my single greatest pet peeve about the item: *I have no consistent method of ruling what fits through the mouth of the bag and what doesn't.* Does it stretch to accommodate oddly proportioned objects or creatures that meet the weight and volume requirements? I'm just tired of not having a good answer to "will X fit through the mouth of the bag?" I don't really have a good idea for a solution here, if I did I would have implemented it already. "Magically accommodates anything that meets the weight/volume limit" seems like the easiest thing to work with.
### I don't know the volume of a horse, or anything that isn't an elementary solid.
Related to the last point, *I don't know the volume of stuff*. Sure, I can convert gallons to cubic feet and tell you how much water the bag will hold. But what's the volume of a 359 pound pony? I don't know, *and I shouldn't have to know to tell you what a magic item can do*. I would do away with the interior volume limit and just use weight, because I am much better at knowing the weights of things. | Your wording will be confusing to anyone used to D&D's ubiquitous 'bag of holding' and similar items.
-----------------------------------------------------------------------------------------------------
Instead something like this will make it clearer to your players what you are aiming for.
>
> **Sack of Lightness**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears as a normal, large sack with a weight of 5 pounds. It can hold an amount of goods typical for a large sack, 12 cubic feet or so. Items placed entirely inside the sack no longer have weight, allowing the wielder to carry the sack without adding the weight of the items inside it to their carrying capacity. Although the weight is not added, the sack if filled with its full allowance of space is still quite large, so an adventurer carrying multiple of these sacks may look quite comical, or run into problems squeezing through tight spaces.
>
>
> Although used for a similar purpose to a bag of holding, the sack of lightness does not make use of extradimensional spaces and retrieving or adding an item to the sack functions as it would with any nonmagical sack of non-lightness.
>
>
>
Wording is a bit colloquial/chatty there, but it should provide a guide. Provided you make it clear that this isn't a sack of holding or carrying or whatever, it's just a sack that makes items inside not weigh anything in the title and spell it out a few times in the text, your players should get the message. If you don't, they might just assume based on similarity of purpose to another, extremely well known item. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Where does the stuff go? How big does the bag get?
--------------------------------------------------
Without the interdimensional space, putting 12 cubic feet of stuff would result in a bag that is 12 cubic feet in size -- because there is nowhere for the things to go. The item as written decreases the weight, but not the size of the item. So, the party looks like they stole Santa's bag.
Let's think about this a bit more. If the bag doesn't shrink items, then it is decreasing mass but not volume, decreasing the density of the items. Thus the bag becomes less dense the more volume you give it, and so if it becomes less dense than water, it can be abused as a flotation device, and if it becomes less dense than air, it becomes a balloon.
If you update it to shrink the items, you run into some other problems I'll address later.
How long does it take to get something out?
-------------------------------------------
Without the clauses about pulling out the right object, you won't be able to pull the right object out quickly, so you'd have to dump out the entire 12 cubic feet of troll parts to find the 3 silver pieces rattling around the bottom of the bag.
What happens if the bag is ripped?
----------------------------------
Is the item able to be ripped? Magic items, by default, are indestructible by normal means, and without a clause about the bag is open to weird abuse, especially if things don't shrink on their way into the bag. Because you can push the indestructible 12 cubic foot bag that only weighs 5 pounds against a door, or hide behind it.
If it can be ripped. Do the items that leave the bag through the rip remain less dense? And if you add shrinking to address the first question, do they also remain small if they fall through the rip? Or do they suddenly regain their weight and size?
Frame of Reference Challenge
----------------------------
The issues you have with the Bag of Holding can be solved in other ways. Such as not giving it out in tier one play (or at all) or simply forbidding its misuse and abuse. Your item is poorly thought out patch to a problem that isn't about the item, it is about your players -- or at least how you think your players will use the bag.
>
> [C]lauses about bad stuff that happens if you put it into another extradimensional space
>
>
>
If that is a problem at your table don't give them any other extradimensional items if you give them a bag of holding. Spells that create extradimensional effects are higher level spells.
>
> they can also can use it to hide items from divination spells that are limited to the same plane
>
>
>
Then BBEG uses different divination spells, or the BBEG knows who took the items and scry/trace/track the players instead of the item. That isn't about railroading either, it is thinking about what the BBEG would resond to the parties use of the bag to hide the item they want.
The argument that putting the stuff into an extradimensional space is "less complex" than instantly changing the mass (and potentially size) of the item in this plane is weird to me. The extradimensional bag of holding just makes the item go somewhere else, where your bag changes the mass (and potentially volume) of the items inside which if you play with real-world physics can create even more and unexpected abuse than the play-tested and tried and true item from the DMG. But at the end of the day, it is your table, and if you feel a need for the item go for it. | It feels **reasonably balanced**, but feel free to add the fixes suggested by Thomas Markov. Stricter definitions removes the necessity for arbitrary judgements.
However, J. A. Streich makes a valid comment - **where does things go**, without a portal of some sort? As far as I understand your description, you're planning on not making things "go" anywhere, per se, just **lose all mass and volume** while inside the bag. Since that seems a bit weird in the D&D magic paradigm, I propose a fix:
>
> **Sack of Reduction**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold up to 360 pounds, pre-reduction. Anything placed into the sack will, once fully inside, be subject to a Reduce effect, decreasing its size by one category, until removed from the sack or the sack is destroyed. Creatures in the sack can breathe normally. Putting held objects or physically compliant creatures into the sack or taking them out requires an Action. The mouth of the sack is malleable with a maximum circumference of 3 feet, and the depth of the bag is 4 feet.
>
>
>
Now we're **using the existing magical ideas** of D&D, though the effects are significantly less than the Bag of Holding - the sack will grow in size and weight as you fill it, though not commensurate to what you stuff inside. I specified the mouth, and added the limitation that things must fit wholly inside before being Reduced. |
201,308 | I am looking for an alternative to bag of holding that is simpler and provides the weight reduction benefit without all the extra baggage from creating extradimensional spaces.
>
> **Sack of Carrying**
>
> *Wonderous Item, Uncommon*
>
>
> This item appears like a normal, large sack that weighs 5 pounds. It can hold 12 cubic feet or 360 pounds, without changing its total weight. Creatures in the sack can breathe normally. You can put objects or creatures into the sack or take them out with a normal object interaction.
>
>
>
Are there any balance, mechanics or wording issues this item would have?
---
**Background**:
The [bag of holding](https://www.dndbeyond.com/magic-items/4581-bag-of-holding) creates a permanent, extradimensional space and a portal effect to access it, quite the exotic effect for an item that is merely *uncommon*, too exotic for my tastes. It also has lots of additional clauses about bad stuff that happens if you put it into another extradimensional space (or vice versa), which for me makes it [unneccesarily complicated](https://rpg.stackexchange.com/search?q=%22bag%20of%20holding%22%20%5Bdnd-5e%5D).
While characters mostly use it to lug around equipment and loot, they can also can use it to hide items from divination spells that are limited to the same plane, which is an unrelated effect to providing carrying capacity. I am looking for a simpler item to add to the game.
I have no problems with bag of holding *per se*. Its a cool item I love like the next guy. I also have no issue with it being used with all its features, when the characters have one. But for tier one play, I feel a simpler item would be a better fit, and am looking to create one. Think of it like I'd like the option of a +1 sword, rather than just having a flametongue. | 2022/09/09 | ['https://rpg.stackexchange.com/questions/201308', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/75095/'] | Where does the stuff go? How big does the bag get?
--------------------------------------------------
Without the interdimensional space, putting 12 cubic feet of stuff would result in a bag that is 12 cubic feet in size -- because there is nowhere for the things to go. The item as written decreases the weight, but not the size of the item. So, the party looks like they stole Santa's bag.
Let's think about this a bit more. If the bag doesn't shrink items, then it is decreasing mass but not volume, decreasing the density of the items. Thus the bag becomes less dense the more volume you give it, and so if it becomes less dense than water, it can be abused as a flotation device, and if it becomes less dense than air, it becomes a balloon.
If you update it to shrink the items, you run into some other problems I'll address later.
How long does it take to get something out?
-------------------------------------------
Without the clauses about pulling out the right object, you won't be able to pull the right object out quickly, so you'd have to dump out the entire 12 cubic feet of troll parts to find the 3 silver pieces rattling around the bottom of the bag.
What happens if the bag is ripped?
----------------------------------
Is the item able to be ripped? Magic items, by default, are indestructible by normal means, and without a clause about the bag is open to weird abuse, especially if things don't shrink on their way into the bag. Because you can push the indestructible 12 cubic foot bag that only weighs 5 pounds against a door, or hide behind it.
If it can be ripped. Do the items that leave the bag through the rip remain less dense? And if you add shrinking to address the first question, do they also remain small if they fall through the rip? Or do they suddenly regain their weight and size?
Frame of Reference Challenge
----------------------------
The issues you have with the Bag of Holding can be solved in other ways. Such as not giving it out in tier one play (or at all) or simply forbidding its misuse and abuse. Your item is poorly thought out patch to a problem that isn't about the item, it is about your players -- or at least how you think your players will use the bag.
>
> [C]lauses about bad stuff that happens if you put it into another extradimensional space
>
>
>
If that is a problem at your table don't give them any other extradimensional items if you give them a bag of holding. Spells that create extradimensional effects are higher level spells.
>
> they can also can use it to hide items from divination spells that are limited to the same plane
>
>
>
Then BBEG uses different divination spells, or the BBEG knows who took the items and scry/trace/track the players instead of the item. That isn't about railroading either, it is thinking about what the BBEG would resond to the parties use of the bag to hide the item they want.
The argument that putting the stuff into an extradimensional space is "less complex" than instantly changing the mass (and potentially size) of the item in this plane is weird to me. The extradimensional bag of holding just makes the item go somewhere else, where your bag changes the mass (and potentially volume) of the items inside which if you play with real-world physics can create even more and unexpected abuse than the play-tested and tried and true item from the DMG. But at the end of the day, it is your table, and if you feel a need for the item go for it. | Your wording will be confusing to anyone used to D&D's ubiquitous 'bag of holding' and similar items.
-----------------------------------------------------------------------------------------------------
Instead something like this will make it clearer to your players what you are aiming for.
>
> **Sack of Lightness**
>
>
> *Wondrous Item, Uncommon*
>
>
> This item appears as a normal, large sack with a weight of 5 pounds. It can hold an amount of goods typical for a large sack, 12 cubic feet or so. Items placed entirely inside the sack no longer have weight, allowing the wielder to carry the sack without adding the weight of the items inside it to their carrying capacity. Although the weight is not added, the sack if filled with its full allowance of space is still quite large, so an adventurer carrying multiple of these sacks may look quite comical, or run into problems squeezing through tight spaces.
>
>
> Although used for a similar purpose to a bag of holding, the sack of lightness does not make use of extradimensional spaces and retrieving or adding an item to the sack functions as it would with any nonmagical sack of non-lightness.
>
>
>
Wording is a bit colloquial/chatty there, but it should provide a guide. Provided you make it clear that this isn't a sack of holding or carrying or whatever, it's just a sack that makes items inside not weigh anything in the title and spell it out a few times in the text, your players should get the message. If you don't, they might just assume based on similarity of purpose to another, extremely well known item. |
5,474,564 | I've noticed that recently sites began to keep images in one big image.
For example google.com

We see a lot of little images on left side. But really is one image:

How these images are cut and shown? (firebug says that it's just element with width and height, but where X and Y position is pointed and how?)
Thanks for reply | 2011/03/29 | ['https://Stackoverflow.com/questions/5474564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547242/'] | with css background the image is moved to the right position. the other part of the image is not shown, because the element with the image as background is exactly as big as the wanted picture part.
try changing the px values in the css in the background part. you should see the image moving
```
<span style="background-position:-20px -132px" class="micon"></span>
```
here you see the background-position which is used for this image | This technology is called [CSS Sprite](http://css-tricks.com/css-sprites/). To reduce the http connections number needed to load multiple images. Usually this is done by designer. |
5,474,564 | I've noticed that recently sites began to keep images in one big image.
For example google.com

We see a lot of little images on left side. But really is one image:

How these images are cut and shown? (firebug says that it's just element with width and height, but where X and Y position is pointed and how?)
Thanks for reply | 2011/03/29 | ['https://Stackoverflow.com/questions/5474564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547242/'] | with css background the image is moved to the right position. the other part of the image is not shown, because the element with the image as background is exactly as big as the wanted picture part.
try changing the px values in the css in the background part. you should see the image moving
```
<span style="background-position:-20px -132px" class="micon"></span>
```
here you see the background-position which is used for this image | This is called "**CSS Sprites**".
There are a lot of informations on Internet about that. In random order :
* [Smashing Magazine](http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/)
* [CSS Tricks](http://css-tricks.com/css-sprites/)
* [A List Apart](http://www.alistapart.com/articles/sprites)
And many more ... |
19,581,247 | i am fighting with `with clause` two return a result set as well as set a sql variable too.
Or somehow i just want to get two results from the `with clause`.
My sql query is:
```
declare @total as int
;with T as
(
// some sql query
)
select * from T
```
above query returning a set of result, But i also want to set `@total` (number of rows in T).
Is this possible ? Thank you
Here is also a way two do this like :
```
;with T as
(
select count(1), * from table1
)
select * from T
```
But its not a appropriate way to do this, Because it will return the `count` as `column`. | 2013/10/25 | ['https://Stackoverflow.com/questions/19581247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1658099/'] | ```
//try this
- (void)searchBarSearchButtonClicked:(UISearchBar *)sBar
{
[sBar resignFirstResponder];
}
``` | Take three Step in count
1) set delegate for textfield
2) set Delegate for particular textfielf yourtextfielg.delegate=self.
3) Resign that particular textField [txt resignFirstResponder]. |
19,581,247 | i am fighting with `with clause` two return a result set as well as set a sql variable too.
Or somehow i just want to get two results from the `with clause`.
My sql query is:
```
declare @total as int
;with T as
(
// some sql query
)
select * from T
```
above query returning a set of result, But i also want to set `@total` (number of rows in T).
Is this possible ? Thank you
Here is also a way two do this like :
```
;with T as
(
select count(1), * from table1
)
select * from T
```
But its not a appropriate way to do this, Because it will return the `count` as `column`. | 2013/10/25 | ['https://Stackoverflow.com/questions/19581247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1658099/'] | ```
//try this
- (void)searchBarSearchButtonClicked:(UISearchBar *)sBar
{
[sBar resignFirstResponder];
}
``` | **Here is the solution:**
```
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
```
**You need the UI field to resign the first responder status to dismiss the keyboard.**
```
- (void)dismissKeyboard
{
[searchBar resignFirstResponder]; //It might not work
```
**or**
```
[field resignFirstResponder]; //it will surely work
}
``` |
43,490,729 | I am using curl reques to get report of sms but facing some issues. i have also ckecked by encoding url but still same issue.
400 bad request is being shown.
```
$url="http://api.smscountry.com/smscwebservices_bulk_reports.aspx?user=&passwd=&fromdate=19/04/2017 00:00:00&todate=19/04/2017 23:59:59&jobno=60210892"; //callbackURL=http://www.jouple.com/marketing/public/save/sms
$ch = curl_init();
if (!$ch){
die("Couldn't initialize a cURL handle");
}
$ret = curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// curl_setopt ($ch, CURLOPT_POSTFIELDS,
// "User=$user&passwd=$password&sid=$senderid");
// $ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//If you are behind proxy then please uncomment below line and provide your proxy ip with port.
// $ret = curl_setopt($ch, CURLOPT_PROXY, "PROXY IP ADDRESS:PORT");
$curlresponse = curl_exec($ch); // execute
// print_r($ch);die;
if(curl_errno($ch))
echo 'curl error : '. curl_error($ch);
if (empty($ret)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
}
``` | 2017/04/19 | ['https://Stackoverflow.com/questions/43490729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4054369/'] | This happens when you have whitespaces in URL. You have to escape url. Follow the below code
```
<?php
$url="http://api.smscountry.com/smscwebservices_bulk_reports.aspx/"; //callbackURL=http://www.jouple.com/marketing/public/save/sms
$url2= "?user=&passwd=&fromdate=19/04/2017 00:00:00&todate=19/04/2017 23:59:59&jobno=60210892";
$ch = curl_init();
$url = $url . curl_escape($ch, $url2);
if (!$ch){
die("Couldn't initialize a cURL handle");
}
$ret = curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// curl_setopt ($ch, CURLOPT_POSTFIELDS,
// "User=$user&passwd=$password&sid=$senderid");
// $ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//If you are behind proxy then please uncomment below line and provide your proxy ip with port.
// $ret = curl_setopt($ch, CURLOPT_PROXY, "PROXY IP ADDRESS:PORT");
$curlresponse = curl_exec($ch); // execute
// print_r($ch);die;
if(curl_errno($ch))
echo 'curl error : '. curl_error($ch);
if (empty($ret)) {
// some kind of an error happened
die(curl_error($ch));
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
}
```
After this you will face a error invalid content length. Uncomment the line CURLOPT\_POSTFIELDS and pass correct credentials. Definitely it will work. | You can add just urlencode() to your parameters like msg and mobile :
```
$sms = "Dear User, Your OTP for trip is $otp CSPL";
$sms = urlencode($sms);
$mobile = urlencode($mobile);
$url = "yoururl";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$responseJson = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
``` |
208,685 | On field detail page, there are two different buttons called **Set Field-Level Security** and **View Field Accessibility**. What is the exact difference in them. | 2018/02/19 | ['https://salesforce.stackexchange.com/questions/208685', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/24950/'] | From field level security you can define field visibility and read only for each profile
In field accessibility shows if a field is required, editable etc based on field level security and page layout configuration | In short, as @annappa has said, from field level security you can define field visibility and read only for each profile,
while field accessibility show us if a field is required, editable, etc based on field level security and page layout configuration.
Also, I found a link that tells you in detail> [Newbie Q: Is "Field Level Security" the same as "Field Accessibility"?](https://salesforce.stackexchange.com/questions/131965/newbie-q-is-field-level-security-the-same-as-field-accessibility)
Hope this clarifies! |
7,357,909 | I am trying to execute some processes in parallel. and it is my first time doing that, upon trying :
using System.Threading.Tasks;
Tasks will be underlined in red saying :
```
The Type or namespace name "Tasks" does not exist in the namespace System.Threading(are you missing an assembly reference?)
```
how do i resolve that!? | 2011/09/09 | ['https://Stackoverflow.com/questions/7357909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909264/'] | Does your project target .NET 3.5 or lower, perhaps? `System.Threading.Tasks` was introduced in .NET 4 - just using Visual Studio 2010 isn't enough; you need to target the appropriate framework. (Fortunately it *is* in the .NET 4 client profile, which is often a little "gotcha" for some other types.)
Likewise Silverlight hasn't *yet* got the TPL, although IIRC it's coming in Silverlight 5. | Make sure that you are targeting .NET 4.0 in the properties of your project. TPL is not available in previous versions of .NET. |
7,357,909 | I am trying to execute some processes in parallel. and it is my first time doing that, upon trying :
using System.Threading.Tasks;
Tasks will be underlined in red saying :
```
The Type or namespace name "Tasks" does not exist in the namespace System.Threading(are you missing an assembly reference?)
```
how do i resolve that!? | 2011/09/09 | ['https://Stackoverflow.com/questions/7357909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909264/'] | Does your project target .NET 3.5 or lower, perhaps? `System.Threading.Tasks` was introduced in .NET 4 - just using Visual Studio 2010 isn't enough; you need to target the appropriate framework. (Fortunately it *is* in the .NET 4 client profile, which is often a little "gotcha" for some other types.)
Likewise Silverlight hasn't *yet* got the TPL, although IIRC it's coming in Silverlight 5. | You have to change the Target `Framework to 4.0` of your project. |
7,357,909 | I am trying to execute some processes in parallel. and it is my first time doing that, upon trying :
using System.Threading.Tasks;
Tasks will be underlined in red saying :
```
The Type or namespace name "Tasks" does not exist in the namespace System.Threading(are you missing an assembly reference?)
```
how do i resolve that!? | 2011/09/09 | ['https://Stackoverflow.com/questions/7357909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909264/'] | Does your project target .NET 3.5 or lower, perhaps? `System.Threading.Tasks` was introduced in .NET 4 - just using Visual Studio 2010 isn't enough; you need to target the appropriate framework. (Fortunately it *is* in the .NET 4 client profile, which is often a little "gotcha" for some other types.)
Likewise Silverlight hasn't *yet* got the TPL, although IIRC it's coming in Silverlight 5. | Have you tried to add it by right clicking on add reference button in visual Studio? |
7,357,909 | I am trying to execute some processes in parallel. and it is my first time doing that, upon trying :
using System.Threading.Tasks;
Tasks will be underlined in red saying :
```
The Type or namespace name "Tasks" does not exist in the namespace System.Threading(are you missing an assembly reference?)
```
how do i resolve that!? | 2011/09/09 | ['https://Stackoverflow.com/questions/7357909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909264/'] | Make sure that you are targeting .NET 4.0 in the properties of your project. TPL is not available in previous versions of .NET. | You have to change the Target `Framework to 4.0` of your project. |
7,357,909 | I am trying to execute some processes in parallel. and it is my first time doing that, upon trying :
using System.Threading.Tasks;
Tasks will be underlined in red saying :
```
The Type or namespace name "Tasks" does not exist in the namespace System.Threading(are you missing an assembly reference?)
```
how do i resolve that!? | 2011/09/09 | ['https://Stackoverflow.com/questions/7357909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909264/'] | Make sure that you are targeting .NET 4.0 in the properties of your project. TPL is not available in previous versions of .NET. | Have you tried to add it by right clicking on add reference button in visual Studio? |
865,931 | I have a unit file and I want to modify some of the properties. I've been able to extend all the properties using the `/etc/systemd/system/unitname.service.d/` directory but cannot get the `WantedBy` property to be extended.
**Original Unit File (deluged.service)**
```
[Unit]
Description=Deluge Bittorrent Client Daemon
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=media
Group=media
ExecStart=/usr/local/bin/deluged -d -u 0.0.0.0
[Install]
WantedBy=multi-user.target
```
**/etc/systemd/system/deluged.service.d/override.conf**
```
[Unit]
BindTo=sys-subsystem-net-devices-tun0.device
After=sys-subsystem-net-devices-tun0.device
[Service]
ExecStart=
ExecStart=/usr/local/bin/deluged -d -i 10.10.10.1 -u 0.0.0.0
[Install]
WantedBy=
WantedBy=sys-subsystem-net-devices-tun0.device
```
Everything appears to work correctly except for `WantedBy` when I run `systemctl enable deluged` it still created the symlink in `multi-user` and no link is created in the new location.
I've searched for documentation on extending/overriding and I haven't seen anything talking about `WantedBy` so I have no idea if it's even possible to extend it. Am I doing something wrong or is it just not possible? | 2017/07/30 | ['https://serverfault.com/questions/865931', 'https://serverfault.com', 'https://serverfault.com/users/239459/'] | A lot of things are going wrong here. Firstly, your DNS servers don't seem to be set up right:
```
[me@risby ~]$ dig soa hostthrone.com @169.239.180.241
[...]
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1680
;; QUESTION SECTION:
;hostthrone.com. IN SOA
[...]
[me@risby ~]$ dig soa hostthrone.com @169.239.181.204
[...]
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1680
;; QUESTION SECTION:
;hostthrone.com. IN SOA
```
But your single biggest problem is that you haven't set the domain up with your registrar properly:
```
[me@risby ~]$ whois hostthrone.com
[Querying whois.verisign-grs.com]
[Redirected to whois.namecheap.com]
[Querying whois.namecheap.com]
[whois.namecheap.com]
Domain name: hostthrone.com
[...]
Name Server: dns1.registrar-servers.com
Name Server: dns2.registrar-servers.com
```
Whilst it is perfectly legitimate to have a domain use nameservers inside itself - that's what [glue records](https://en.wikipedia.org/wiki/Glue_records) were invented for - each registrar has a slightly different procedure for setting this up, and you have not done yours. That means your registrar is not telling the internet that your servers are authoritative for your domain, so even if they were working, the domain would not be served properly.
Thank you for not obscuring your domain name and IP addresses; that makes the question much easier to answer. | After following MadHatter answer I solved the whois hostthrone.com by using these namecheap settings :
[](https://i.stack.imgur.com/BvOas.png)
My DNS server would only work for period of time after setting up hostthrone.com zone in PowerDNS
[](https://i.stack.imgur.com/QhbTp.png)
After a lot of googling the real problem was that that Ubuntu was installing an alpha version of PowerDNS
Here is the solution :
```
sudo nano /etc/apt/sources.list.d/pdns.list
deb [arch=amd64] http://repo.powerdns.com/ubuntu xenial-auth-40 main
sudo nano /etc/apt/preferences.d/pdns
Package: pdns-*
Pin: origin repo.powerdns.com
Pin-Priority: 600
curl https://repo.powerdns.com/FD380FBB-pub.asc | sudo apt-key add - && sudo apt-get update && sudo apt-get install pdns-server
```
If you have an error of this nature RestrictAddressFamilies=AF\_UNIX AF\_INET AF\_INET6 then edit /lib/systemd/system/pdns.service
```
#RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
```
Install pdns-backend-mysql
```
sudo apt-get install pdns-backend-mysql
service pdns restart
netstat -tap | grep pdns
tcp 0 0 *:domain *:* LISTEN 1145/pdns_server-in
tcp6 0 0 [::]:domain [::]:* LISTEN 1145/pdns_server-in
```
dig hostthrone.com SOA @169.239.181.204 returns an answer still after a few days |
70,563,335 | ```
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("abcd@gmail.com");
message.setTo(recipients);
message.setSubject("SERVICE DOWN");
message.setText(".............");
mailSender.send(message);
```
When using this, username is showing as display name. I want custom name like "SUPPORT"? | 2022/01/03 | ['https://Stackoverflow.com/questions/70563335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11581348/'] | `SimpleMailMessage` does not support that function. You have to use another class that does. A good alternative would be [`MimeMessageHelper`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/javamail/MimeMessageHelper.html). It is pretty straightforward to use and supports more functionalities.
Here is a simple example
First of all, a `MailSender` object is required. You could create one or create a bean out of it:
```java
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);
mailSender.setUsername("my.gmail@gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
```
Then send the message:
```java
MimeMessagePreparator mailMessage = mimeMessage -> {
MimeMessageHelper message = new MimeMessageHelper(
mimeMessage, true, StandardCharsets.UTF_8);
try {
message.setFrom(senderEmail, senderName); // Here comes your name
message.addTo(recipientEmail);
message.setReplyTo(senderEmail);
message.setSubject(subject);
message.setText(fallbackTextContent, htmlContent);
} catch (Exception e) {
throw new MailDeliveryServiceException(recipientEmail, e);
}
};
mailSender.send(mailMessage);
``` | As you can read on the [API docs from Spring](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/SimpleMailMessage.html), you should use a different class:
"Consider JavaMailSender and JavaMail MimeMessages for creating more sophisticated messages, for example messages with attachments, special character encodings, or **personal names that accompany mail addresses**." |
18,236,639 | I am a noob at ajax, but I think my problem is fairly simple. After I submit my form, I would like to have the server echo back to me. Here is my current code which is not working. I'm fairly certain that the problem is with my ajax, because I know that my values are being placed in dataString.
**HTML**
```
<form method="POST" onSubmit="new_user(this);" >
<input type="submit" value="signed" name="astatus" />
<input type="hidden" value="FaKEIdkEy" name="mark_attend" />
</form>
```
**Javascript**
```
function new_user(form){
var url = "attendance.php";
var dataString = "status="+form.astatus.value;
dataString = dataString+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
alert(data);
}
});
}
```
**php** (attendance.php)
```
if(!empty($_POST))
{
echo "response";
}
```
Any Ideas on how to fix? | 2013/08/14 | ['https://Stackoverflow.com/questions/18236639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2406939/'] | You should add a `return false;` at the end of the function to prevent the form from submitting.
```
function new_user(form) {
var url = "attendance.php";
var dataString = "status="+form.astatus.value+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
}
``` | ```
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
console.log(data);
}
});
```
Does the console show "response"? |
18,236,639 | I am a noob at ajax, but I think my problem is fairly simple. After I submit my form, I would like to have the server echo back to me. Here is my current code which is not working. I'm fairly certain that the problem is with my ajax, because I know that my values are being placed in dataString.
**HTML**
```
<form method="POST" onSubmit="new_user(this);" >
<input type="submit" value="signed" name="astatus" />
<input type="hidden" value="FaKEIdkEy" name="mark_attend" />
</form>
```
**Javascript**
```
function new_user(form){
var url = "attendance.php";
var dataString = "status="+form.astatus.value;
dataString = dataString+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
alert(data);
}
});
}
```
**php** (attendance.php)
```
if(!empty($_POST))
{
echo "response";
}
```
Any Ideas on how to fix? | 2013/08/14 | ['https://Stackoverflow.com/questions/18236639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2406939/'] | You should add a `return false;` at the end of the function to prevent the form from submitting.
```
function new_user(form) {
var url = "attendance.php";
var dataString = "status="+form.astatus.value+"&id="+form.mark_attend.value;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
}
``` | ```
You are calling ajax at on submit , so when ajax run after that page is reload so data is vanished.
<form method="POST" >
<input type="button" value="signed" name="astatus" onclick="new_user()" />
<input type="hidden" value="FaKEIdkEy" name="mark_attend" id="mark_attend"/>
</form>
and get the value with jquery
var fakeidkey=$_('#mark_attend').val();
and then concat it with your varaible .
``` |
13,237,478 | I'm using markdown and I've got some input such as `**test**` which makes the word test appear in bold **test** and I've converted it with html like so"
```
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
```
And this alerts `<b>test</b>` the issue is I need to take this value, namely `<b>test</b>` and access this via server side code (asp.net). I tried assigning it to a variable like so:
```
document.getElementById("Label1").value = html;
```
But it doesn't seem to work, when I go to the code behind it shows `Label1` as being empty.
Is this possible?
Edit
----
I tried to change it to a hidden field same issue:
```
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
var h = document.getElementById('<%= h1.ClientID %>');
alert(h.value);
})();
</script>
```
The issue I have is I have an asp.net server side button that when clicked I try to do this:
`Label1.Text = h1.Value;`
That is to store the value from the hidden field to a label but this doesnt work. When I put a break point in it shows `h1` is empty `""`....So I'm not sure what event or how to do this so that when I make changes to my textarea `wmd_input` that i should be able to see these changes in my server side code...
Here's my entire asp.net form:
```
<html>
<head>
<title>PageDown Demo Page</title>
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<script type="text/javascript" src="js/Markdown.Converter.js"></script>
<script type="text/javascript" src="js/Markdown.Sanitizer.js"></script>
<script type="text/javascript" src="js/Markdown.Editor.js"></script>
</head>
<body>
<form id="myForm" runat="server">
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea cols="5" rows="5" id="wmd_input" class="wmd-input" runat="server"></textarea>
<div id="wmd_preview" class="wmd-panel wmd-preview" runat="server"></div>
</div>
<asp:button id="Button1" runat="server" Text="Set" onclick="Button1_Click"></asp:button>
<asp:button id="Button2" runat="server" Text="Get" onclick="Button2_Click"></asp:button><asp:label id="Label1" runat="server">Label</asp:label>
<asp:HiddenField ID="h1" runat="server" EnableViewState="true" />
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
alert(document.getElementById('<%= h1.ClientID %>').value);
})();
</script>
</form>
</body>
</html>
``` | 2012/11/05 | ['https://Stackoverflow.com/questions/13237478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255446/'] | The `asp:Label` tag isn't an input control, so it won't get posted back to the server. I'd suggest using `asp:HiddenField` or `asp:TextBox` instead. (And Adil's point is crucial too, you need to make sure the client ID is actually what you think it is.)
---
Here's a test that works for me. On the first page load, the label shows "initial value", but the alert shows "updated". After postback, the label also shows "updated".
**Edit** Added the client-side update logic inside a client-side event handler.
```
<%@ Page Title="Test" Language="C#" AutoEventWireup="true" %>
<script runat="server">
void Page_Load()
{
l1.Text = h1.Value;
}
</script>
<html>
<body>
<form runat="server">
<asp:HiddenField runat="server" Value="initial value" ID="h1" />
<asp:Label runat="server" ID="l1" />
<asp:Button runat="server" Text="do postback" />
</form>
<script>
document.getElementById('<%= Button1.ClientID %>').onclick = function () {
document.getElementById('<%= h1.ClientID %>').value = 'updated';
alert(document.getElementById('<%= h1.ClientID %>').value);
};
</script>
</body>
</html>
``` | Labels don't post. You will have to use an `input` or `textarea` element ([`<asp:TextBox>`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx)). If you don't want the user to see the markup source, you can also use an [`<asp:HiddenField>`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx). |
13,237,478 | I'm using markdown and I've got some input such as `**test**` which makes the word test appear in bold **test** and I've converted it with html like so"
```
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
```
And this alerts `<b>test</b>` the issue is I need to take this value, namely `<b>test</b>` and access this via server side code (asp.net). I tried assigning it to a variable like so:
```
document.getElementById("Label1").value = html;
```
But it doesn't seem to work, when I go to the code behind it shows `Label1` as being empty.
Is this possible?
Edit
----
I tried to change it to a hidden field same issue:
```
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
var h = document.getElementById('<%= h1.ClientID %>');
alert(h.value);
})();
</script>
```
The issue I have is I have an asp.net server side button that when clicked I try to do this:
`Label1.Text = h1.Value;`
That is to store the value from the hidden field to a label but this doesnt work. When I put a break point in it shows `h1` is empty `""`....So I'm not sure what event or how to do this so that when I make changes to my textarea `wmd_input` that i should be able to see these changes in my server side code...
Here's my entire asp.net form:
```
<html>
<head>
<title>PageDown Demo Page</title>
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<script type="text/javascript" src="js/Markdown.Converter.js"></script>
<script type="text/javascript" src="js/Markdown.Sanitizer.js"></script>
<script type="text/javascript" src="js/Markdown.Editor.js"></script>
</head>
<body>
<form id="myForm" runat="server">
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea cols="5" rows="5" id="wmd_input" class="wmd-input" runat="server"></textarea>
<div id="wmd_preview" class="wmd-panel wmd-preview" runat="server"></div>
</div>
<asp:button id="Button1" runat="server" Text="Set" onclick="Button1_Click"></asp:button>
<asp:button id="Button2" runat="server" Text="Get" onclick="Button2_Click"></asp:button><asp:label id="Label1" runat="server">Label</asp:label>
<asp:HiddenField ID="h1" runat="server" EnableViewState="true" />
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
alert(document.getElementById('<%= h1.ClientID %>').value);
})();
</script>
</form>
</body>
</html>
``` | 2012/11/05 | ['https://Stackoverflow.com/questions/13237478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255446/'] | Labels don't post. You will have to use an `input` or `textarea` element ([`<asp:TextBox>`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx)). If you don't want the user to see the markup source, you can also use an [`<asp:HiddenField>`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx). | you should be able to do what you want to do by using knockoutjs <http://knockoutjs.com/examples/helloWorld.html> You can use element binding. |
13,237,478 | I'm using markdown and I've got some input such as `**test**` which makes the word test appear in bold **test** and I've converted it with html like so"
```
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
```
And this alerts `<b>test</b>` the issue is I need to take this value, namely `<b>test</b>` and access this via server side code (asp.net). I tried assigning it to a variable like so:
```
document.getElementById("Label1").value = html;
```
But it doesn't seem to work, when I go to the code behind it shows `Label1` as being empty.
Is this possible?
Edit
----
I tried to change it to a hidden field same issue:
```
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
var h = document.getElementById('<%= h1.ClientID %>');
alert(h.value);
})();
</script>
```
The issue I have is I have an asp.net server side button that when clicked I try to do this:
`Label1.Text = h1.Value;`
That is to store the value from the hidden field to a label but this doesnt work. When I put a break point in it shows `h1` is empty `""`....So I'm not sure what event or how to do this so that when I make changes to my textarea `wmd_input` that i should be able to see these changes in my server side code...
Here's my entire asp.net form:
```
<html>
<head>
<title>PageDown Demo Page</title>
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<script type="text/javascript" src="js/Markdown.Converter.js"></script>
<script type="text/javascript" src="js/Markdown.Sanitizer.js"></script>
<script type="text/javascript" src="js/Markdown.Editor.js"></script>
</head>
<body>
<form id="myForm" runat="server">
<div class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea cols="5" rows="5" id="wmd_input" class="wmd-input" runat="server"></textarea>
<div id="wmd_preview" class="wmd-panel wmd-preview" runat="server"></div>
</div>
<asp:button id="Button1" runat="server" Text="Set" onclick="Button1_Click"></asp:button>
<asp:button id="Button2" runat="server" Text="Get" onclick="Button2_Click"></asp:button><asp:label id="Label1" runat="server">Label</asp:label>
<asp:HiddenField ID="h1" runat="server" EnableViewState="true" />
<script type="text/javascript">
(function () {
var converter1 = Markdown.getSanitizingConverter();
var editor1 = new Markdown.Editor(converter1);
editor1.run();
var d = document.getElementById("wmd_input");
var html = converter1.makeHtml(d.value);
alert(html);
document.getElementById('<%= h1.ClientID %>').value = html;
alert(document.getElementById('<%= h1.ClientID %>').value);
})();
</script>
</form>
</body>
</html>
``` | 2012/11/05 | ['https://Stackoverflow.com/questions/13237478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255446/'] | The `asp:Label` tag isn't an input control, so it won't get posted back to the server. I'd suggest using `asp:HiddenField` or `asp:TextBox` instead. (And Adil's point is crucial too, you need to make sure the client ID is actually what you think it is.)
---
Here's a test that works for me. On the first page load, the label shows "initial value", but the alert shows "updated". After postback, the label also shows "updated".
**Edit** Added the client-side update logic inside a client-side event handler.
```
<%@ Page Title="Test" Language="C#" AutoEventWireup="true" %>
<script runat="server">
void Page_Load()
{
l1.Text = h1.Value;
}
</script>
<html>
<body>
<form runat="server">
<asp:HiddenField runat="server" Value="initial value" ID="h1" />
<asp:Label runat="server" ID="l1" />
<asp:Button runat="server" Text="do postback" />
</form>
<script>
document.getElementById('<%= Button1.ClientID %>').onclick = function () {
document.getElementById('<%= h1.ClientID %>').value = 'updated';
alert(document.getElementById('<%= h1.ClientID %>').value);
};
</script>
</body>
</html>
``` | you should be able to do what you want to do by using knockoutjs <http://knockoutjs.com/examples/helloWorld.html> You can use element binding. |
1,541,537 | What is the Galois group of $(x^2-1)(x^2-2)...(x^2-p+1)$ over $\mathbb Z\_p$ for an odd prime, $p$? There are exactly $\frac{p-1}{2}$ squares in $\mathbb Z\_p$ but my guess is the group is $\mathbb Z\_2$. | 2015/11/22 | ['https://math.stackexchange.com/questions/1541537', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/292519/'] | By the uniqueness of finite fields of a given degree, there is one and **only** one field of order $p^2$. Since not all elements of $\Bbb F\_p$ are squares, you know that if $a$ is a non-square then
>
> $$\Bbb F\_p[\sqrt{a}]=\Bbb F\_p[x]/(x^2-a)=\Bbb F\_{p^2}$$
>
>
>
is an extension of degree $2$. But then since another non-square $b$ would also generate an extension $\Bbb F\_p[b]$ of degree $2$, it must be that these two are **the same field**, i.e. $\Bbb F\_p[\sqrt{b}]=\Bbb F\_{p^2}$ as well. So the splitting field for that polynomial is $\Bbb F\_{p^2}$ since that field has all the square roots of all elements of $\Bbb F\_p$ in it. The Galois group of this extension has order $2$, hence must be $\Bbb Z/2\Bbb Z$, as you surmise. | Also one can use the fact that $\mathbb{F}\_{p^2}/\mathbb{F}\_p$ is Galois, in other words is normal, so one can write $\prod (x^2-i)$ actually splits in $\mathbb{F}\_{p^2}$. So, ans is $\mathbb{Z}\_2$ |
62,255,365 | I am new to ELF binary protection.
I want to strip section header table to avoid debugging.
I try to find section header table offset on disk by run readelf -h, and try to nop them, but they are all 0.
How can I strip section header table?
Thanks in advance. | 2020/06/08 | ['https://Stackoverflow.com/questions/62255365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12157762/'] | First of all you can check which sections are present in your elf with `readelf --section-headers`. You should see something like this:
```
$ readelf --section-headers <your-file>
[ #] Name Type Address Offset
Size Size.Ent Flags - - Alignment
[ 0] NULL 0000000000000000 00000000
0000000000000000 0000000000000000 0 0 0
[ 1] .data PROGBITS 00000000006000b0 000000b0
000000000000003b 0000000000000000 WA 0 0 1
[ 2] .text PROGBITS 0000000000a000f0 000000f0
00000000000003e9 0000000000000000 AX 0 0 1
[ 3] .shstrtab STRTAB 0000000000000000 000004d9
0000000000000027 0000000000000000 0 0 1
[ 4] .symtab SYMTAB 0000000000000000 00000680
0000000000000438 0000000000000018 5 41 8
[ 5] .strtab STRTAB 0000000000000000 00000ab8
0000000000000258 0000000000000000 0 0 1
```
And you should be aware that most of sections are added by linker since the only real parts you need in your binary are `.text` and `.data`. Most of other information can be omitted if you do linkage manually.
If you are using classic `ld` linker, i would recommend trying options `--strip-all` and `--strip-debug`. As name suggests, they remove debug-info and other symbolic information from binary - [here](https://linux.die.net/man/1/ld) you can see the docs.
```
$ readelf --section-headers <your-file>
[ #] Name Type Address Offset
Size Size.Ent Flags - - Alignment
[ 0] NULL 0000000000000000 00000000
0000000000000000 0000000000000000 0 0 0
[ 1] .data PROGBITS 00000000006000b0 000000b0
000000000000003b 0000000000000000 WA 0 0 1
[ 2] .text PROGBITS 0000000000a000f0 000000f0
00000000000003e9 0000000000000000 AX 0 0 1
[ 3] .shstrtab STRTAB 0000000000000000 000004d9
0000000000000017 0000000000000000 0 0 1
```
But by now you should probably have only 3 sections and since most of the data is already omitted, you can stop at that point - now your `.shstrtab` only contains names of text and data sections - it's not really a secret it does :)
And now it really depends on how far you are ready to go.
If you would like to proceed, i would suggest trying another tool called `strip` (from binutils) which you can use like this: `strip --remove-section=shstrtab <your-file>` - it basically removes the undesired section but it's not that easy to get rid of `.shstrtab` as i remember using it.
You can even try removing it by yourself - since you know exact offset of section (and it's probably at the very end of file), you can just place zeroes over it aka "renaming" sections to null :)
And according to ELF specs shstrtab is not required for execution so you should be ok even if you manually remove it from file (removing those bytes) - just keep other pointers,offsets,etc valid
---
In my case removing debug info was ok so i didn't go that far but you can - I would just wish you good luck :) | You can download the Upx packer. Then, when you will run `objdump -fs` you'll have something link this :
```
ransom: file format elf64-x86-64
architecture: i386:x86-64, flags 0x00000140:
DYNAMIC, D_PAGED
start address 0x0000000000003190
```
With nothing else. |
17,797,602 | I just downloaded the play framework from their site and am working through [this tutorial](http://www.playframework.com/documentation/2.1.x/JavaTodoList).
I've noticed the framework creates the folders app/controllers and app/views, but not a models folder. I created it manually and added Task.java to it. When I get to the section entitled "Rendering the first page" and open `localhost:9000/tasks` I get a compilation error that says `package play.models does not exist`. Here is what my Task.java looks like:
```
package models;
import java.util.*;
public class Task {
public Long id;
@Required
public String label;
public static List<Task> all() {
return new ArrayList<Task>();
}
public static void create(Task task) {
}
public static void delete(Long id) {
}
}
```
Here is application.java, the file generating the compilation error:
```
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
import play.data.*;
import play.models.*; // COMPILATION ERROR: "package play.models does not exist"!
public class Application extends Controller {
static Form<Task> taskForm = Form.form(Task.class);
public static Result index() {
//return ok(index.render("Your new application is ready."));
return redirect(routes.Application.tasks());
}
public static Result tasks() {
return ok(views.html.index.render(Task.all(), taskForm));
}
public static Result newTask() {
return TODO;
}
public static Result deleteTask(Long id) {
return TODO;
}
}
``` | 2013/07/22 | ['https://Stackoverflow.com/questions/17797602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1040923/'] | There is no difference between `Winsock2.h` and `winsock2.h`. Filenames are case-insensitive on typical Windows filesystems. The `ws2_32.lib` file is for Winsock 2, while `wsock32.lib` is for the obsolete, older version. | As shown here: <https://technet.microsoft.com/en-us/library/cc958787.aspx>, wsock32.dll and wsock.dll are the backwards-compatiblity shells for w2\_32.dll
You can use wsock32.dll for compatibility with Win95, or wsock.dll for compatibility with win3.11 :) But normally they are used by Win95 and Win3.11 programs for compatibility with win2K+
wsock32.lib and w2\_32.lib contain a list of the exported functions and data elements from the dynamic link libraries.
Note: some of the differences between wsock32 and ws\_32 may be unexpected. For example wsock32 will run winsock version 2.2 API -- but to get version 2.0 you need w2\_32. |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | You never seem to increment your `x` variable. It always has the value `0`... | First, jquery use another format for CSS. It's `backgroundPosition` instead of `background-position`.
Second point, instead of call a timeout every 10sec, call .animate() function. Something like:
```
setInterval(function() {
$('.background').animate({backgroundPosition: imageWidth + ' 0'}, 1000);
}, 1000);
```
Third: You never increment `x`.. Do a x++ on your SetTimeout. |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | May I suggest, in the end of year 2015, another way, using CSS only.
```
@keyframes animatedBackground {
from { background-position: 0 0; }
to { background-position: 100% 0; }
}
#animate-area {
width: 560px;
height: 400px;
background-image: url(bg-clouds.png);
background-position: 0px 0px;
background-repeat: repeat-x;
animation: animatedBackground 40s linear infinite;
}
```
Src: <https://davidwalsh.name/demo/background-animation-css.php> | First, jquery use another format for CSS. It's `backgroundPosition` instead of `background-position`.
Second point, instead of call a timeout every 10sec, call .animate() function. Something like:
```
setInterval(function() {
$('.background').animate({backgroundPosition: imageWidth + ' 0'}, 1000);
}, 1000);
```
Third: You never increment `x`.. Do a x++ on your SetTimeout. |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | I've rewritten your jQuery script into plain vanilla javascript and it seems to work fine:
```js
function slideBackground() {
var background = document.getElementsByClassName('background')[0];
var x = 0;
setInterval(function(){
background.style.backgroundPosition = x + 'px 0';
x++;
}, 10);
}
window.addEventListener('load',slideBackground,false);
```
```css
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('http://bit.ly/1NCb5xC');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
```html
<div class="background">
</div>
``` | First, jquery use another format for CSS. It's `backgroundPosition` instead of `background-position`.
Second point, instead of call a timeout every 10sec, call .animate() function. Something like:
```
setInterval(function() {
$('.background').animate({backgroundPosition: imageWidth + ' 0'}, 1000);
}, 1000);
```
Third: You never increment `x`.. Do a x++ on your SetTimeout. |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | The more jQuery'ish way of doing it, would be to write a plugin that animates the background
```
$.fn.animateBG = function(x, y, speed, callback) {
var pos = this.css('background-position').split(' ');
this.x = pos[0] ? +pos[0].replace(/\D/g,'') : 0,
this.y = pos[1] ? +pos[1].replace(/\D/g,'') : 0,
$.Animation( this, {
x: x,
y: y
}, {
duration: speed
}).progress(function(e) {
this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
}).done(callback);
return this;
};
```
And then just use it in a recursive function for infinite animation
```
(function recursive() {
$('.background').animateBG(100, 0, 1000, function() {
this.animateBG(0, 0, 1000, recursive);
});
}());
```
[**FIDDLE**](https://jsfiddle.net/adeneo/dzaxsg6f/1/) | First, jquery use another format for CSS. It's `backgroundPosition` instead of `background-position`.
Second point, instead of call a timeout every 10sec, call .animate() function. Something like:
```
setInterval(function() {
$('.background').animate({backgroundPosition: imageWidth + ' 0'}, 1000);
}, 1000);
```
Third: You never increment `x`.. Do a x++ on your SetTimeout. |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | May I suggest, in the end of year 2015, another way, using CSS only.
```
@keyframes animatedBackground {
from { background-position: 0 0; }
to { background-position: 100% 0; }
}
#animate-area {
width: 560px;
height: 400px;
background-image: url(bg-clouds.png);
background-position: 0px 0px;
background-repeat: repeat-x;
animation: animatedBackground 40s linear infinite;
}
```
Src: <https://davidwalsh.name/demo/background-animation-css.php> | You never seem to increment your `x` variable. It always has the value `0`... |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | I've rewritten your jQuery script into plain vanilla javascript and it seems to work fine:
```js
function slideBackground() {
var background = document.getElementsByClassName('background')[0];
var x = 0;
setInterval(function(){
background.style.backgroundPosition = x + 'px 0';
x++;
}, 10);
}
window.addEventListener('load',slideBackground,false);
```
```css
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('http://bit.ly/1NCb5xC');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
```html
<div class="background">
</div>
``` | You never seem to increment your `x` variable. It always has the value `0`... |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | May I suggest, in the end of year 2015, another way, using CSS only.
```
@keyframes animatedBackground {
from { background-position: 0 0; }
to { background-position: 100% 0; }
}
#animate-area {
width: 560px;
height: 400px;
background-image: url(bg-clouds.png);
background-position: 0px 0px;
background-repeat: repeat-x;
animation: animatedBackground 40s linear infinite;
}
```
Src: <https://davidwalsh.name/demo/background-animation-css.php> | I've rewritten your jQuery script into plain vanilla javascript and it seems to work fine:
```js
function slideBackground() {
var background = document.getElementsByClassName('background')[0];
var x = 0;
setInterval(function(){
background.style.backgroundPosition = x + 'px 0';
x++;
}, 10);
}
window.addEventListener('load',slideBackground,false);
```
```css
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('http://bit.ly/1NCb5xC');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
```html
<div class="background">
</div>
``` |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | May I suggest, in the end of year 2015, another way, using CSS only.
```
@keyframes animatedBackground {
from { background-position: 0 0; }
to { background-position: 100% 0; }
}
#animate-area {
width: 560px;
height: 400px;
background-image: url(bg-clouds.png);
background-position: 0px 0px;
background-repeat: repeat-x;
animation: animatedBackground 40s linear infinite;
}
```
Src: <https://davidwalsh.name/demo/background-animation-css.php> | The more jQuery'ish way of doing it, would be to write a plugin that animates the background
```
$.fn.animateBG = function(x, y, speed, callback) {
var pos = this.css('background-position').split(' ');
this.x = pos[0] ? +pos[0].replace(/\D/g,'') : 0,
this.y = pos[1] ? +pos[1].replace(/\D/g,'') : 0,
$.Animation( this, {
x: x,
y: y
}, {
duration: speed
}).progress(function(e) {
this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
}).done(callback);
return this;
};
```
And then just use it in a recursive function for infinite animation
```
(function recursive() {
$('.background').animateBG(100, 0, 1000, function() {
this.animateBG(0, 0, 1000, recursive);
});
}());
```
[**FIDDLE**](https://jsfiddle.net/adeneo/dzaxsg6f/1/) |
34,364,330 | Here's the css I have for a div located in my `body` tag :
```
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('Queens-University.jpg');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
I am trying to move the background image of this div move from left to right in a continuous manner (infinite).
I am trying to do this using jQuery but nothing is happening, here is my code:
```
$(window).load(function() {
var image = $('.background');
var x=0;
setInterval(function(){
image.css('background-position', x + 'px 0');
x++;
}, 10);
});
```
How can I use the jQuery to move the background-image? What is wrong with my function? | 2015/12/18 | ['https://Stackoverflow.com/questions/34364330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333347/'] | I've rewritten your jQuery script into plain vanilla javascript and it seems to work fine:
```js
function slideBackground() {
var background = document.getElementsByClassName('background')[0];
var x = 0;
setInterval(function(){
background.style.backgroundPosition = x + 'px 0';
x++;
}, 10);
}
window.addEventListener('load',slideBackground,false);
```
```css
.background {
top: 0;
left: 0;
right: 0;
z-index: 1;
position: absolute;
display: block;
background: url('http://bit.ly/1NCb5xC');
background-repeat: no-repeat;
background-size: 100px 150px;
width: 100%;
height: 100%;
-webkit-filter: blur(3px);
-moz-filter: blur(2px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(3px);
}
```
```html
<div class="background">
</div>
``` | The more jQuery'ish way of doing it, would be to write a plugin that animates the background
```
$.fn.animateBG = function(x, y, speed, callback) {
var pos = this.css('background-position').split(' ');
this.x = pos[0] ? +pos[0].replace(/\D/g,'') : 0,
this.y = pos[1] ? +pos[1].replace(/\D/g,'') : 0,
$.Animation( this, {
x: x,
y: y
}, {
duration: speed
}).progress(function(e) {
this.css('background-position', e.tweens[0].now+'px '+e.tweens[1].now+'px');
}).done(callback);
return this;
};
```
And then just use it in a recursive function for infinite animation
```
(function recursive() {
$('.background').animateBG(100, 0, 1000, function() {
this.animateBG(0, 0, 1000, recursive);
});
}());
```
[**FIDDLE**](https://jsfiddle.net/adeneo/dzaxsg6f/1/) |
4,329,478 | How can I change the color or the transparency of the popup's overlay? I want to have another color and alpha 1. | 2010/12/01 | ['https://Stackoverflow.com/questions/4329478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69654/'] | <http://mprami.wordpress.com/2008/04/22/alert_popup_modal_transparancy_color_blur_changes/>
In flex ‘’ tag has mainly four attributes related to modal properties of pop-ups.
* modalTransparency
* modalTransparencyBlur
* modalTransparencyColor
* modalTransparencyDuration
In spark it looks like these were renamed slightly:
* modal-transparency
* modal-transparency-color
* modal-transparency-duration
* modal-transparency-blur (guessing on this one) | To extend on artjumble's answer, if you're using a css file, you can also declare it like that in the css file:
```
global {
modalTransparencyBlur: 0;
modalTransparency: 0.3;
modalTransparencyColor: black;
modalTransparencyDuration: 500;
}
``` |
51,989,213 | I'm newbie in MVVM . I have two xaml pages. the second one cannot be accessed ( Locked ) unless the button from the first page (Introduction page) has been clicked. How can I do that?
The lock page has this code.
```
<Frame Grid.Row="0" Grid.Column="1" BackgroundColor="LightGray" IsVisible="{Binding LockPage}">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_Lock" />
</Frame.GestureRecognizers>
<Label Text="Locked"/>
</Frame>
```
The Introduction page has this code.
```
<StackLayout>
<Label Text="This is only a simple Introduction Text."/>
<Label Text=""/>
<Button Text="Lets Go!!" Command="{Binding UnlockPageCommand}" Clicked="Tap_Next"/>
</StackLayout>
```
This is the the class LockModule.cs
```
public class LockModule : INotifyPropertyChanged
{
public LockModule()
{
UnlockPageCommand = new Command(UnlockPage);
}
bool lockPage = true;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string lockpage)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(lockpage));
}
public bool LockPage
{
get { return lockPage; }
set
{
lockPage = value;
OnPropertyChanged(nameof(LockPage));
}
}
public Command UnlockPageCommand { get; }
void UnlockPage()
{
if (lockPage == true)
{
lockPage = false;
}
else
{
lockPage = true;
}
OnPropertyChanged(nameof(LockPage));
}
}
```
and it's not working...... | 2018/08/23 | ['https://Stackoverflow.com/questions/51989213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10161534/'] | There are two files needed to be modified about port 8081:
1.react-native/local-cli/server/server.js - default
2.react-native/React/React.xcodeproj/project.pbxproj - replace all the 8081 ports with your desired ports in above two files
Your port will be changed. | After migrating the React Native CLI configs into `@react-native-community/cli` changing the default PORT for metro bundler became very easier, for changing the default PORT just export an environment variable by the following command inside you project path:
```
export RCT_METRO_PORT=8590
```
Also, find the `RCTDefines.h` files inside your `ios/Pods` folder, there are two of them and inside both of them change the value `8081` to `8590`.
For a test run the `echo $RCT_METRO_PORT` and if you see the new PORT `8590`, it is changed now and easily run your project with default commands.
***NOTE***: For using React Native Debugger for development just press `⌘`+`t` and then change the port value `8081` to `8590`. |
51,989,213 | I'm newbie in MVVM . I have two xaml pages. the second one cannot be accessed ( Locked ) unless the button from the first page (Introduction page) has been clicked. How can I do that?
The lock page has this code.
```
<Frame Grid.Row="0" Grid.Column="1" BackgroundColor="LightGray" IsVisible="{Binding LockPage}">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_Lock" />
</Frame.GestureRecognizers>
<Label Text="Locked"/>
</Frame>
```
The Introduction page has this code.
```
<StackLayout>
<Label Text="This is only a simple Introduction Text."/>
<Label Text=""/>
<Button Text="Lets Go!!" Command="{Binding UnlockPageCommand}" Clicked="Tap_Next"/>
</StackLayout>
```
This is the the class LockModule.cs
```
public class LockModule : INotifyPropertyChanged
{
public LockModule()
{
UnlockPageCommand = new Command(UnlockPage);
}
bool lockPage = true;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string lockpage)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(lockpage));
}
public bool LockPage
{
get { return lockPage; }
set
{
lockPage = value;
OnPropertyChanged(nameof(LockPage));
}
}
public Command UnlockPageCommand { get; }
void UnlockPage()
{
if (lockPage == true)
{
lockPage = false;
}
else
{
lockPage = true;
}
OnPropertyChanged(nameof(LockPage));
}
}
```
and it's not working...... | 2018/08/23 | ['https://Stackoverflow.com/questions/51989213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10161534/'] | There are two files needed to be modified about port 8081:
1.react-native/local-cli/server/server.js - default
2.react-native/React/React.xcodeproj/project.pbxproj - replace all the 8081 ports with your desired ports in above two files
Your port will be changed. | You need to overwrite the `RCT_METRO_PORT` macro variable to ensure your app points to the correct port when running via xcode or `react-native run-ios`. This can be done by opening the Pods project within your workspace, navigating to Build Settings and adding a Preprocessor Macro. For example `RCT_METRO_PORT=7777`, if the port you are using is `7777`.
[](https://i.stack.imgur.com/aYw06.png) |
51,989,213 | I'm newbie in MVVM . I have two xaml pages. the second one cannot be accessed ( Locked ) unless the button from the first page (Introduction page) has been clicked. How can I do that?
The lock page has this code.
```
<Frame Grid.Row="0" Grid.Column="1" BackgroundColor="LightGray" IsVisible="{Binding LockPage}">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_Lock" />
</Frame.GestureRecognizers>
<Label Text="Locked"/>
</Frame>
```
The Introduction page has this code.
```
<StackLayout>
<Label Text="This is only a simple Introduction Text."/>
<Label Text=""/>
<Button Text="Lets Go!!" Command="{Binding UnlockPageCommand}" Clicked="Tap_Next"/>
</StackLayout>
```
This is the the class LockModule.cs
```
public class LockModule : INotifyPropertyChanged
{
public LockModule()
{
UnlockPageCommand = new Command(UnlockPage);
}
bool lockPage = true;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string lockpage)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(lockpage));
}
public bool LockPage
{
get { return lockPage; }
set
{
lockPage = value;
OnPropertyChanged(nameof(LockPage));
}
}
public Command UnlockPageCommand { get; }
void UnlockPage()
{
if (lockPage == true)
{
lockPage = false;
}
else
{
lockPage = true;
}
OnPropertyChanged(nameof(LockPage));
}
}
```
and it's not working...... | 2018/08/23 | ['https://Stackoverflow.com/questions/51989213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10161534/'] | I was trying to get my RN app running on port **8088** instead of default port **8081**. I've spend almost 2 days to figure out how to do this, but the solutions found were not working in my case. Finally i've found a way to tackle this problem. Follow the 3 steps and get this resolved.
1. In `metro.config.js` file, add the following snippet within the `module.exports`.
>
> server: {
> port: 8088, }
>
>
>
2. Search for 8081 in the entire ios project and replace the value with `8088`. I had to do this in the following files for the variable `RCT_METRO_PORT`.
>
> * ios/Pods/Headers/Private/React-Core/React/RCTDefines.h
> * ios/Pods/Headers/Public/React-Core/React/RCTDefines.h
>
>
>
3. Run the build as usual, this time with the port passed as an argument.
>
> `npx react-native run-ios --port 8088`
>
>
>
Thanks! | After migrating the React Native CLI configs into `@react-native-community/cli` changing the default PORT for metro bundler became very easier, for changing the default PORT just export an environment variable by the following command inside you project path:
```
export RCT_METRO_PORT=8590
```
Also, find the `RCTDefines.h` files inside your `ios/Pods` folder, there are two of them and inside both of them change the value `8081` to `8590`.
For a test run the `echo $RCT_METRO_PORT` and if you see the new PORT `8590`, it is changed now and easily run your project with default commands.
***NOTE***: For using React Native Debugger for development just press `⌘`+`t` and then change the port value `8081` to `8590`. |
51,989,213 | I'm newbie in MVVM . I have two xaml pages. the second one cannot be accessed ( Locked ) unless the button from the first page (Introduction page) has been clicked. How can I do that?
The lock page has this code.
```
<Frame Grid.Row="0" Grid.Column="1" BackgroundColor="LightGray" IsVisible="{Binding LockPage}">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_Lock" />
</Frame.GestureRecognizers>
<Label Text="Locked"/>
</Frame>
```
The Introduction page has this code.
```
<StackLayout>
<Label Text="This is only a simple Introduction Text."/>
<Label Text=""/>
<Button Text="Lets Go!!" Command="{Binding UnlockPageCommand}" Clicked="Tap_Next"/>
</StackLayout>
```
This is the the class LockModule.cs
```
public class LockModule : INotifyPropertyChanged
{
public LockModule()
{
UnlockPageCommand = new Command(UnlockPage);
}
bool lockPage = true;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string lockpage)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(lockpage));
}
public bool LockPage
{
get { return lockPage; }
set
{
lockPage = value;
OnPropertyChanged(nameof(LockPage));
}
}
public Command UnlockPageCommand { get; }
void UnlockPage()
{
if (lockPage == true)
{
lockPage = false;
}
else
{
lockPage = true;
}
OnPropertyChanged(nameof(LockPage));
}
}
```
and it's not working...... | 2018/08/23 | ['https://Stackoverflow.com/questions/51989213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10161534/'] | I was trying to get my RN app running on port **8088** instead of default port **8081**. I've spend almost 2 days to figure out how to do this, but the solutions found were not working in my case. Finally i've found a way to tackle this problem. Follow the 3 steps and get this resolved.
1. In `metro.config.js` file, add the following snippet within the `module.exports`.
>
> server: {
> port: 8088, }
>
>
>
2. Search for 8081 in the entire ios project and replace the value with `8088`. I had to do this in the following files for the variable `RCT_METRO_PORT`.
>
> * ios/Pods/Headers/Private/React-Core/React/RCTDefines.h
> * ios/Pods/Headers/Public/React-Core/React/RCTDefines.h
>
>
>
3. Run the build as usual, this time with the port passed as an argument.
>
> `npx react-native run-ios --port 8088`
>
>
>
Thanks! | You need to overwrite the `RCT_METRO_PORT` macro variable to ensure your app points to the correct port when running via xcode or `react-native run-ios`. This can be done by opening the Pods project within your workspace, navigating to Build Settings and adding a Preprocessor Macro. For example `RCT_METRO_PORT=7777`, if the port you are using is `7777`.
[](https://i.stack.imgur.com/aYw06.png) |
51,989,213 | I'm newbie in MVVM . I have two xaml pages. the second one cannot be accessed ( Locked ) unless the button from the first page (Introduction page) has been clicked. How can I do that?
The lock page has this code.
```
<Frame Grid.Row="0" Grid.Column="1" BackgroundColor="LightGray" IsVisible="{Binding LockPage}">
<Frame.GestureRecognizers>
<TapGestureRecognizer Tapped="Tap_Lock" />
</Frame.GestureRecognizers>
<Label Text="Locked"/>
</Frame>
```
The Introduction page has this code.
```
<StackLayout>
<Label Text="This is only a simple Introduction Text."/>
<Label Text=""/>
<Button Text="Lets Go!!" Command="{Binding UnlockPageCommand}" Clicked="Tap_Next"/>
</StackLayout>
```
This is the the class LockModule.cs
```
public class LockModule : INotifyPropertyChanged
{
public LockModule()
{
UnlockPageCommand = new Command(UnlockPage);
}
bool lockPage = true;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string lockpage)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(lockpage));
}
public bool LockPage
{
get { return lockPage; }
set
{
lockPage = value;
OnPropertyChanged(nameof(LockPage));
}
}
public Command UnlockPageCommand { get; }
void UnlockPage()
{
if (lockPage == true)
{
lockPage = false;
}
else
{
lockPage = true;
}
OnPropertyChanged(nameof(LockPage));
}
}
```
and it's not working...... | 2018/08/23 | ['https://Stackoverflow.com/questions/51989213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10161534/'] | After migrating the React Native CLI configs into `@react-native-community/cli` changing the default PORT for metro bundler became very easier, for changing the default PORT just export an environment variable by the following command inside you project path:
```
export RCT_METRO_PORT=8590
```
Also, find the `RCTDefines.h` files inside your `ios/Pods` folder, there are two of them and inside both of them change the value `8081` to `8590`.
For a test run the `echo $RCT_METRO_PORT` and if you see the new PORT `8590`, it is changed now and easily run your project with default commands.
***NOTE***: For using React Native Debugger for development just press `⌘`+`t` and then change the port value `8081` to `8590`. | You need to overwrite the `RCT_METRO_PORT` macro variable to ensure your app points to the correct port when running via xcode or `react-native run-ios`. This can be done by opening the Pods project within your workspace, navigating to Build Settings and adding a Preprocessor Macro. For example `RCT_METRO_PORT=7777`, if the port you are using is `7777`.
[](https://i.stack.imgur.com/aYw06.png) |
7,964,512 | Can I start using Html 5 on our websites? Or is it too early to use it?
I see that Google is using Html 5 for their images site. If google can use it, I guess, we too can. | 2011/11/01 | ['https://Stackoverflow.com/questions/7964512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336191/'] | HTML5 is many things. If you're asking, "Is every feature of HTML5 ready for the web?" then the answer is and will be *no* for a long time.
Instead, if you're asking "Can I use these cool HTML5 things like `<section>` elements, canvas, CSS3, custom fonts, and local storage?" then the answer is *yes*. The best source to guage support of HTML5 features is [caniuse.com](http://caniuse.com/), which also includes links to [shims or polyfills](http://remysharp.com/2010/10/08/what-is-a-polyfill/) for browsers which don't support the feature. | The answer is: yes, you **should**.
Please read [here](http://coding.smashingmagazine.com/2010/12/10/why-we-should-start-using-css3-and-html5-today/), and [here](http://www.standardista.com/yes-you-can-start-using-html5-today/). |
7,964,512 | Can I start using Html 5 on our websites? Or is it too early to use it?
I see that Google is using Html 5 for their images site. If google can use it, I guess, we too can. | 2011/11/01 | ['https://Stackoverflow.com/questions/7964512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336191/'] | HTML5 is many things. If you're asking, "Is every feature of HTML5 ready for the web?" then the answer is and will be *no* for a long time.
Instead, if you're asking "Can I use these cool HTML5 things like `<section>` elements, canvas, CSS3, custom fonts, and local storage?" then the answer is *yes*. The best source to guage support of HTML5 features is [caniuse.com](http://caniuse.com/), which also includes links to [shims or polyfills](http://remysharp.com/2010/10/08/what-is-a-polyfill/) for browsers which don't support the feature. | "Depending on who you ask, HTML5 is already ready, or it won't be ready until 2022" this was quoted from Google developer advocate Mark Pilgrim at the WWW2010 conference..
you can have a look at this [post](http://www.infoworld.com/t/internet/google-official-reaffirms-html5-readiness-444) also this [post](http://www.itmontreal.ca/blog/2011/08/html-5-ready-use/) and read some info about HTML5 whether ready or not |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | You do **not** need parent `>` child here also you must **not** have space between `:` and `first-child`
**[Live Demo](http://jsfiddle.net/k84LG/)**
```
$('div.sidebar :first-child').html('<div>hiiiiiiii</div>');
```
>
> [**:first-child**](https://api.jquery.com/first-selector/) Selects all elements that are the first child of their
> parent.
>
>
>
If you just want first element then go for `:first`
>
> [**:first**](https://api.jquery.com/first-selector/) Selects the first matched element.
>
>
>
**[Live Demo](http://jsfiddle.net/k84LG/2/)**
```
$('div.sidebar :first').html('<div>hiiiiiiii</div>');
``` | ```
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
``` |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | You do **not** need parent `>` child here also you must **not** have space between `:` and `first-child`
**[Live Demo](http://jsfiddle.net/k84LG/)**
```
$('div.sidebar :first-child').html('<div>hiiiiiiii</div>');
```
>
> [**:first-child**](https://api.jquery.com/first-selector/) Selects all elements that are the first child of their
> parent.
>
>
>
If you just want first element then go for `:first`
>
> [**:first**](https://api.jquery.com/first-selector/) Selects the first matched element.
>
>
>
**[Live Demo](http://jsfiddle.net/k84LG/2/)**
```
$('div.sidebar :first').html('<div>hiiiiiiii</div>');
``` | ```
$('div.sidebar :first-child').html('hiiiiii');
```
[Refer here](https://api.jquery.com/first-child-selector/)
No space needed between : and first |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | you need to use `:first`. it will select only the first child of div with class sidebar:
```
$("div.sidebar :first").html('<div>hiiiiiiii</div>');
```
[**Here is DEMO**](http://jsfiddle.net/G6y5z/1/) | ```
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
``` |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | you need to use `:first`. it will select only the first child of div with class sidebar:
```
$("div.sidebar :first").html('<div>hiiiiiiii</div>');
```
[**Here is DEMO**](http://jsfiddle.net/G6y5z/1/) | ```
$('div.sidebar :first-child').html('hiiiiii');
```
[Refer here](https://api.jquery.com/first-child-selector/)
No space needed between : and first |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | You don't need the space between `:` and `first-child`. When you're using space, the selector will try to match a descendant `:` of `div.sidebar` which will result in this syntax error:
```
Uncaught Error: Syntax error, unrecognized expression: div.sidebar > : first-child
```
So you need to remove the space:
```
$('div.sidebar > :first-child').html('<div>hiiiiiiii</div>');
```
**[Fiddle Demo](http://jsfiddle.net/9U2QW/)** | ```
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
``` |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | You don't need the space between `:` and `first-child`. When you're using space, the selector will try to match a descendant `:` of `div.sidebar` which will result in this syntax error:
```
Uncaught Error: Syntax error, unrecognized expression: div.sidebar > : first-child
```
So you need to remove the space:
```
$('div.sidebar > :first-child').html('<div>hiiiiiiii</div>');
```
**[Fiddle Demo](http://jsfiddle.net/9U2QW/)** | ```
$('div.sidebar :first-child').html('hiiiiii');
```
[Refer here](https://api.jquery.com/first-child-selector/)
No space needed between : and first |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | Try this:
```
$('div.sidebar').first().html('<div>hiiiiiiii</div>');
```
OR
```
$('div.sidebar').eq(1).html('<div>hiiiiiiii</div>');
```
OR
```
$('div.sidebar')[0].html('<div>hiiiiiiii</div>');
``` | ```
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
``` |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | Try this:
```
$('div.sidebar').first().html('<div>hiiiiiiii</div>');
```
OR
```
$('div.sidebar').eq(1).html('<div>hiiiiiiii</div>');
```
OR
```
$('div.sidebar')[0].html('<div>hiiiiiiii</div>');
``` | ```
$('div.sidebar :first-child').html('hiiiiii');
```
[Refer here](https://api.jquery.com/first-child-selector/)
No space needed between : and first |
23,240,392 | I am having sidebar boxes and I want to change content of single box on the click event.
Here is my code :
```
<div class="sidebar">
<div class="box"> //box 1
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 1</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
<div class="box"> //box 2
<div class="box-t">
<div class="box-b">
<div class="">
<h2>This is sample box 2</h2>
<p style="text-align: left;">Please give us a shout at
<a href="mailto:concierge@example.com">concierge@example.com</a>.
</p>
</div>
</div>
</div>
</div>
</div> //sidebar div close
```
Above code is get generated dynamically and I want change the content of first box on a click of one button.
So to access first child div from sidebar, I have made a use of :
```
$('div.sidebar > : first-child').html('<div>hiiiiiiii</div>');
```
and also I have tried :
```
$('div.sidebar > : first-child').replaceWith('hiiiiiiii');
```
But both above attempts are not changing any data.
What is missing or is there any other way to change the content from of single div from multiple divs whose having same class ? | 2014/04/23 | ['https://Stackoverflow.com/questions/23240392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242378/'] | ```
$('div.sidebar : first-child').html('<div>hi with just 1 i </div>');
``` | ```
$('div.sidebar :first-child').html('hiiiiii');
```
[Refer here](https://api.jquery.com/first-child-selector/)
No space needed between : and first |
50,041,497 | I am Calculating Over Time of the employees in time format cell using **Microsoft Excel 2007**. In my result, its calculated as hh and mm. But I want only Hours and ignore Min.
Eg : I have to get this result of SANIA SARWER **0.18** as **0.0**
See the screenshot below.
[](https://i.stack.imgur.com/2gMy2.png) | 2018/04/26 | ['https://Stackoverflow.com/questions/50041497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5945772/'] | ```
=SUMPRODUCT(Int(24*$B:$B),--($A:$A=D2))
```
How does it work?
-----------------
Well, `SUMPRODUCT` will go through each item and multiply them together (So `SUMPRODUCT(A1:A3,B1:B3)` is the same as `=(A1*B1)+(A2*B2)+(A3*B3)`) - now, let's looks at each of the columns we're multiplying.
`INT(24*$B:$B)` is just Days, converted to Hours, and trim off the decimal part (minutes/seconds) - fairly simple.
`--($A:$A=D2)` first checks if the value in column A is the same as in `D2` and gives `TRUE` or `FALSE`. The `--` then converts this into `1` or `0`, which we multiply by the hours before adding them all up. | Easiest way would be to **Round Down** the data using ROUND function, and then use SUM function to add the rounding data up.
You can find a simple example below.
[](https://i.stack.imgur.com/EFvG9.png) |
61,248,155 | I am new to spring and trying to learn basic crud operations but I am stuck with delete operation my entity looks like following
```
public class Alien {
@Id
int aid;
String aname;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
```
My home.jsp file looks like the following
```
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="addAlien">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit"><br>
</form>
<form action="deleteAlien">
<input type="text" name="aid"><br>
<input type="submit"><br>
</form>
</body>
</html>
```
And controller looks like following i want submit button in delete operation where i want to delete entry bases on id
```
public class HomeController {
@Autowired
Alienrepo alienrepo;
@RequestMapping("/")
public String home() {
return "home.jsp";
}
@RequestMapping("/addAlien")
public String addAlien(Alien alien) {
alienrepo.save(alien);
return "home.jsp";
}
@RequestMapping("/deleteAlien")
public String deleteAlien(Integer id) {
alienrepo.deleteById(id);
return "home.jsp";
}
}
```
What is that I am missing? | 2020/04/16 | ['https://Stackoverflow.com/questions/61248155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10444822/'] | This `Formula1:="="""` is no valid validation forumla. The formula must according to the documentation [Validation.Add method](https://learn.microsoft.com/en-us/office/vba/api/excel.validation.add) result in `True` or `False`.
So replace it with `Formula1:=rngP.Address(False, False) & "="""`. You somehow need an address in the formula that `""` is compared to. | cheers to @HTH re the first part of the answer.
The final issue I had with runtime error 1004, was that I had not put in enough quotation marks.
So where I had: `RngP.Validation.Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Formula1:="="""`
I should have had `RngP.Validation.Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Formula1:=""=""""` |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
<https://askubuntu.com/q/384033/402539>
<https://askubuntu.com/q/810854/402539> | **EDIT:** As pointed out in recent comments, this solution may **BREAK** your system.
***You most likely don't want to remove python3.***
Please refer to the other answers for possible solutions.
*Outdated answer (not recommended)*
>
> sudo apt-get remove 'python3.\*'
>
>
> |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | neither try any above ways nor `sudo apt autoremove python3` because it will remove all gnome based applications from your system including gnome-terminal. **In case if you have done that mistake and left with kernal only than try`sudo apt install gnome` on kernal.**
try to change your default python version instead removing it. you can do this through **bashrc file** or **export path** command. | Its simple
just try:
sudo apt-get remove python3.7 or the versions that you want to remove |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | **EDIT:** As pointed out in recent comments, this solution may **BREAK** your system.
***You most likely don't want to remove python3.***
Please refer to the other answers for possible solutions.
*Outdated answer (not recommended)*
>
> sudo apt-get remove 'python3.\*'
>
>
> | neither try any above ways nor `sudo apt autoremove python3` because it will remove all gnome based applications from your system including gnome-terminal. **In case if you have done that mistake and left with kernal only than try`sudo apt install gnome` on kernal.**
try to change your default python version instead removing it. you can do this through **bashrc file** or **export path** command. |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove `Jupyter` and then alias `python=python2.7` and install all packages on Python 2.7 again.
Arguably, I can install `virtualenv` but me and my colleagues are only using 2.7. I am just going to be lazy in this case :) | neither try any above ways nor `sudo apt autoremove python3` because it will remove all gnome based applications from your system including gnome-terminal. **In case if you have done that mistake and left with kernal only than try`sudo apt install gnome` on kernal.**
try to change your default python version instead removing it. you can do this through **bashrc file** or **export path** command. |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
<https://askubuntu.com/q/384033/402539>
<https://askubuntu.com/q/810854/402539> | neither try any above ways nor `sudo apt autoremove python3` because it will remove all gnome based applications from your system including gnome-terminal. **In case if you have done that mistake and left with kernal only than try`sudo apt install gnome` on kernal.**
try to change your default python version instead removing it. you can do this through **bashrc file** or **export path** command. |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove `Jupyter` and then alias `python=python2.7` and install all packages on Python 2.7 again.
Arguably, I can install `virtualenv` but me and my colleagues are only using 2.7. I am just going to be lazy in this case :) | First of all, don't try the following command as suggested by Germain above.
```
`sudo apt-get remove 'python3.*'`
```
In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.
<https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un>
**If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.**
*Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.*
<https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/> |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | First of all, don't try the following command as suggested by Germain above.
```
`sudo apt-get remove 'python3.*'`
```
In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.
<https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un>
**If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.**
*Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.*
<https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/> | Its simple
just try:
sudo apt-get remove python3.7 or the versions that you want to remove |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
<https://askubuntu.com/q/384033/402539>
<https://askubuntu.com/q/810854/402539> | First of all, don't try the following command as suggested by Germain above.
```
`sudo apt-get remove 'python3.*'`
```
In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.
<https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un>
**If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.**
*Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.*
<https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/> |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove `Jupyter` and then alias `python=python2.7` and install all packages on Python 2.7 again.
Arguably, I can install `virtualenv` but me and my colleagues are only using 2.7. I am just going to be lazy in this case :) | Its simple
just try:
sudo apt-get remove python3.7 or the versions that you want to remove |
34,198,892 | I have recently get hold of a RackSpace Ubuntu server and it has pythons all over the place:
iPython in 3.5, Pandas in 3.4 &2.7, modules I need like pyodbc etc. are only in 2,7
Therefore, I am keen to clean up the box and, as a 2.7 users, keep everything in 2.7.
So the key question is, is there a way to remove both 3.4 and 3.5 efficiently at the same time while keeping Python 2.7? | 2015/12/10 | ['https://Stackoverflow.com/questions/34198892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4779515/'] | First of all, don't try the following command as suggested by Germain above.
```
`sudo apt-get remove 'python3.*'`
```
In Ubuntu, many software depends upon Python3 so if you will execute this command it will remove all of them as it happened with me. I found following answer useful to recover it.
<https://askubuntu.com/questions/810854/i-deleted-package-python3-on-ubuntu-and-i-have-lost-dashboard-terminal-and-un>
**If you want to use different python versions for different projects then create virtual environments it will be very useful. refer to the following link to create virtual environments.**
*Creating Virtual Environment also helps in using Tensorflow and Keras in Jupyter Notebook.*
<https://linoxide.com/linux-how-to/setup-python-virtual-environment-ubuntu/> | neither try any above ways nor `sudo apt autoremove python3` because it will remove all gnome based applications from your system including gnome-terminal. **In case if you have done that mistake and left with kernal only than try`sudo apt install gnome` on kernal.**
try to change your default python version instead removing it. you can do this through **bashrc file** or **export path** command. |
29,001,343 | I'm trying to get OAuth 1 (3 legged) on a simple Spring Boot + Spring OAuth app, only as a consumer.
I've been trying to port the tonr sample on the spring-security-oauth repository (<https://github.com/spring-projects/spring-security-oauth>) to use Java config instead of XML.
However, I'm getting:
```java
java.lang.NullPointerException: null
at org.springframework.security.oauth.consumer.filter.OAuthConsumerProcessingFilter.doFilter(OAuthConsumerProcessingFilter.java:87)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
```
...probably because the OAuthConsumerContextFilter is not being setup properly.
I tried configuring the `<oauth:consumer>` part as follows:
```java
@Bean
public OAuthConsumerProcessingFilter oAuthConsumerProcessingFilter()
{
OAuthConsumerProcessingFilter result = new OAuthConsumerProcessingFilter();
result.setProtectedResourceDetailsService(protectedResourceDetailsService());
final LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map = new LinkedHashMap<>();
map.put(new RegexRequestMatcher("/sparklr/*", null), Collections.singletonList(ConsumerSecurityConfig.PERMIT_ALL_ATTRIBUTE));
result.setObjectDefinitionSource(new DefaultFilterInvocationSecurityMetadataSource(map));
return result;
}
@Bean
public ProtectedResourceDetailsService protectedResourceDetailsService()
{
return (String id) -> {
switch (id) {
case "sparklrPhotos":
sparklrProtectedResourceDetails();
break;
}
throw new RuntimeException("Error");
};
}
@Bean
public OAuthConsumerContextFilter oAuthConsumerContextFilter() {
final CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();
consumerSupport.setProtectedResourceDetailsService(protectedResourceDetailsService());
final OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter();
filter.setConsumerSupport(consumerSupport);
return filter;
}
```
...but obviously something is missing. I even removed the `switch` and returned the same protected resource details all the time, but that doesn't change the fact that I don't have a context.
What should I do to make this work? Let me know if I need to show any other part of my code.
UPDATE: I've added the Consumer Context filter, but I think it's not being applied, as I get the same error | 2015/03/12 | ['https://Stackoverflow.com/questions/29001343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/544584/'] | In order to use Spring Security with Java Config you have to have SecurityConfig file with something like this inside (taken from <http://projects.spring.io/spring-security-oauth/docs/oauth2.html>)
```
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/login").permitAll().and()
// default protection for all resources (including /oauth/authorize)
.authorizeRequests()
.anyRequest().hasRole("USER")
// ... more configuration, e.g. for form login
}
```
That's also a place where you can add your filters in specific order using `http.addFilterAfter(oAuthConsumerContextFilter(), AnonymousAuthenticationFilter.class);`
The problem with your code is that your filter is being executed before Authetication created.
So I guess both of yout filters should be at least after AnonymousAuthenticationFilter.class
You can find list of filters here : <http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#filter-stack>
This worked for me :
```
http
.addFilterAfter(oAuthConsumerContextFilter(), SwitchUserFilter.class)
.addFilterAfter(oAuthConsumerProcessingFilter(), OAuthConsumerContextFilter.class)
``` | I found that several parts of the code in this question and other answers were incomplete and did not work for various reasons when taken as a whole. Here's the complete solution I found to get Spring Security OAuth 1 working with Spring Boot using Java config.
You need a configuration class like so:
```
@Configuration
@EnableWebSecurity
public class OAuthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(
this.oauthConsumerContextFilter(),
SwitchUserFilter.class
);
http.addFilterAfter(
this.oauthConsumerProcessingFilter(),
OAuthConsumerContextFilter.class
);
}
// IMPORTANT: this must not be a Bean
OAuthConsumerContextFilter oauthConsumerContextFilter() {
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter();
filter.setConsumerSupport(this.consumerSupport());
return filter;
}
// IMPORTANT: this must not be a Bean
OAuthConsumerProcessingFilter oauthConsumerProcessingFilter() {
OAuthConsumerProcessingFilter filter = new OAuthConsumerProcessingFilter();
filter.setProtectedResourceDetailsService(this.prds());
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map =
new LinkedHashMap<>();
// one entry per oauth:url element in xml
map.put(
// 1st arg is equivalent of url:pattern in xml
// 2nd arg is equivalent of url:httpMethod in xml
new AntPathRequestMatcher("/oauth/**", null),
// arg is equivalent of url:resources in xml
// IMPORTANT: this must match the ids in prds() and prd() below
Collections.singletonList(new SecurityConfig("myResource"))
);
filter.setObjectDefinitionSource(
new DefaultFilterInvocationSecurityMetadataSource(map)
);
return filter;
}
@Bean // optional, I re-use it elsewhere, hence the Bean
OAuthConsumerSupport consumerSupport() {
CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();
consumerSupport.setProtectedResourceDetailsService(prds());
return consumerSupport;
}
@Bean // optional, I re-use it elsewhere, hence the Bean
ProtectedResourceDetailsService prds() {
return (String id) -> {
switch (id) {
// this must match the id in prd() below
case "myResource":
return prd();
}
throw new RuntimeException("Invalid id: " + id);
};
}
ProtectedResourceDetails prd() {
BaseProtectedResourceDetails details = new BaseProtectedResourceDetails();
// this must be present and match the id in prds() and prd() above
details.setId("myResource");
details.setConsumerKey("OAuth_Key");
details.setSharedSecret("OAuth_Secret");
details.setRequestTokenURL("...");
details.setUserAuthorizationURL("...");
details.setAccessTokenURL("...");
// any other service-specific settings
return details;
}
}
```
Some key points to understand so you can avoid the problems I faced:
First, the original question configures the Processing filter with `ConsumerSecurityConfig.PERMIT_ALL_ATTRIBUTE` but this doesn't work. The value in the map has to be a SecurityConfig containing the id of the resource which is the OAuth owner for those paths.
This id must also match the ids in both the `ProtectedResourceDetailsService` and the `ProtectedResourceDetails`, and both ids must be present. Even though they are somewhat redundant, leaving out the id in `ProtectedResourceDetails` breaks the setup.
Second, the original question configures both filters as Beans. However, Spring Boot automatically registers any Beans which implement Filter in the *main* application filter chain which in this case will cause them to run twice and fail the OAuth access token process every time since it looks like a replay attack. More details in this question: [Oauth 1.0a consumer code equesting an access token twice](https://stackoverflow.com/questions/36227926/oauth-1-0a-consumer-code-equesting-an-access-token-twice)
There are two ways to fix this. I used the shorter one above (just don't make them Beans) but you can also create a `FilterRegistrationBean` to disable the auto-registration behavior.
With those corrections in place, the code above is tested and confirmed to support a working OAuth 1 negotiation with pure Java config in a Spring Boot container.
References:
The Spring OAuth 1 doc is good for understanding the classes involved and what they're for: <https://projects.spring.io/spring-security-oauth/docs/oauth1.html>
The Bean Definition Parser is the canonical implementation which converts XML to Java, so see this for any edge cases I didn't mention: <https://github.com/codehaus/spring-security-oauth/blob/master/spring-security-oauth/src/main/java/org/springframework/security/oauth/config/OAuthConsumerBeanDefinitionParser.java> |
9,590 | When reading a manual on using a PICAXE and an I2C device I saw this diagram.

I can't work how this would behave as wouldn't it make the connection on the lines constantly high due to the connection to the power rail, so never goes low. I understand that they are open-drain lines and they are needed inorder to make the lines go high but how can it make them go low with that connection to the positive rail? | 2011/01/31 | ['https://electronics.stackexchange.com/questions/9590', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1623/'] | Those are pull-up resistors. When devices aren't communicating the resistors pull both lines to high. A device is able to pull the lines low. It has to supply current that gets dissipated by the pull up resistors. You can think of this like a basic V=IR problem to determine how much current is required.
The reasoning for this setup is the situation where you want to have multiple devices communicating on a single line. If you had a device pulling the line high instead of the pull up resistors, when a different device tries to communicate it will be forced to overcome the other device in order to pull the line low. In this situation you still have a V=IR problem, except this time your R is very very small which makes I very very large. | They are required by the I2C specification.
They can be driven low by making the output pin low. |
9,590 | When reading a manual on using a PICAXE and an I2C device I saw this diagram.

I can't work how this would behave as wouldn't it make the connection on the lines constantly high due to the connection to the power rail, so never goes low. I understand that they are open-drain lines and they are needed inorder to make the lines go high but how can it make them go low with that connection to the positive rail? | 2011/01/31 | ['https://electronics.stackexchange.com/questions/9590', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1623/'] | The resistors you see are called "pull up" resistors; they literally "pull up" the signal to the positive voltage rail.
I2C is a communication bus that allows multiple devices to talk on it. Since there is only a clock and data line there is no way to ensure that two devices won't start talking at the same time, or a device mis-identifies a message as being for it and responds out of turn.
If two devices try to control the data line and one wants it '1' and the other '0' you end up with a condition called contention. Internally a normal digital output is built up out of two transistors: one connects the signal line to +V and the other to ground. The device turns on one transistor or the other to set the output signal to the appropriate level. When two devices are trying to make the same signal two different voltages you end up with +V connected to ground through two transistors. This is known as contention and is something you want to avoid because it causes high currents and can damage one or both of the output drivers.
In order to get around this problem, the I2C specification requires the use of "open collector" or "open drain" (same thing) drivers. This means that the devices on the bus can ONLY connect the signal to ground. The only way for a device to output a '1' is to not drive the line to zero. Something has to bring the line to a logic '1' and that something is the pull-up resistor.
What happens now if two devices try to drive the data line is that one is not doing anything (it wants the line to be '1') and the other device has its output transistor turned on, connecting the signal to ground. The resulting signal is a '0' -- there is no contention because the only thing holding trying to make the line a '1' is a resistor which by design limits the amount of current it allows through. Pull-up resistors are usually selected to offer a bit of resistance to a changing signal but not too much. For I2C the value for a pull up is usually 4700-10000 ohms.
Check out <http://en.wikipedia.org/wiki/Open_collector> and <http://en.wikipedia.org/wiki/I%C2%B2C> for more information. | Those are pull-up resistors. When devices aren't communicating the resistors pull both lines to high. A device is able to pull the lines low. It has to supply current that gets dissipated by the pull up resistors. You can think of this like a basic V=IR problem to determine how much current is required.
The reasoning for this setup is the situation where you want to have multiple devices communicating on a single line. If you had a device pulling the line high instead of the pull up resistors, when a different device tries to communicate it will be forced to overcome the other device in order to pull the line low. In this situation you still have a V=IR problem, except this time your R is very very small which makes I very very large. |
9,590 | When reading a manual on using a PICAXE and an I2C device I saw this diagram.

I can't work how this would behave as wouldn't it make the connection on the lines constantly high due to the connection to the power rail, so never goes low. I understand that they are open-drain lines and they are needed inorder to make the lines go high but how can it make them go low with that connection to the positive rail? | 2011/01/31 | ['https://electronics.stackexchange.com/questions/9590', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1623/'] | The resistors you see are called "pull up" resistors; they literally "pull up" the signal to the positive voltage rail.
I2C is a communication bus that allows multiple devices to talk on it. Since there is only a clock and data line there is no way to ensure that two devices won't start talking at the same time, or a device mis-identifies a message as being for it and responds out of turn.
If two devices try to control the data line and one wants it '1' and the other '0' you end up with a condition called contention. Internally a normal digital output is built up out of two transistors: one connects the signal line to +V and the other to ground. The device turns on one transistor or the other to set the output signal to the appropriate level. When two devices are trying to make the same signal two different voltages you end up with +V connected to ground through two transistors. This is known as contention and is something you want to avoid because it causes high currents and can damage one or both of the output drivers.
In order to get around this problem, the I2C specification requires the use of "open collector" or "open drain" (same thing) drivers. This means that the devices on the bus can ONLY connect the signal to ground. The only way for a device to output a '1' is to not drive the line to zero. Something has to bring the line to a logic '1' and that something is the pull-up resistor.
What happens now if two devices try to drive the data line is that one is not doing anything (it wants the line to be '1') and the other device has its output transistor turned on, connecting the signal to ground. The resulting signal is a '0' -- there is no contention because the only thing holding trying to make the line a '1' is a resistor which by design limits the amount of current it allows through. Pull-up resistors are usually selected to offer a bit of resistance to a changing signal but not too much. For I2C the value for a pull up is usually 4700-10000 ohms.
Check out <http://en.wikipedia.org/wiki/Open_collector> and <http://en.wikipedia.org/wiki/I%C2%B2C> for more information. | They are required by the I2C specification.
They can be driven low by making the output pin low. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.