问:
How to efficiently check whether a vector of numbers is in an interval defined by a data frame
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

```<code>set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}
</code>```

Thanks!

答:
If I understand correctly, the OP is looking for an efficient method to pick a value from a matching right-closed interval where the upper limits are given.

For large datasets, a rolling join might be worthwhile to look at:

```<code>library(data.table)
setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value
</code>```

or, replacing n1 as desired by the OP

```<code>n1 <- setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value
</code>```

As the OP is asking for efficiency, here is a benchmark with varying problem sizes which compares the methods posted so far:

```<code>library(data.table)
bm <- bench::press(
  n_int = 10*c(1e2L, 1e4L, 1e6L),
  n_n1 = 10*c(1e2L, 1e4L, 1e6L),
  {
  seq.vec <- seq(400L, length.out = n_int, by = 200L)
  df.int <- data.frame(Upper.Limit = seq.vec,
                       Value = seq_along(seq.vec))
  set.seed(123)
  n0 <- sample(400:max(seq.vec), n_n1, replace = TRUE)
  # include edge cases
  n0[1:5] <- c(seq.vec[1L] - 1L, seq.vec[1L], seq.vec[2L],
               max(seq.vec), max(seq.vec) + 1L)
  n1 <- data.table::copy(n0)

    bench::mark(
      rollJoin = {
        setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value
      }
      , findInt = {
        i <- findInterval(n1, df.int$Upper.Limit, left.open = TRUE)
        df.int[["Value"]][i+1]
      }
      , approx = {
      approx(x = df.int$Upper.Limit,
             y = df.int$Value,
             xout = n1,
             method = "constant",
             f = 1,
             rule = 2:1             ## extrapolation behavior outside domain
      )$y
    }
    , subsInt = {
      subsInterval <- function(x, DF, colLimits = 1, colValues = 2, lower = TRUE){
        vec <- if(lower)
          c(DF[[colLimits]], Inf)
        else
          c(-Inf, DF[[colLimits]])
        i <- findInterval(x, vec, left.open = TRUE)
        DF[[colValues]][i]
      }
      subsInterval(n1, df.int, lower = FALSE)
    }
    , min_time = 1.5
    , check = TRUE
  )
  }
)
</code>```

which returns the following timings

```<code>print(bm, n = Inf)
</code>```

```<code># A tibble: 36 x 15
   expression  n_int   n_n1      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory time  gc
   <bch:expr>  <dbl>  <dbl> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list> <lis> <lis>
 1 rollJoin   1.00e3 1.00e3   1.84ms   2.24ms   4.31e+2  144.57KB   1.37     630     2      1.46s <int ~ <Rpro~ <bch~ <tib~
 2 findInt    1.00e3 1.00e3   73.9us   77.2us   1.15e+4   35.44KB   2.31    9998     2   866.63ms <int ~ <Rpro~ <bch~ <tib~
 3 approx     1.00e3 1.00e3  124.9us  129.7us   7.04e+3   63.16KB   2.11    9997     3      1.42s <dbl ~ <Rpro~ <bch~ <tib~
 4 subsInt    1.00e3 1.00e3   71.8us     74us   1.23e+4   23.63KB   1.23    9999     1   813.65ms <int ~ <Rpro~ <bch~ <tib~
 5 rollJoin   1.00e5 1.00e3   3.17ms   3.65ms   2.65e+2  918.01KB   1.35     392     2      1.48s <int ~ <Rpro~ <bch~ <tib~
 6 findInt    1.00e5 1.00e3  455.7us  603.6us   1.58e+3  808.88KB   5.99    2107     8      1.34s <int ~ <Rpro~ <bch~ <tib~
 7 approx     1.00e5 1.00e3   4.26ms   5.28ms   1.88e+2    4.83MB   4.46     253     6      1.35s <dbl ~ <Rpro~ <bch~ <tib~
 8 subsInt    1.00e5 1.00e3    516us  659.4us   1.46e+3  797.07KB   5.94    1960     8      1.35s <int ~ <Rpro~ <bch~ <tib~
 9 rollJoin   1.00e7 1.00e3  80.21ms  83.39ms   1.12e+1   76.43MB   2.64      17     4      1.52s <int ~ <Rpro~ <bch~ <tib~
10 findInt    1.00e7 1.00e3  37.72ms  48.19ms   1.66e+1   76.32MB   7.98      25    12       1.5s <int ~ <Rpro~ <bch~ <tib~
11 approx     1.00e7 1.00e3  931.5ms 934.27ms   1.07e+0  509.49MB   2.14       2     4      1.87s <dbl ~ <Rpro~ <bch~ <tib~
12 subsInt    1.00e7 1.00e3  46.98ms  49.05ms   1.64e+1   76.31MB   4.59      25     7      1.53s <int ~ <Rpro~ <bch~ <tib~
13 rollJoin   1.00e3 1.00e5   9.05ms  10.56ms   9.42e+1    3.16MB   0.683    138     1      1.47s <int ~ <Rpro~ <bch~ <tib~
14 findInt    1.00e3 1.00e5    6.6ms   7.17ms   1.37e+2    2.68MB   0.680    202     1      1.47s <int ~ <Rpro~ <bch~ <tib~
15 approx     1.00e3 1.00e5   6.95ms   7.54ms   1.31e+2    1.57MB   0.682    192     1      1.47s <dbl ~ <Rpro~ <bch~ <tib~
16 subsInt    1.00e3 1.00e5   5.78ms   6.35ms   1.56e+2    1.53MB   0.681    229     1      1.47s <int ~ <Rpro~ <bch~ <tib~
17 rollJoin   1.00e5 1.00e5  13.24ms  14.34ms   6.93e+1    3.92MB   0.686    101     1      1.46s <int ~ <Rpro~ <bch~ <tib~
18 findInt    1.00e5 1.00e5  20.74ms  22.21ms   4.48e+1    3.43MB   0         68     0      1.52s <int ~ <Rpro~ <bch~ <tib~
19 approx     1.00e5 1.00e5  17.69ms   19.4ms   5.14e+1    6.34MB   1.41      73     2      1.42s <dbl ~ <Rpro~ <bch~ <tib~
20 subsInt    1.00e5 1.00e5  20.17ms  21.29ms   4.39e+1    2.29MB   0         66     0       1.5s <int ~ <Rpro~ <bch~ <tib~
21 rollJoin   1.00e7 1.00e5   98.3ms  104.8ms   9.02e+0   79.45MB   1.29      14     2      1.55s <int ~ <Rpro~ <bch~ <tib~
22 findInt    1.00e7 1.00e5 202.72ms 204.44ms   4.47e+0   78.97MB   1.28       7     2      1.57s <int ~ <Rpro~ <bch~ <tib~
23 approx     1.00e7 1.00e5    1.11s    1.14s   8.76e-1     511MB   2.19       2     5      2.28s <dbl ~ <Rpro~ <bch~ <tib~
24 subsInt    1.00e7 1.00e5 208.82ms 211.26ms   4.57e+0   77.82MB   0.653      7     1      1.53s <int ~ <Rpro~ <bch~ <tib~
25 rollJoin   1.00e3 1.00e7    1.02s    1.12s   8.93e-1  305.29MB   1.34       2     3      2.24s <int ~ <Rpro~ <bch~ <tib~
26 findInt    1.00e3 1.00e7 797.56ms 807.58ms   1.24e+0  267.04MB   1.86       2     3      1.61s <int ~ <Rpro~ <bch~ <tib~
27 approx     1.00e3 1.00e7 747.18ms 844.75ms   1.18e+0  152.63MB   0.592      2     1      1.69s <dbl ~ <Rpro~ <bch~ <tib~
28 subsInt    1.00e3 1.00e7  639.3ms 642.26ms   1.53e+0   152.6MB   0.510      3     1      1.96s <int ~ <Rpro~ <bch~ <tib~
29 rollJoin   1.00e5 1.00e7    1.68s    1.68s   5.95e-1  306.04MB   1.19       1     2      1.68s <int ~ <Rpro~ <bch~ <tib~
30 findInt    1.00e5 1.00e7    2.34s    2.34s   4.27e-1  267.79MB   0.427      1     1      2.34s <int ~ <Rpro~ <bch~ <tib~
31 approx     1.00e5 1.00e7    1.45s    1.46s   6.86e-1   157.4MB   0.343      2     1      2.92s <dbl ~ <Rpro~ <bch~ <tib~
32 subsInt    1.00e5 1.00e7    2.08s    2.08s   4.81e-1  153.35MB   0          1     0      2.08s <int ~ <Rpro~ <bch~ <tib~
33 rollJoin   1.00e7 1.00e7    1.82s    1.82s   5.49e-1  381.57MB   0.549      1     1      1.82s <int ~ <Rpro~ <bch~ <tib~
34 findInt    1.00e7 1.00e7   18.21s   18.21s   5.49e-2  343.32MB   0.110      1     2     18.21s <int ~ <Rpro~ <bch~ <tib~
35 approx     1.00e7 1.00e7     6.2s     6.2s   1.61e-1  662.06MB   0.323      1     2       6.2s <dbl ~ <Rpro~ <bch~ <tib~
36 subsInt    1.00e7 1.00e7   16.57s   16.57s   6.03e-2  228.88MB   0.0603     1     1     16.57s <int ~ <Rpro~ <bch~ <tib~
</code>```

```<code>library(ggplot2)
autoplot(bm)
</code>```

Please note the logarithmic time scale.

For smaller problem sizes, findInterval() or the function which wraps findInterval() seem to be the fastest methods while for increasing problem sizes rolling join takes the lead.

For larger problem sizes, memory allocation (see table) might become an issue which also might impact performance as well.

Body:
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}

Thanks!

Body:
If I understand correctly, the OP is looking for an efficient method to pick a value from a matching right-closed interval where the upper limits are given.

For large datasets, a rolling join might be worthwhile to look at:

library(data.table)
setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value

or, replacing n1 as desired by the OP

n1 <- setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value

As the OP is asking for efficiency, here is a benchmark with varying problem sizes which compares the methods posted so far:

library(data.table)
bm <- bench::press(
  n_int = 10*c(1e2L, 1e4L, 1e6L),
  n_n1 = 10*c(1e2L, 1e4L, 1e6L),
  {
  seq.vec <- seq(400L, length.out = n_int, by = 200L)
  df.int <- data.frame(Upper.Limit = seq.vec,
                       Value = seq_along(seq.vec))
  set.seed(123)
  n0 <- sample(400:max(seq.vec), n_n1, replace = TRUE)
  # include edge cases
  n0[1:5] <- c(seq.vec[1L] - 1L, seq.vec[1L], seq.vec[2L],
               max(seq.vec), max(seq.vec) + 1L)
  n1 <- data.table::copy(n0)

    bench::mark(
      rollJoin = {
        setDT(df.int)[data.table(n1), on = .(Upper.Limit = n1), roll = -Inf]$Value
      }
      , findInt = {
        i <- findInterval(n1, df.int$Upper.Limit, left.open = TRUE)
        df.int[["Value"]][i+1]
      }
      , approx = {
      approx(x = df.int$Upper.Limit,
             y = df.int$Value,
             xout = n1,
             method = "constant",
             f = 1,
             rule = 2:1             ## extrapolation behavior outside domain
      )$y
    }
    , subsInt = {
      subsInterval <- function(x, DF, colLimits = 1, colValues = 2, lower = TRUE){
        vec <- if(lower)
          c(DF[[colLimits]], Inf)
        else
          c(-Inf, DF[[colLimits]])
        i <- findInterval(x, vec, left.open = TRUE)
        DF[[colValues]][i]
      }
      subsInterval(n1, df.int, lower = FALSE)
    }
    , min_time = 1.5
    , check = TRUE
  )
  }
)

which returns the following timings

print(bm, n = Inf)

# A tibble: 36 x 15
   expression  n_int   n_n1      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory time  gc
   <bch:expr>  <dbl>  <dbl> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list> <lis> <lis>
 1 rollJoin   1.00e3 1.00e3   1.84ms   2.24ms   4.31e+2  144.57KB   1.37     630     2      1.46s <int ~ <Rpro~ <bch~ <tib~
 2 findInt    1.00e3 1.00e3   73.9us   77.2us   1.15e+4   35.44KB   2.31    9998     2   866.63ms <int ~ <Rpro~ <bch~ <tib~
 3 approx     1.00e3 1.00e3  124.9us  129.7us   7.04e+3   63.16KB   2.11    9997     3      1.42s <dbl ~ <Rpro~ <bch~ <tib~
 4 subsInt    1.00e3 1.00e3   71.8us     74us   1.23e+4   23.63KB   1.23    9999     1   813.65ms <int ~ <Rpro~ <bch~ <tib~
 5 rollJoin   1.00e5 1.00e3   3.17ms   3.65ms   2.65e+2  918.01KB   1.35     392     2      1.48s <int ~ <Rpro~ <bch~ <tib~
 6 findInt    1.00e5 1.00e3  455.7us  603.6us   1.58e+3  808.88KB   5.99    2107     8      1.34s <int ~ <Rpro~ <bch~ <tib~
 7 approx     1.00e5 1.00e3   4.26ms   5.28ms   1.88e+2    4.83MB   4.46     253     6      1.35s <dbl ~ <Rpro~ <bch~ <tib~
 8 subsInt    1.00e5 1.00e3    516us  659.4us   1.46e+3  797.07KB   5.94    1960     8      1.35s <int ~ <Rpro~ <bch~ <tib~
 9 rollJoin   1.00e7 1.00e3  80.21ms  83.39ms   1.12e+1   76.43MB   2.64      17     4      1.52s <int ~ <Rpro~ <bch~ <tib~
10 findInt    1.00e7 1.00e3  37.72ms  48.19ms   1.66e+1   76.32MB   7.98      25    12       1.5s <int ~ <Rpro~ <bch~ <tib~
11 approx     1.00e7 1.00e3  931.5ms 934.27ms   1.07e+0  509.49MB   2.14       2     4      1.87s <dbl ~ <Rpro~ <bch~ <tib~
12 subsInt    1.00e7 1.00e3  46.98ms  49.05ms   1.64e+1   76.31MB   4.59      25     7      1.53s <int ~ <Rpro~ <bch~ <tib~
13 rollJoin   1.00e3 1.00e5   9.05ms  10.56ms   9.42e+1    3.16MB   0.683    138     1      1.47s <int ~ <Rpro~ <bch~ <tib~
14 findInt    1.00e3 1.00e5    6.6ms   7.17ms   1.37e+2    2.68MB   0.680    202     1      1.47s <int ~ <Rpro~ <bch~ <tib~
15 approx     1.00e3 1.00e5   6.95ms   7.54ms   1.31e+2    1.57MB   0.682    192     1      1.47s <dbl ~ <Rpro~ <bch~ <tib~
16 subsInt    1.00e3 1.00e5   5.78ms   6.35ms   1.56e+2    1.53MB   0.681    229     1      1.47s <int ~ <Rpro~ <bch~ <tib~
17 rollJoin   1.00e5 1.00e5  13.24ms  14.34ms   6.93e+1    3.92MB   0.686    101     1      1.46s <int ~ <Rpro~ <bch~ <tib~
18 findInt    1.00e5 1.00e5  20.74ms  22.21ms   4.48e+1    3.43MB   0         68     0      1.52s <int ~ <Rpro~ <bch~ <tib~
19 approx     1.00e5 1.00e5  17.69ms   19.4ms   5.14e+1    6.34MB   1.41      73     2      1.42s <dbl ~ <Rpro~ <bch~ <tib~
20 subsInt    1.00e5 1.00e5  20.17ms  21.29ms   4.39e+1    2.29MB   0         66     0       1.5s <int ~ <Rpro~ <bch~ <tib~
21 rollJoin   1.00e7 1.00e5   98.3ms  104.8ms   9.02e+0   79.45MB   1.29      14     2      1.55s <int ~ <Rpro~ <bch~ <tib~
22 findInt    1.00e7 1.00e5 202.72ms 204.44ms   4.47e+0   78.97MB   1.28       7     2      1.57s <int ~ <Rpro~ <bch~ <tib~
23 approx     1.00e7 1.00e5    1.11s    1.14s   8.76e-1     511MB   2.19       2     5      2.28s <dbl ~ <Rpro~ <bch~ <tib~
24 subsInt    1.00e7 1.00e5 208.82ms 211.26ms   4.57e+0   77.82MB   0.653      7     1      1.53s <int ~ <Rpro~ <bch~ <tib~
25 rollJoin   1.00e3 1.00e7    1.02s    1.12s   8.93e-1  305.29MB   1.34       2     3      2.24s <int ~ <Rpro~ <bch~ <tib~
26 findInt    1.00e3 1.00e7 797.56ms 807.58ms   1.24e+0  267.04MB   1.86       2     3      1.61s <int ~ <Rpro~ <bch~ <tib~
27 approx     1.00e3 1.00e7 747.18ms 844.75ms   1.18e+0  152.63MB   0.592      2     1      1.69s <dbl ~ <Rpro~ <bch~ <tib~
28 subsInt    1.00e3 1.00e7  639.3ms 642.26ms   1.53e+0   152.6MB   0.510      3     1      1.96s <int ~ <Rpro~ <bch~ <tib~
29 rollJoin   1.00e5 1.00e7    1.68s    1.68s   5.95e-1  306.04MB   1.19       1     2      1.68s <int ~ <Rpro~ <bch~ <tib~
30 findInt    1.00e5 1.00e7    2.34s    2.34s   4.27e-1  267.79MB   0.427      1     1      2.34s <int ~ <Rpro~ <bch~ <tib~
31 approx     1.00e5 1.00e7    1.45s    1.46s   6.86e-1   157.4MB   0.343      2     1      2.92s <dbl ~ <Rpro~ <bch~ <tib~
32 subsInt    1.00e5 1.00e7    2.08s    2.08s   4.81e-1  153.35MB   0          1     0      2.08s <int ~ <Rpro~ <bch~ <tib~
33 rollJoin   1.00e7 1.00e7    1.82s    1.82s   5.49e-1  381.57MB   0.549      1     1      1.82s <int ~ <Rpro~ <bch~ <tib~
34 findInt    1.00e7 1.00e7   18.21s   18.21s   5.49e-2  343.32MB   0.110      1     2     18.21s <int ~ <Rpro~ <bch~ <tib~
35 approx     1.00e7 1.00e7     6.2s     6.2s   1.61e-1  662.06MB   0.323      1     2       6.2s <dbl ~ <Rpro~ <bch~ <tib~
36 subsInt    1.00e7 1.00e7   16.57s   16.57s   6.03e-2  228.88MB   0.0603     1     1     16.57s <int ~ <Rpro~ <bch~ <tib~

library(ggplot2)
autoplot(bm)

Please note the logarithmic time scale.

For smaller problem sizes, findInterval() or the function which wraps findInterval() seem to be the fastest methods while for increasing problem sizes rolling join takes the lead.

For larger problem sizes, memory allocation (see table) might become an issue which also might impact performance as well.


来源: stackexchange

问:
Google Pixel not found in Android Studio
Having trouble with Android Studio connecting to my Pixel phone. I'm sort of out of ideas and am looking for suggestions. I feel like I'm missing an obvious step.

Things I've done:

Made sure developer options is on with USB debugging on.

Have tried switching from MTP to PTP.

My computer recognizes the Pixel just fine under windows 8.

Made sure android studio is up to date including "Google USB Driver" installed under SDK tools.

My previous phone (Droid mini) connects just fine.

Tried different USB ports for the cable to my phone.

答:
I have had the same trouble with my Google Pixel 2 (Android 9); I couldn't connect it to ADB in Android Studio 3.3. In my special case, AS runs on Kubuntu 18.04 in a VMware Workstation on a Windows host.
I have to do following steps every time I want to connect the phone (the phone is already in developer mode):

Plug phone via USB into the computer (and connect it to the VMware guest, if you use it)

Phone: Swipe down the notification bar, there should be a message 'Charging the device via UDB'

Tab on it and change the 'Use USB for' from 'No data transfer' to 'File trasfer'

You can activate 'USB debugging' on your phone's developer screen before or after this procedure, both works for me.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
DataVisualization Charting - Place Point Label In Bar (If Go Outside Of Chart)
I am using DataVisualization.Charting in C# to generate a column chart - The issue I am having is that the label I am adding to show the value of the bar is displaying off the top of the chart (See image below).

The 0 values are ok but in a perfect world in the scenario below I would like the label on the columns with data which go off the top of the chart to be placed within the bar its self - Is this possible at all?

I have tried various settings via the Series SmartLabelStyles but have not been able to find a solution which works.

Below is how I am adding my labels to the chart:

```<code>chart.Series[0].Points[0].Label = Math.Round(pos1, 2).ToString() + "hrs " + Math.Round(((pos1 / totalHoursV) * 100), 2).ToString() + "%";
</code>```

UPDATE

I have tried to display the Labels on the Bottom as per this answer (https://stackoverflow.com/a/28590709/2822664) which does actually work for the values in the bars and shows the values in the bar, however it then messes up the values of 0 and doesn't show them correctly (See image below).

答:
You can control the alignment of the Labels by setting a custom property.

This can be done for the whole Series but also for each DataPoint individually:

```<code>Series s = chart1.Series[0];
s.ChartType = SeriesChartType.Column;
s.IsValueShownAsLabel = true;

for (int i = 0; i < 30; i++)
{
    int p = s.Points.AddXY(i, rnd.Next(30));
    DataPoint pt = s.Points[p];
    if (pt.YValues[0] >   10)   // use a suitable value!
    {
       pt.SetCustomProperty("LabelStyle", "Bottom");
       pt.LabelForeColor = Color.White;
    }
    else pt.LabelBackColor = Color.White;

}
</code>```

Body:
I am using DataVisualization.Charting in C# to generate a column chart - The issue I am having is that the label I am adding to show the value of the bar is displaying off the top of the chart (See image below).

The 0 values are ok but in a perfect world in the scenario below I would like the label on the columns with data which go off the top of the chart to be placed within the bar its self - Is this possible at all?

I have tried various settings via the Series SmartLabelStyles but have not been able to find a solution which works.

Below is how I am adding my labels to the chart:

chart.Series[0].Points[0].Label = Math.Round(pos1, 2).ToString() + "hrs " + Math.Round(((pos1 / totalHoursV) * 100), 2).ToString() + "%";

UPDATE

I have tried to display the Labels on the Bottom as per this answer (https://stackoverflow.com/a/28590709/2822664) which does actually work for the values in the bars and shows the values in the bar, however it then messes up the values of 0 and doesn't show them correctly (See image below).

Body:
You can control the alignment of the Labels by setting a custom property.

This can be done for the whole Series but also for each DataPoint individually:

Series s = chart1.Series[0];
s.ChartType = SeriesChartType.Column;
s.IsValueShownAsLabel = true;

for (int i = 0; i < 30; i++)
{
    int p = s.Points.AddXY(i, rnd.Next(30));
    DataPoint pt = s.Points[p];
    if (pt.YValues[0] >   10)   // use a suitable value!
    {
       pt.SetCustomProperty("LabelStyle", "Bottom");
       pt.LabelForeColor = Color.White;
    }
    else pt.LabelBackColor = Color.White;

}


问:
FileDescriptor for USB Accessory gets closed
I use a service to open connection to USB Accessory. I use an input stream that is bind to the FileDescriptor I get from UsbManager's openAccessory() method. Everything works fine as long as I don't start a new activity. For some reason when I start a new activity I get IOException (File descriptor closed). Any ideas why this is happening? I wan't it to work so that the input stream stays connected across activities.</p>

答:
Let me help you a bit more with a complete service to read the usb in accessory mode.
The read data is put in a buffer.</p>

```<code>public final class UsbService extends Service {

    //Member attributes
    // USB
    private static final String ACTION_USB_PERMISSION = "com.examples.accessory.controller.action.USB_PERMISSION";

    private Context mMainContext;
    LocalBroadcastManager mBroadcastManager = null;

    private UsbManager mUsbManager;
    private PendingIntent mPermissionIntent;
    private UsbAccessory mAccessory;
    private ParcelFileDescriptor mFileDescriptor;
    private FileInputStream mInputStream;
    private FileOutputStream mOutputStream;

    private boolean mPermissionRequestPendding = false;

    private Thread mAccessMonitor;
    private Thread mUsbListenner;

    private ConcurrentLinkedQueue<String> usbDataBuffer;

    /* ************************************* */
    /*         BROADCAST RECEIVERS           */
    /* ************************************* */

    private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            usbPermissionMonitor(intent);
        }
    };

    /* ************************************* */
    /*              RUNNABLES                */
    /* ************************************* */

    // Running thread listenning to USB port for received messages
    private Runnable UsbListenner = new Runnable() {
        public void run() {
            while(1)
                readUsbAccessory();
        }
    };

    // Running thread listenning to USB accessories
    private Runnable AccessoryMonitor = new Runnable() {
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            while(mIsServiceRunning){
                try {
                    getAccessory();
                    sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /* ************************************* */
    /*           SERVICE FUNCTIONS           */
    /* ************************************* */
    public UsbService(){}

    @Override
    public void onCreate() {
        mMainContext = getApplicationContext();
        mBroadcastManager = LocalBroadcastManager.getInstance(mMainContext);
        mBroadcastManager.registerReceiver(usbServiceReceiver, usbServiceFilter);
        initUsb();
    }

    public IBinder onBind(Intent intent){
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        super.onUnbind(intent);
        return true;
    }

    // Destroy
    @Override
    public void onDestroy() {

        closeAccessory();
        mBroadcastManager.unregisterReceiver(mUsbPermissionReceiver);
        mBroadcastManager.unregisterReceiver(usbServiceReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        return START_NOT_STICKY;
    }

    /* ************************************* */
    /*         USB CONTROL FUNCTIONS         */
    /* ************************************* */

    private void initUsb()
    {
        usbDataBuffer = new ConcurrentLinkedQueue<>();
        mAccessMonitor= new Thread(AccessoryMonitor);
        mUsbListenner = new Thread(UsbListenner);

        mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(UsbManager.EXTRA_ACCESSORY);
        mBroadcastManager.registerReceiver(mUsbPermissionReceiver, filter);
        mAccessMonitor.start();
    }

    private void getAccessory()
    {
        if (mFileDescriptor != null) {
            return;
        }

        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
        if (accessory != null)
        {
            if (mUsbManager.hasPermission(accessory))
            {
                //"has permission";
                if(!mPermissionRequestPendding) {
                    openAccessory(accessory);
                }
            }
            else
            {
                //"no permission";
                synchronized (mUsbPermissionReceiver)
                {
                    if(!mPermissionRequestPendding) {
                        mUsbManager.requestPermission(accessory, mPermissionIntent);
                        mPermissionRequestPendding = true;
                    }
                }
            }
        }
    }

    private void openAccessory(UsbAccessory accessory)
    {
        if(accessory != null) {
            mFileDescriptor = mUsbManager.openAccessory(accessory);
            if (mFileDescriptor != null) {
                mAccessory = accessory;
                FileDescriptor fd = mFileDescriptor.getFileDescriptor();
                mInputStream = new FileInputStream(fd);
                mOutputStream = new FileOutputStream(fd);
                mUsbListenner.start();
                mPermissionRequestPendding = false;
            }
        }
    }

    private void closeAccessory() {
        try {
            if (mFileDescriptor != null) {
                mFileDescriptor.close();
            }
        }
        catch (IOException e) {

        }
        finally {
            mAccessory = null;
            mFileDescriptor = null;
        }
    }

    public void sendDataUsb(String msg)
    {
        if (mFileDescriptor != null) {
            byte[] bytes = msg.getBytes();
            try {
                mOutputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * Runnable block that will poll the accessory data stream
     * for regular updates, adds each message to a buffer.
     */
    private void readUsbAccessory() {
        if (mFileDescriptor != null) {
            int ret = 0;
            byte[] buffer = new byte[16384];

            while (mFileDescriptor != null) {
                try {
                    ret = mInputStream.read(buffer);
                    if (ret > 0) {
                        usbDataBuffer.add(new String(buffer, 0, ret));
                    }
                } catch (IOException e) {
                    break;
                }
            }
        }
    }

    /*
     * This receiver monitors for the event of a user granting permission to use
     * the attached accessory.  If the user has checked to always allow, this will
     * be generated following attachment without further user interaction.
     */
    private void usbPermissionMonitor(Intent intent)
    {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                final UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    openAccessory(accessory);
                    mPermissionRequestPendding = false;
                } else {
                    //permission refused
                    mUsbManager.requestPermission(accessory, mPermissionIntent);
                }
            }
        } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
            UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
            if (accessory != null && accessory.equals(mAccessory)) {
                Toast.makeText(this, "Cable detach !", Toast.LENGTH_LONG).show();
                closeAccessory();
                mUsbActive = false;
            }
        }
    }
}
</code>```

Body:
Let me help you a bit more with a complete service to read the usb in accessory mode.
The read data is put in a buffer.

public final class UsbService extends Service {

    //Member attributes
    // USB
    private static final String ACTION_USB_PERMISSION = "com.examples.accessory.controller.action.USB_PERMISSION";

    private Context mMainContext;
    LocalBroadcastManager mBroadcastManager = null;

    private UsbManager mUsbManager;
    private PendingIntent mPermissionIntent;
    private UsbAccessory mAccessory;
    private ParcelFileDescriptor mFileDescriptor;
    private FileInputStream mInputStream;
    private FileOutputStream mOutputStream;

    private boolean mPermissionRequestPendding = false;

    private Thread mAccessMonitor;
    private Thread mUsbListenner;

    private ConcurrentLinkedQueue<String> usbDataBuffer;

    /* ************************************* */
    /*         BROADCAST RECEIVERS           */
    /* ************************************* */

    private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            usbPermissionMonitor(intent);
        }
    };

    /* ************************************* */
    /*              RUNNABLES                */
    /* ************************************* */

    // Running thread listenning to USB port for received messages
    private Runnable UsbListenner = new Runnable() {
        public void run() {
            while(1)
                readUsbAccessory();
        }
    };

    // Running thread listenning to USB accessories
    private Runnable AccessoryMonitor = new Runnable() {
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            while(mIsServiceRunning){
                try {
                    getAccessory();
                    sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /* ************************************* */
    /*           SERVICE FUNCTIONS           */
    /* ************************************* */
    public UsbService(){}

    @Override
    public void onCreate() {
        mMainContext = getApplicationContext();
        mBroadcastManager = LocalBroadcastManager.getInstance(mMainContext);
        mBroadcastManager.registerReceiver(usbServiceReceiver, usbServiceFilter);
        initUsb();
    }

    public IBinder onBind(Intent intent){
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        super.onUnbind(intent);
        return true;
    }

    // Destroy
    @Override
    public void onDestroy() {

        closeAccessory();
        mBroadcastManager.unregisterReceiver(mUsbPermissionReceiver);
        mBroadcastManager.unregisterReceiver(usbServiceReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        return START_NOT_STICKY;
    }

    /* ************************************* */
    /*         USB CONTROL FUNCTIONS         */
    /* ************************************* */

    private void initUsb()
    {
        usbDataBuffer = new ConcurrentLinkedQueue<>();
        mAccessMonitor= new Thread(AccessoryMonitor);
        mUsbListenner = new Thread(UsbListenner);

        mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        filter.addAction(UsbManager.EXTRA_ACCESSORY);
        mBroadcastManager.registerReceiver(mUsbPermissionReceiver, filter);
        mAccessMonitor.start();
    }

    private void getAccessory()
    {
        if (mFileDescriptor != null) {
            return;
        }

        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
        if (accessory != null)
        {
            if (mUsbManager.hasPermission(accessory))
            {
                //"has permission";
                if(!mPermissionRequestPendding) {
                    openAccessory(accessory);
                }
            }
            else
            {
                //"no permission";
                synchronized (mUsbPermissionReceiver)
                {
                    if(!mPermissionRequestPendding) {
                        mUsbManager.requestPermission(accessory, mPermissionIntent);
                        mPermissionRequestPendding = true;
                    }
                }
            }
        }
    }

    private void openAccessory(UsbAccessory accessory)
    {
        if(accessory != null) {
            mFileDescriptor = mUsbManager.openAccessory(accessory);
            if (mFileDescriptor != null) {
                mAccessory = accessory;
                FileDescriptor fd = mFileDescriptor.getFileDescriptor();
                mInputStream = new FileInputStream(fd);
                mOutputStream = new FileOutputStream(fd);
                mUsbListenner.start();
                mPermissionRequestPendding = false;
            }
        }
    }

    private void closeAccessory() {
        try {
            if (mFileDescriptor != null) {
                mFileDescriptor.close();
            }
        }
        catch (IOException e) {

        }
        finally {
            mAccessory = null;
            mFileDescriptor = null;
        }
    }

    public void sendDataUsb(String msg)
    {
        if (mFileDescriptor != null) {
            byte[] bytes = msg.getBytes();
            try {
                mOutputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * Runnable block that will poll the accessory data stream
     * for regular updates, adds each message to a buffer.
     */
    private void readUsbAccessory() {
        if (mFileDescriptor != null) {
            int ret = 0;
            byte[] buffer = new byte[16384];

            while (mFileDescriptor != null) {
                try {
                    ret = mInputStream.read(buffer);
                    if (ret > 0) {
                        usbDataBuffer.add(new String(buffer, 0, ret));
                    }
                } catch (IOException e) {
                    break;
                }
            }
        }
    }

    /*
     * This receiver monitors for the event of a user granting permission to use
     * the attached accessory.  If the user has checked to always allow, this will
     * be generated following attachment without further user interaction.
     */
    private void usbPermissionMonitor(Intent intent)
    {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                final UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    openAccessory(accessory);
                    mPermissionRequestPendding = false;
                } else {
                    //permission refused
                    mUsbManager.requestPermission(accessory, mPermissionIntent);
                }
            }
        } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
            UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
            if (accessory != null && accessory.equals(mAccessory)) {
                Toast.makeText(this, "Cable detach !", Toast.LENGTH_LONG).show();
                closeAccessory();
                mUsbActive = false;
            }
        }
    }
}


问:
How to make a server wide filter on Tomcat?
At work, we've inherited this Java class which handles all SSO login operations. There's a FiltroSegurancaGlobal.class which is mapped to *, forcing everything with a annotation

```<code>@WebFilter(urlPatterns = { "/*" })
</code>```

The class is deployed in a JAR with a few other classes to handle the whole SSO operation.

Recently I was requested to install and configure a git server for internal purposes, I found a really interesting solution GitBlit, which works like a charm.

Here's the thing, when I deployed it to the server somehow some requests are slipping through the filter. That seemed impossible so I changed the filter to nothing:

```<code>public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("filter hit");
}
</code>```

While the whole application wasn't being loaded, the user wasn't being redirected to the log in page, none of the resources (css,js) were loaded, but the (index) still shows in the developer tools windows with some of the page.

How is this possible? Wasn't a deployed filter with "/*" urlPatterns supposed to filter ALL requests?

As mentioned bellow I tried changing the urlPatters using annotation first, then server's web.xml later:

```<code>@WebFilter({"/", "*", "/*"})
</code>```

and then

```<code><filter-mapping>
  <filter-name>FiltroSegurancaGlobal</filter-name>
  <url-pattern>/*</url-pattern>
  <url-pattern>*</url-pattern>
  <url-pattern>/</url-pattern>
</filter-mapping>
</code>```

Nothing has changed.

By probing chrome I realized that the only file that seemed to come through the server was angular.js, by searching their github I found a NgController.java file which has an odd code segment:

```<code>public void renderHead(IHeaderResponse response) {
        // add Google AngularJS reference
        response.renderJavascriptReference(new ResourceReference(NgController.class, "angular.js"));
</code>```

The actual class also implements IHeaderContributor, which is from the Apache Wicket package, not sure if this helps to troubleshoot the issue.

I also found this question which mentions FORWARD requests, I'm gonna try checking this out, but I'm still not sure what's going on.

Just a minor addition, it seems that the correct solution would be using Tomcat's Valve but that question has a comment mentioning that: [Filters]'re only overridable whenever webapp's /WEB-INF/web.xml has another one with same filter name.

Which is an impossible situation in this case, since I doubt the deployed app has a filter map with the same filter name.

I'll probably migrate the whole thing to the Valve Component to make sure it's server wide, but I still don't understand what's going on in this particular scenario.

ALSO: I forgot to mention that GitBlit has a console output when a user tries to connect, ex: 2016-05-13 13:53:38 [INFO ] 0 repositories identified with calculated folder sizes in 5 msecs and I just noticed that the filter hit system.out.println is being executed AFTER it, meaning somehow the request from the browser is not passing through it.

答:
I had the same problem and although I didn't find any answer to this problems I did some tests myself and I came to the conclusion that the /* url mapping on Tomcat's web.xml means anything below the root context.

Suppose this is what you have deployed on your Tomcat:

```<code>/ (root application)
/myApp1
/myApp2
</code>```

If you then make a GET request to the URL /myApp1/users the filter won't be triggered because you are performing an operation on /myApp1 context.

If instead you make a GET request to the URL /myApp3/users then the filter will run, because now the context is /.

Unluckily, has I said, I have no source for this claim, apart from some personal tests and I don't quite understand how Tomcat default filters are supposed to work, so feel free to disprove me.

Body:
At work, we've inherited this Java class which handles all SSO login operations. There's a FiltroSegurancaGlobal.class which is mapped to *, forcing everything with a annotation

@WebFilter(urlPatterns = { "/*" })

The class is deployed in a JAR with a few other classes to handle the whole SSO operation.

Recently I was requested to install and configure a git server for internal purposes, I found a really interesting solution GitBlit, which works like a charm.

Here's the thing, when I deployed it to the server somehow some requests are slipping through the filter. That seemed impossible so I changed the filter to nothing:

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        System.out.println("filter hit");
}

While the whole application wasn't being loaded, the user wasn't being redirected to the log in page, none of the resources (css,js) were loaded, but the (index) still shows in the developer tools windows with some of the page.

How is this possible? Wasn't a deployed filter with "/*" urlPatterns supposed to filter ALL requests?

As mentioned bellow I tried changing the urlPatters using annotation first, then server's web.xml later:

@WebFilter({"/", "*", "/*"})

and then

<filter-mapping>
  <filter-name>FiltroSegurancaGlobal</filter-name>
  <url-pattern>/*</url-pattern>
  <url-pattern>*</url-pattern>
  <url-pattern>/</url-pattern>
</filter-mapping>

Nothing has changed.

By probing chrome I realized that the only file that seemed to come through the server was angular.js, by searching their github I found a NgController.java file which has an odd code segment:

public void renderHead(IHeaderResponse response) {
        // add Google AngularJS reference
        response.renderJavascriptReference(new ResourceReference(NgController.class, "angular.js"));

The actual class also implements IHeaderContributor, which is from the Apache Wicket package, not sure if this helps to troubleshoot the issue.

I also found this question which mentions FORWARD requests, I'm gonna try checking this out, but I'm still not sure what's going on.

Just a minor addition, it seems that the correct solution would be using Tomcat's Valve but that question has a comment mentioning that: [Filters]'re only overridable whenever webapp's /WEB-INF/web.xml has another one with same filter name.

Which is an impossible situation in this case, since I doubt the deployed app has a filter map with the same filter name.

I'll probably migrate the whole thing to the Valve Component to make sure it's server wide, but I still don't understand what's going on in this particular scenario.

ALSO: I forgot to mention that GitBlit has a console output when a user tries to connect, ex: 2016-05-13 13:53:38 [INFO ] 0 repositories identified with calculated folder sizes in 5 msecs and I just noticed that the filter hit system.out.println is being executed AFTER it, meaning somehow the request from the browser is not passing through it.

Body:
I had the same problem and although I didn't find any answer to this problems I did some tests myself and I came to the conclusion that the /* url mapping on Tomcat's web.xml means anything below the root context.

Suppose this is what you have deployed on your Tomcat:

/ (root application)
/myApp1
/myApp2

If you then make a GET request to the URL /myApp1/users the filter won't be triggered because you are performing an operation on /myApp1 context.

If instead you make a GET request to the URL /myApp3/users then the filter will run, because now the context is /.

Unluckily, has I said, I have no source for this claim, apart from some personal tests and I don't quite understand how Tomcat default filters are supposed to work, so feel free to disprove me.


问:
XSLT chaining or combining xsl:copy-of and xsl:copy
I've got the following two XSL transforms that I would like to chain together in one XSL file.

The first transform:

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="/">
  <xsl:copy-of select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>
</code>```

And the second transform (using the output of the first as input):

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/xs:schema/xs:element[@name='ServiceAuth']"/>
<xsl:template match="/xs:schema/xs:import[@namespace='http://www.somecompany.com/serviceAuth/ ']"/>
</xsl:stylesheet>
</code>```

What I'm aiming to accomplish with this, is to copy only the xs:schema node (and all it's children) from a WSDL whilst at the same time removing two nodes from inside the xs:schema node.

How do I chain these two together in one XSL or is there an even better way to accomplish the above objective?

Below is the WSDL input file that should serve as input to the first transform:

```<code><s0:definitions name="CBS_GetUpgradeEligibility" targetNamespace="http://www.somecompany.com/" xmlns:s0="http://schemas.xmlsoap.org/wsdl/" xmlns:s1="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:s2="http://www.somecompany.com/" xmlns:s3="http://schemas.xmlsoap.org/wsdl/soap/">
   <s0:types>
      <xs:schema targetNamespace="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:auth="http://www.somecompany.com/serviceAuth/" xmlns:cbs="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:esb="http://www.somecompany.com/esbTypes/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.somecompany.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
         <xs:import namespace="http://www.somecompany.com/esbTypes/" schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ESBTypes"/>
         <xs:import namespace="http://www.somecompany.com/serviceAuth/ " schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ServiceAuth"/>
         <xs:simpleType name="DESTINATION_MSISDN">
            <xs:restriction base="xs:string">
               <xs:maxLength value="11"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_13">
            <xs:restriction base="xs:string">
               <xs:maxLength value="13"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_20">
            <xs:restriction base="xs:string">
               <xs:maxLength value="20"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:complexType name="UPGRADE_TYPE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isber" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="isreward" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="code" type="cbs:STRING_20"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="QUALIFIES_FOR_UPGRADE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isaveragespentmet" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="is7daypremature" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradepossible" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradeduedate" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="0" name="UpgradeType" type="cbs:UPGRADE_TYPE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
         <xs:element name="ServiceAuth">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="Username" type="auth:Username"/>
                  <xs:element name="Password" type="auth:Password"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityRequest">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="TSORequest" type="cbs:getUpgradeEligibilityRequestElement"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityResponse">
            <xs:complexType>
               <xs:sequence>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOID" type="esb:TSOID"/>
                  <xs:element name="TSOResponse" type="cbs:getUpgradeEligibilityResponseElement"/>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOResult" type="esb:TSOResult"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:complexType name="getUpgradeEligibilityRequestElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getUpgradeEligibilityResponseElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
               <xs:element maxOccurs="1" minOccurs="1" name="QualifiesForUpgrade" type="cbs:QUALIFIES_FOR_UPGRADE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
      </xs:schema>
   </s0:types>
   <s0:message name="GetUpgradeEligibilityRequestMessage">
      <s0:part element="s1:ServiceAuth" name="ServiceAuth"/>
      <s0:part element="s1:GetUpgradeEligibilityRequest" name="GetUpgradeEligibilityRequest"/>
   </s0:message>
   <s0:message name="GetUpgradeEligibilityResponseMessage">
      <s0:part element="s1:GetUpgradeEligibilityResponse" name="GetUpgradeEligibilityResponse"/>
   </s0:message>
   <s0:portType name="esbTransactionPort">
      <s0:operation name="getUpgradeEligibility">
         <s0:input message="s2:GetUpgradeEligibilityRequestMessage"/>
         <s0:output message="s2:GetUpgradeEligibilityResponseMessage"/>
      </s0:operation>
   </s0:portType>
   <s0:binding name="getUpgradeEligibilityEsbTransactionBinding" type="s2:esbTransactionPort">
      <s3:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <s0:operation name="getUpgradeEligibility">
         <s3:operation soapAction="" style="document"/>
         <s0:input>
            <s3:header message="s2:GetUpgradeEligibilityRequestMessage" part="ServiceAuth" use="literal"/>
            <s3:body parts="GetUpgradeEligibilityRequest" use="literal"/>
         </s0:input>
         <s0:output>
            <s3:body parts="GetUpgradeEligibilityResponse" use="literal"/>
         </s0:output>
      </s0:operation>
   </s0:binding>
   <s0:service name="getUpgradeEligibilityEsbTransactionBindingQSService">
      <s0:port binding="s2:getUpgradeEligibilityEsbTransactionBinding" name="getUpgradeEligibilityEsbTransactionBindingQSPort">
         <s3:address location="http://VESB14-PRD:7701/CBS_GetUpgradeEligibility"/>
      </s0:port>
   </s0:service>
</s0:definitions>
</code>```

答:
Since the first stylesheet is just selecting what is processed by the 2nd -- not doing any transformation itself, can't you just change copy-of to apply-templates, and import the 2nd stylesheet ? ( You don't really need to do any chaining. )</p>

```<code><xsl:stylesheet
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:s0="http://schemas.xmlsoap.org/wsdl/">

<xsl:import href="stylesheet-2.xsl" />

<xsl:template match="/">
   <xsl:apply-templates select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>
</code>```

Body:
I've got the following two XSL transforms that I would like to chain together in one XSL file.

The first transform:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="/">
  <xsl:copy-of select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>

And the second transform (using the output of the first as input):

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:s0="http://schemas.xmlsoap.org/wsdl/">
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/xs:schema/xs:element[@name='ServiceAuth']"/>
<xsl:template match="/xs:schema/xs:import[@namespace='http://www.somecompany.com/serviceAuth/ ']"/>
</xsl:stylesheet>

What I'm aiming to accomplish with this, is to copy only the xs:schema node (and all it's children) from a WSDL whilst at the same time removing two nodes from inside the xs:schema node.

How do I chain these two together in one XSL or is there an even better way to accomplish the above objective?

Below is the WSDL input file that should serve as input to the first transform:

<s0:definitions name="CBS_GetUpgradeEligibility" targetNamespace="http://www.somecompany.com/" xmlns:s0="http://schemas.xmlsoap.org/wsdl/" xmlns:s1="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:s2="http://www.somecompany.com/" xmlns:s3="http://schemas.xmlsoap.org/wsdl/soap/">
   <s0:types>
      <xs:schema targetNamespace="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:auth="http://www.somecompany.com/serviceAuth/" xmlns:cbs="http://www.somecompany.com/CBS_GetUpgradeEligibility/" xmlns:esb="http://www.somecompany.com/esbTypes/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.somecompany.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
         <xs:import namespace="http://www.somecompany.com/esbTypes/" schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ESBTypes"/>
         <xs:import namespace="http://www.somecompany.com/serviceAuth/ " schemaLocation="http://127.0.0.1:5000/CBS_GetUpgradeEligibility?SCHEMA%2FVodacom+Services%2FInfrastructure+Services%2FSchemas%2FXSD_ServiceAuth"/>
         <xs:simpleType name="DESTINATION_MSISDN">
            <xs:restriction base="xs:string">
               <xs:maxLength value="11"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_13">
            <xs:restriction base="xs:string">
               <xs:maxLength value="13"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:simpleType name="STRING_20">
            <xs:restriction base="xs:string">
               <xs:maxLength value="20"/>
            </xs:restriction>
         </xs:simpleType>
         <xs:complexType name="UPGRADE_TYPE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isber" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="isreward" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="code" type="cbs:STRING_20"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="QUALIFIES_FOR_UPGRADE_DETAILS">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="isaveragespentmet" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="is7daypremature" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradepossible" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="1" name="upgradeduedate" type="cbs:STRING_13"/>
               <xs:element maxOccurs="1" minOccurs="0" name="UpgradeType" type="cbs:UPGRADE_TYPE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
         <xs:element name="ServiceAuth">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="Username" type="auth:Username"/>
                  <xs:element name="Password" type="auth:Password"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityRequest">
            <xs:complexType>
               <xs:sequence>
                  <xs:element name="TSORequest" type="cbs:getUpgradeEligibilityRequestElement"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:element name="GetUpgradeEligibilityResponse">
            <xs:complexType>
               <xs:sequence>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOID" type="esb:TSOID"/>
                  <xs:element name="TSOResponse" type="cbs:getUpgradeEligibilityResponseElement"/>
                  <xs:element maxOccurs="1" minOccurs="1" name="TSOResult" type="esb:TSOResult"/>
               </xs:sequence>
            </xs:complexType>
         </xs:element>
         <xs:complexType name="getUpgradeEligibilityRequestElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getUpgradeEligibilityResponseElement">
            <xs:sequence>
               <xs:element maxOccurs="1" minOccurs="1" name="MSISDN" type="cbs:DESTINATION_MSISDN"/>
               <xs:element maxOccurs="1" minOccurs="1" name="QualifiesForUpgrade" type="cbs:QUALIFIES_FOR_UPGRADE_DETAILS"/>
            </xs:sequence>
         </xs:complexType>
      </xs:schema>
   </s0:types>
   <s0:message name="GetUpgradeEligibilityRequestMessage">
      <s0:part element="s1:ServiceAuth" name="ServiceAuth"/>
      <s0:part element="s1:GetUpgradeEligibilityRequest" name="GetUpgradeEligibilityRequest"/>
   </s0:message>
   <s0:message name="GetUpgradeEligibilityResponseMessage">
      <s0:part element="s1:GetUpgradeEligibilityResponse" name="GetUpgradeEligibilityResponse"/>
   </s0:message>
   <s0:portType name="esbTransactionPort">
      <s0:operation name="getUpgradeEligibility">
         <s0:input message="s2:GetUpgradeEligibilityRequestMessage"/>
         <s0:output message="s2:GetUpgradeEligibilityResponseMessage"/>
      </s0:operation>
   </s0:portType>
   <s0:binding name="getUpgradeEligibilityEsbTransactionBinding" type="s2:esbTransactionPort">
      <s3:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <s0:operation name="getUpgradeEligibility">
         <s3:operation soapAction="" style="document"/>
         <s0:input>
            <s3:header message="s2:GetUpgradeEligibilityRequestMessage" part="ServiceAuth" use="literal"/>
            <s3:body parts="GetUpgradeEligibilityRequest" use="literal"/>
         </s0:input>
         <s0:output>
            <s3:body parts="GetUpgradeEligibilityResponse" use="literal"/>
         </s0:output>
      </s0:operation>
   </s0:binding>
   <s0:service name="getUpgradeEligibilityEsbTransactionBindingQSService">
      <s0:port binding="s2:getUpgradeEligibilityEsbTransactionBinding" name="getUpgradeEligibilityEsbTransactionBindingQSPort">
         <s3:address location="http://VESB14-PRD:7701/CBS_GetUpgradeEligibility"/>
      </s0:port>
   </s0:service>
</s0:definitions>

Body:
Since the first stylesheet is just selecting what is processed by the 2nd -- not doing any transformation itself, can't you just change copy-of to apply-templates, and import the 2nd stylesheet ? ( You don't really need to do any chaining. )

<xsl:stylesheet
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:s0="http://schemas.xmlsoap.org/wsdl/">

<xsl:import href="stylesheet-2.xsl" />

<xsl:template match="/">
   <xsl:apply-templates select="/s0:definitions/s0:types/xs:schema"/>
</xsl:template>
</xsl:stylesheet>


问:
Docker nginx 502 bad gateway for GET/Post requests but not websocket
There have been various similar cases here on stackoverflow but they're pretty much all refer to incorrect ports or using localhost as the IP instead of the docker-machine ip.

The vue.js app connects perfectly fine to the websocket and works. However, the GET requests to 192.168.99.100:8080/meows and other endpoints all hit the nginx 502 bad gateway. Manually accessing the endpoints (instead of vue.js) also hit 502 bad gateway.

The ip's are properly set. Ports are the same everywhere :8080. endpoints have the correct http verband all have an nginx upstream pointing at the server location /..{}. Yet no problems connecting to the network, all data passing through no problem.

EDIT: Im running windows 7 with the docker-toolbox because my windows version doesnt have the whole virtualization thing. No further configuration after installation has been done.

The architecture is the following:

docker-compose

```<code>version: "3.6"

services:
  meow:
    build: "."
    command: "meow-service"
    depends_on:
      - "postgres"
      - "nats"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
      NATS_ADDRESS: "nats:4222"
  query:
    build: "."
    command: "query-service"
    depends_on:
      - "postgres"
      - "nats"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
      NATS_ADDRESS: "nats:4222"
      ELASTICSEARCH_ADDRESS: "elasticsearch:9200"
  pusher:
    build: "."
    command: "pusher-service"
    depends_on:
      - "nats"
    environment:
      NATS_ADDRESS: "nats:4222"
  postgres:
    build: "./postgres"
    restart: "always"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
  nats:
    image: "nats-streaming:0.9.2"
    restart: "always"
  elasticsearch:
    image: 'docker.elastic.co/elasticsearch/elasticsearch:6.2.3'
  nginx:
    build: "./nginx"
    ports:
      - "8080:80"
    depends_on:
      - "meow"
      - "query"
      - "pusher"
</code>```

nginx.conf:

```<code>user nginx;
worker_processes 1;

events {
  worker_connections 1024;
}

http {
  upstream meows_POST {
    server meow:8080;
  }

  upstream meows_GET {
    server query:8080;
  }

  upstream search_GET {
    server query:8080;
  }

  upstream pusher {
    server pusher:8080;
  }

  server {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    add_header Access-Control-Allow-Origin *;

    location /meows {
      limit_except GET POST OPTIONS {
        deny all;
      }
      proxy_pass http://meows_$request_method;
    }

    location /search {
      limit_except GET OPTIONS {
        deny all;
      }
      proxy_pass http://search_GET;
    }

    location /pusher {
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_pass http://pusher;
    }
  }
}
</code>```

And to show that the go application also uses the correct ports, the following is the port listening for

```<code>func newRouter() (router *mux.Router) {
    router = mux.NewRouter()
    router.HandleFunc("/meows", listMeowsHandler).
        Methods("GET")
    router.HandleFunc("/search", searchMeowsHandler).
        Methods("GET")
    return
}

router := newRouter()
if err := http.ListenAndServe(":8080", router); err != nil {
    log.Fatal(err)
}
</code>```

答:
Instead of:

```<code>ports:
  - "8080"
</code>```

in every docker-compose service, try:

```<code>ports:
  // I assume your containers operate on 8080 port
  - "8080:8080"
</code>```

By specifying just 8080 you assign container's port 8080 to your host's random port. I believe you don't want that. You can verify that with docker-compose ps.

Also why do you change the default port everywhere to 8080? With Docker it's not necessary, you can simply map the port to a different port on the host side, eg:

```<code>ports:
    - "8080:80"
</code>```

Remember that containers talk to each other using their ports and those ports don't need to be published. You only publish ports you want to access "from the outside world".

Body:
There have been various similar cases here on stackoverflow but they're pretty much all refer to incorrect ports or using localhost as the IP instead of the docker-machine ip.

The vue.js app connects perfectly fine to the websocket and works. However, the GET requests to 192.168.99.100:8080/meows and other endpoints all hit the nginx 502 bad gateway. Manually accessing the endpoints (instead of vue.js) also hit 502 bad gateway.

The ip's are properly set. Ports are the same everywhere :8080. endpoints have the correct http verband all have an nginx upstream pointing at the server location /..{}. Yet no problems connecting to the network, all data passing through no problem.

EDIT: Im running windows 7 with the docker-toolbox because my windows version doesnt have the whole virtualization thing. No further configuration after installation has been done.

The architecture is the following:

docker-compose

version: "3.6"

services:
  meow:
    build: "."
    command: "meow-service"
    depends_on:
      - "postgres"
      - "nats"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
      NATS_ADDRESS: "nats:4222"
  query:
    build: "."
    command: "query-service"
    depends_on:
      - "postgres"
      - "nats"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
      NATS_ADDRESS: "nats:4222"
      ELASTICSEARCH_ADDRESS: "elasticsearch:9200"
  pusher:
    build: "."
    command: "pusher-service"
    depends_on:
      - "nats"
    environment:
      NATS_ADDRESS: "nats:4222"
  postgres:
    build: "./postgres"
    restart: "always"
    environment:
      POSTGRES_DB: "meower"
      POSTGRES_USER: "meower"
      POSTGRES_PASSWORD: "123456"
  nats:
    image: "nats-streaming:0.9.2"
    restart: "always"
  elasticsearch:
    image: 'docker.elastic.co/elasticsearch/elasticsearch:6.2.3'
  nginx:
    build: "./nginx"
    ports:
      - "8080:80"
    depends_on:
      - "meow"
      - "query"
      - "pusher"

nginx.conf:

user nginx;
worker_processes 1;

events {
  worker_connections 1024;
}

http {
  upstream meows_POST {
    server meow:8080;
  }

  upstream meows_GET {
    server query:8080;
  }

  upstream search_GET {
    server query:8080;
  }

  upstream pusher {
    server pusher:8080;
  }

  server {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    add_header Access-Control-Allow-Origin *;

    location /meows {
      limit_except GET POST OPTIONS {
        deny all;
      }
      proxy_pass http://meows_$request_method;
    }

    location /search {
      limit_except GET OPTIONS {
        deny all;
      }
      proxy_pass http://search_GET;
    }

    location /pusher {
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_pass http://pusher;
    }
  }
}

And to show that the go application also uses the correct ports, the following is the port listening for

func newRouter() (router *mux.Router) {
    router = mux.NewRouter()
    router.HandleFunc("/meows", listMeowsHandler).
        Methods("GET")
    router.HandleFunc("/search", searchMeowsHandler).
        Methods("GET")
    return
}

router := newRouter()
if err := http.ListenAndServe(":8080", router); err != nil {
    log.Fatal(err)
}

Body:
Instead of:

ports:
  - "8080"

in every docker-compose service, try:

ports:
  // I assume your containers operate on 8080 port
  - "8080:8080"

By specifying just 8080 you assign container's port 8080 to your host's random port. I believe you don't want that. You can verify that with docker-compose ps.

Also why do you change the default port everywhere to 8080? With Docker it's not necessary, you can simply map the port to a different port on the host side, eg:

ports:
    - "8080:80"

Remember that containers talk to each other using their ports and those ports don't need to be published. You only publish ports you want to access "from the outside world".


问:
WPF Image HESREST：0x88982F72
This picture can't be displayed

Anything else will do.
Image URL: http://eyy250.com/132.jpg

```<code><Grid>
    <Image Source="http://eyy250.com/132.jpg"></Image>

</Grid>
</code>```

答:
Achieve your scenario by setting CreateOptions as IgnoreColorProfile in BitMap as like below code.

```<code>        <Image Width="300" Height="300">
            <Image.Source>
                <BitmapImage CreateOptions="IgnoreColorProfile" UriSource="http://eyy250.com/132.jpg"/>
            </Image.Source>
        </Image>
</code>```

Title: WPF Image HESREST：0x88982F72

Body:
This picture can't be displayed

Anything else will do.
Image URL: http://eyy250.com/132.jpg

<Grid>
    <Image Source="http://eyy250.com/132.jpg"></Image>

</Grid>

Body:
Achieve your scenario by setting CreateOptions as IgnoreColorProfile in BitMap as like below code.

        <Image Width="300" Height="300">
            <Image.Source>
                <BitmapImage CreateOptions="IgnoreColorProfile" UriSource="http://eyy250.com/132.jpg"/>
            </Image.Source>
        </Image>


问:
JAVA_HOME is not defined correctly on Ubuntu?
I am trying to install some software (Shibboleth) in Ubuntu 14.04. I already have Java 7 OpenJDK installed in /usr/lib/jvm/, and I have these lines in /usr/environment

```<code>JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64"
export JAVA_HOME
</code>```

If I type echo $JAVA_HOME I correctly get /usr/lib/jvm/java-7-openjdk-amd64.
However, when I try to install Shibboleth I always get Error: JAVA_HOME is not defined correctly. Cannot execute java.

Interestingly, if I type java command it works (it refers to /usr/lib/java which is a link to the right one). However, when I try to run bash bin/install.sh of Shibboleth, I get the JAVA_HOME error

I already tried setting JAVA_HOME to the jre folder with same result. Any ideas?

答:
from Ubantu terminal execute:

```<code>export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/
</code>```

to test maven run:

```<code>mvn --version
</code>```

it will give output:

```<code>Maven home: /usr/share/maven
Java version: 1.7.x.xxx, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-7-openjdk-amd64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-47-generic", arch: "amd64", family: "unix"
</code>```

Body:
I am trying to install some software (Shibboleth) in Ubuntu 14.04. I already have Java 7 OpenJDK installed in /usr/lib/jvm/, and I have these lines in /usr/environment

JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64"
export JAVA_HOME

If I type echo $JAVA_HOME I correctly get /usr/lib/jvm/java-7-openjdk-amd64.
However, when I try to install Shibboleth I always get Error: JAVA_HOME is not defined correctly. Cannot execute java.

Interestingly, if I type java command it works (it refers to /usr/lib/java which is a link to the right one). However, when I try to run bash bin/install.sh of Shibboleth, I get the JAVA_HOME error

I already tried setting JAVA_HOME to the jre folder with same result. Any ideas?

Body:
from Ubantu terminal execute:

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/

to test maven run:

mvn --version

it will give output:

Maven home: /usr/share/maven
Java version: 1.7.x.xxx, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-7-openjdk-amd64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-47-generic", arch: "amd64", family: "unix"


问:
Weird arguments in UIColor colorWithRed:green:blue:alpha:
When checking this method, I was expecting for red, green and blue to be in the 0-255 range. Instead, it's in 0-1.

Am I the only one who thinks this is weird?

Is there any reason not o use the more common 0-255 values for RGB, or even hex numbers (as in html)?

答:
In my opinion this is not weird. Both 0-255 and 0.0-1.0 levels are widely used in different platforms. You can always convert that by using something like this:</p>

```#define FLOAT_COLOR_VALUE(n) (n)/255.0```

Body:
In my opinion this is not weird. Both 0-255 and 0.0-1.0 levels are widely used in different platforms. You can always convert that by using something like this:

#define FLOAT_COLOR_VALUE(n) (n)/255.0


问:
React hooks: How to write variables in functional components that in class components were initialized in the constructor
I'm using uppy with React and they normally initialize uppy as a global variable. In React, they allow to do this instead:

class MyComponent extends React.Component {
  constructor (props) {
    super(props)
    this.uppy = Uppy()
      .use(Transloadit, {})
  }

  componentWillUnmount () {
    this.uppy.close()
  }

  render () {
    return <StatusBar uppy={this.uppy} />
  }
}
```

<p>How do I write this in a functional component with hooks? The naive approach would be the following (didn't expect it to work after reading this issue):</p>

<pre class="lang-js prettyprint-override"><code>const MyComponent = () => {
  const uppy = Uppy()
    .use(Transloadit, {})

  useEffect(() => {
    return () => uppy.close()
  })

  return <StatusBar uppy={uppy} />
}
</code>```

PS: It needs to be done inside of the functional component because I'm using some props in an uppy.use method.

答:
Variables in functional components can be initialized using useRef hook (read more here). Also since you only want to run the cleanup function on unmounting and not on every re-render, you should pass an empty [] as the second argument to useEffect

```<code>const MyComponent = () => {
  const uppy = useRef(Uppy()
    .use(Transloadit, {}))

  useEffect(() => {
    return () => uppy.current.close()
  }, [])

  return <StatusBar uppy={uppy.current} />
}
</code>```

Body:
I'm using uppy with React and they normally initialize uppy as a global variable. In React, they allow to do this instead:

class MyComponent extends React.Component {
  constructor (props) {
    super(props)
    this.uppy = Uppy()
      .use(Transloadit, {})
  }

  componentWillUnmount () {
    this.uppy.close()
  }

  render () {
    return <StatusBar uppy={this.uppy} />
  }
}

How do I write this in a functional component with hooks? The naive approach would be the following (didn't expect it to work after reading this issue):

const MyComponent = () => {
  const uppy = Uppy()
    .use(Transloadit, {})

  useEffect(() => {
    return () => uppy.close()
  })

  return <StatusBar uppy={uppy} />
}

PS: It needs to be done inside of the functional component because I'm using some props in an uppy.use method.

Body:
Variables in functional components can be initialized using useRef hook (read more here). Also since you only want to run the cleanup function on unmounting and not on every re-render, you should pass an empty [] as the second argument to useEffect

const MyComponent = () => {
  const uppy = useRef(Uppy()
    .use(Transloadit, {}))

  useEffect(() => {
    return () => uppy.current.close()
  }, [])

  return <StatusBar uppy={uppy.current} />
}


问:
Trying to set color point by column value in CartoDB
This is my first time using CartoDB. My dataset is a simulation of the behaviour of users arround the campus. My rows have latitude, longitude and the class column depending of the cluster in which the user is.

I saw an option to visualize the animation of the behaviour (cartodb transforms the data into a time lapse), but I'm trying to see the points colored by the class value. In the platform, there is an option to do that, but when I choose the "animation" mode then I can't choose any of the columns to set the color.

I show you an image:

However, if I choose the "By points" mode, I can display the points color by the class column value.

Is there anyone who has had the same problem? Do you have any recommendation?

答:
I think the problem is on the column type, you need your column to be a string to be offered as a value, so maybe you want add a column to your SELECT statement on the DATA tab to reclassify your clusters. If you rename then you can also show them on the legend can reflect a better name for your clusters:

```<code>select *,
       case cluster
         when 1 then 'Cluster 1'
         when 2 then 'Cluster 2'
         else 'unknown'
       end as cluster_named
from my_table
</code>```

Something around that should help to convert cluster numeric field into a string one, then you'll see it offered to animate by that value.

Disclaimer: I work at CARTO

Body:
I think the problem is on the column type, you need your column to be a string to be offered as a value, so maybe you want add a column to your SELECT statement on the DATA tab to reclassify your clusters. If you rename then you can also show them on the legend can reflect a better name for your clusters:

select *,
       case cluster
         when 1 then 'Cluster 1'
         when 2 then 'Cluster 2'
         else 'unknown'
       end as cluster_named
from my_table

Something around that should help to convert cluster numeric field into a string one, then you'll see it offered to animate by that value.

Disclaimer: I work at CARTO


问:
Delete array using list
I want to implement endpoint for deleting a list if IDs

```<code>    @DeleteMapping("/contracts/remove/{id}")
    public ResponseEntity<?> remove(@PathVariable Integer id) {
        contractsTerminalsService.delete(id);
        return ResponseEntity.noContent().build();
    }
</code>```

How I can send a list of IDs like this:

```<code>POST /api/contracts/bulk_delete
with body { ids: [1,5,6] }
</code>```

What is the proper way to implement this?

答:
Just use List<Integer> and your request should be like  /api/contracts/bulk_delete/1,5,6

```<code>@DeleteMapping("/contracts/bulk_delete/{ids}")
public ResponseEntity<?> remove(@PathVariable List<Integer> ids) {
    // Do whatever you want with id
    return ResponseEntity.noContent().build();
}
</code>```

For more reference visit Passing an Array or List to @Pathvariable - Spring/Java

Title: Delete array using list

Body:
I want to implement endpoint for deleting a list if IDs

    @DeleteMapping("/contracts/remove/{id}")
    public ResponseEntity<?> remove(@PathVariable Integer id) {
        contractsTerminalsService.delete(id);
        return ResponseEntity.noContent().build();
    }

How I can send a list of IDs like this:

POST /api/contracts/bulk_delete
with body { ids: [1,5,6] }

What is the proper way to implement this?

Body:
Just use List<Integer> and your request should be like  /api/contracts/bulk_delete/1,5,6

@DeleteMapping("/contracts/bulk_delete/{ids}")
public ResponseEntity<?> remove(@PathVariable List<Integer> ids) {
    // Do whatever you want with id
    return ResponseEntity.noContent().build();
}

For more reference visit Passing an Array or List to @Pathvariable - Spring/Java


问:
Pandas Lambda Function with Nan Support
I am trying to write a lambda function in Pandas that checks to see if Col1 is a Nan and if so, uses another column's data.  I have having trouble getting code (below) to compile/execute correctly.

```<code>import pandas as pd
import numpy as np
df=pd.DataFrame({ 'Col1' : [1,2,3,np.NaN], 'Col2': [7, 8, 9, 10]})
df2=df.apply(lambda x: x['Col2'] if x['Col1'].isnull() else x['Col1'], axis=1)
</code>```

Does anyone have any good idea on how to write a solution like this with a lambda function or have I exceeded the abilities of lambda?  If not, do you have another solution?  Thanks.

答:
Within pandas 0.24.2, I use

```<code>df.apply(lambda x: x['col_name'] if x[col1] is np.nan else expressions_another, axis=1)
</code>```

because pd.isnull() doesn't work.

in my work,I found the following phenomenon,

No running results:

```<code>df['prop'] = df.apply(lambda x: (x['buynumpday'] / x['cnumpday']) if pd.isnull(x['cnumpday']) else np.nan, axis=1)
</code>```

Results exist:

```<code>df['prop'] = df.apply(lambda x: (x['buynumpday'] / x['cnumpday']) if x['cnumpday'] is not np.nan else np.nan, axis=1)
</code>```

So far, I still don't know the deeper reason, but I have these experiences, for object, use [is np.nan()] or pd.isna(). For a float, use np.isnan() or pd.isna().

Title: Pandas Lambda Function with Nan Support

Body:
I am trying to write a lambda function in Pandas that checks to see if Col1 is a Nan and if so, uses another column's data.  I have having trouble getting code (below) to compile/execute correctly.

import pandas as pd
import numpy as np
df=pd.DataFrame({ 'Col1' : [1,2,3,np.NaN], 'Col2': [7, 8, 9, 10]})
df2=df.apply(lambda x: x['Col2'] if x['Col1'].isnull() else x['Col1'], axis=1)

Does anyone have any good idea on how to write a solution like this with a lambda function or have I exceeded the abilities of lambda?  If not, do you have another solution?  Thanks.

Body:
Within pandas 0.24.2, I use

df.apply(lambda x: x['col_name'] if x[col1] is np.nan else expressions_another, axis=1)

because pd.isnull() doesn't work.

in my work,I found the following phenomenon,

No running results:

df['prop'] = df.apply(lambda x: (x['buynumpday'] / x['cnumpday']) if pd.isnull(x['cnumpday']) else np.nan, axis=1)

Results exist:

df['prop'] = df.apply(lambda x: (x['buynumpday'] / x['cnumpday']) if x['cnumpday'] is not np.nan else np.nan, axis=1)

So far, I still don't know the deeper reason, but I have these experiences, for object, use [is np.nan()] or pd.isna(). For a float, use np.isnan() or pd.isna().


答:
You can achieve like this.</p>

```<code>> const MyComponent = (props) => {   let uppy;
>
>   useEffect(() => {
>     uppy = Uppy()
>     .use(Transloadit, {});
>     return () => uppy.close()   }, [])
>
>   return <StatusBar uppy={uppy} /> }
</code>```

Title: React hooks: How to write variables in functional components that in class components were initialized in the constructor

Body:
You can achieve like this.

> const MyComponent = (props) => {   let uppy;
>
>   useEffect(() => {
>     uppy = Uppy()
>     .use(Transloadit, {});
>     return () => uppy.close()   }, [])
>
>   return <StatusBar uppy={uppy} /> }


问:
Hitting "Something went wrong!" with desktop version of APIC Test & Monitor
Using the v1.0.0 desktop client, downloaded from here as per this: -

IBM API Connect Test and Monitor

I'm trying/failing to hit a local RESTful endpoint, which is running on the same Mac as that hosting the APIC T&M client.

This is what I see from APIC T&M: -

```<code>Something went wrong!

Failed to fetch your request; most likely due to network error or invalid hostname.
</code>```

and, in my endpoint's debug: -

```<code>http2: server: error reading preface from client [::1]:55968: read tcp [::1]:8443->[::1]:55968: read: connection reset by peer
</code>```

I've also tried changing the URL to: -

```<code>https://127.0.0.1:8443/v1/instances
</code>```

but to no avail.

I CAN hit the same endpoint using cURL, openSSL, Postman, Insomnia, SoapUI, Firefox and Chrome, so I don't believe it's the endpoint but .....

Looking at the options to debug the APIC T&M client ...

答:
Based on the provided URL, I suspect the issue you described is caused by the use of HTTPS without a valid certificate. The app currently relies on Chromium Root Certificate Policy to validate SSL certificates.

The developer team is currently working on a feature that enables users to ignore unrecognised/self-signed SSL certificates and should be available in the next release.

Disclaimer: I'm a member of the IBM API Connect Test and Monitor development team.

Body:
Using the v1.0.0 desktop client, downloaded from here as per this: -

IBM API Connect Test and Monitor

I'm trying/failing to hit a local RESTful endpoint, which is running on the same Mac as that hosting the APIC T&M client.

This is what I see from APIC T&M: -

Something went wrong!

Failed to fetch your request; most likely due to network error or invalid hostname.

and, in my endpoint's debug: -

http2: server: error reading preface from client [::1]:55968: read tcp [::1]:8443->[::1]:55968: read: connection reset by peer

I've also tried changing the URL to: -

https://127.0.0.1:8443/v1/instances

but to no avail.

I CAN hit the same endpoint using cURL, openSSL, Postman, Insomnia, SoapUI, Firefox and Chrome, so I don't believe it's the endpoint but .....

Looking at the options to debug the APIC T&M client ...


问:
How to remove TextInputLayout drawable padding?
I am using ExitText inside TextInputLayout and have enable ``

```<code>app:passwordToggleEnabled="true"
</code>```

And getting Toggle view as below

I want to remove Right Padding of the toggle but somehow not able to.
I have all set everything 0dp, but no success.

```<code><com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    android:layout_margin="0dp"
    android:padding="0dp">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:layout_margin="0dp"
        android:drawablePadding="0dp"/>

</com.google.android.material.textfield.TextInputLayout>
</code>```

There are some naive solutions like setting negative margin, but as I don't know the size of padding I can't do that either. Any suggestion?

答:
Try this :</p>

```<code> <android.support.design.widget.TextInputLayout
                                android:id="@+id/tilPassword"
                                style="@style/text_input_layout_style"
                                app:passwordToggleEnabled="true">

                            <android.support.design.widget.TextInputEditText
                                    android:id="@+id/etPassword"
                                    style="@style/text_input_edit_text_without_border_style"
                                    android:contentDescription="Password"
                                    android:maxLength="@integer/pass_max"
                                    android:digits="@string/textPasswordDigits"
                                    android:drawableEnd="@drawable/drawable_ic_eyes"
                                    android:drawablePadding="@dimen/padding_small"
                                    android:inputType="textPassword"
                                    android:textCursorDrawable="@null"
                                    android:hint="@string/label_password"/>

    </android.support.design.widget.TextInputLayout>
</code>```

Body:
I am using ExitText inside TextInputLayout and have enable ``

app:passwordToggleEnabled="true"

And getting Toggle view as below

I want to remove Right Padding of the toggle but somehow not able to.
I have all set everything 0dp, but no success.

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    android:layout_margin="0dp"
    android:padding="0dp">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="0dp"
        android:layout_margin="0dp"
        android:drawablePadding="0dp"/>

</com.google.android.material.textfield.TextInputLayout>

There are some naive solutions like setting negative margin, but as I don't know the size of padding I can't do that either. Any suggestion?

Body:
Try this :

 <android.support.design.widget.TextInputLayout
                                android:id="@+id/tilPassword"
                                style="@style/text_input_layout_style"
                                app:passwordToggleEnabled="true">

                            <android.support.design.widget.TextInputEditText
                                    android:id="@+id/etPassword"
                                    style="@style/text_input_edit_text_without_border_style"
                                    android:contentDescription="Password"
                                    android:maxLength="@integer/pass_max"
                                    android:digits="@string/textPasswordDigits"
                                    android:drawableEnd="@drawable/drawable_ic_eyes"
                                    android:drawablePadding="@dimen/padding_small"
                                    android:inputType="textPassword"
                                    android:textCursorDrawable="@null"
                                    android:hint="@string/label_password"/>

    </android.support.design.widget.TextInputLayout>


问:
How to fix "astimezone() cannot be applied to a naive datetime"
Is possible to get a specific problem with Debian OS to use astimezone() ?
I use the same code in Python 3 with both OS : Ubuntu and Debian.

The first is OK to use

The second get an error with the same instruction

LOCAL_TIMEZONE = datetime.datetime.now().astimezone().tzinfo

debian error :
"ValueError: astimezone() cannot be applied to a naive datetime"

ubuntu works well

If there is anyone else that faced this and know what it is just reading what is here, well, would be nice if you tell me, I would be glad.
Thanks in advance!

答:
I'm on Ubuntu and I get same error, on Python 3.5.

I think it's something in system locale settings.
pytz can solve this, but simpler solutions might exist:

```<code>import datetime as dt
import pytz

t = dt.datetime.now()
local_tz = pytz.timezone("Europe/Rome")

>>> print(local_tz.localize(t))
2019-05-31 12:09:48.199220+02:00

>>> print(local_tz.localize(t).tzinfo)
Europe/Rome

>>> print(local_tz.localize(t).astimezone(pytz.UTC))
2019-05-31 10:09:48.199220+00:00
</code>```

Body:
I'm on Ubuntu and I get same error, on Python 3.5.

I think it's something in system locale settings.
pytz can solve this, but simpler solutions might exist:

import datetime as dt
import pytz

t = dt.datetime.now()
local_tz = pytz.timezone("Europe/Rome")

>>> print(local_tz.localize(t))
2019-05-31 12:09:48.199220+02:00

>>> print(local_tz.localize(t).tzinfo)
Europe/Rome

>>> print(local_tz.localize(t).astimezone(pytz.UTC))
2019-05-31 10:09:48.199220+00:00


问:
use operator< into template
I have a class template with paramter T, it is a custom container. T will could be a pointer or a reference.
Into this template i have a function with which i put my objects into the container. I want to put new elements in order with operator< but the problem is that i dont know if T is a pointer or a reference. if T is a pointer i have to dereference it, otherwise not.

I find std::is_pointer::value but i have a compiletime error when i try to create a container with int T-type.

void insert(int row, T t){
 int i = 0;
 for (; i < size && *t < *matrix[i]; i++) { //or t < matrix[i] if T is a reference
   new_matrix[i] = matrix[i];
}
```

答:
You might create additional methods to unify insert implementation, something like:

```<code>template <typename T> T& deref_ptr(T* p) { return *p; }
template <typename T> T& deref_ptr(T& p) { return p; }
</code>```

and then replace your *t (of pointer version) by (generic) deref_ptr(t) (and *matrix[i] by deref_ptr(matrix[i])):

```<code>void insert(int row, T t){
    for (int i = 0; i < size && deref_ptr(t) < deref_ptr(matrix[i]); i++) {
        new_matrix[i] = matrix[i];
    }
}
</code>```

Title: use operator< into template

Body:
You might create additional methods to unify insert implementation, something like:

template <typename T> T& deref_ptr(T* p) { return *p; }
template <typename T> T& deref_ptr(T& p) { return p; }

and then replace your *t (of pointer version) by (generic) deref_ptr(t) (and *matrix[i] by deref_ptr(matrix[i])):

void insert(int row, T t){
    for (int i = 0; i < size && deref_ptr(t) < deref_ptr(matrix[i]); i++) {
        new_matrix[i] = matrix[i];
    }
}


问:
How to install the mogenerator in Mac OS 10.14.4
I am not able to install mogenerator after writing in terminal for below command

```<code>brew install mogenerator
</code>```

and getting error like -bash: brew: command not found

can you please provide me step for all process?

答:
I am also getting this type of error mogenerator and solved it by following steps.

Open terminal and write command:: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

after doing step 1 if you get error like

==> /usr/bin/sudo /bin/rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress

==> /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools

xcode-select: error: invalid developer directory
  '/Library/Developer/CommandLineTools'

Failed during: /usr/bin/sudo /usr/bin/xcode-select --switch
  /Library/Developer/CommandLineTools

In your terminal write command ::   xcode-select --install

after doing step no 3 you will get one popUp , so click on install button

After completing installation , finally fire command to install mogenerator is. ::  brew install mogenerator

you will not getting error and mogenerator Installed Successfully

Reference Link : https://docs.brew.sh/Installation

Body:
I am not able to install mogenerator after writing in terminal for below command

brew install mogenerator

and getting error like -bash: brew: command not found

can you please provide me step for all process?


问:
How to check if a string contains a substring from an array and split it
I have an array of string like:

```<code>var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
</code>```

and I want to check if in my string
(e.g. var myString= "Cod.Fisc.FGDTFR34L16G643W") exists that substring (in this case "Cod.Fisc").
If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"]. How can I do that using JavaScript?

答:
Make your array into a regular expression:

const matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"];
const myString = "Cod.Fisc.FGDTFR34L16G643W";

const splitRegex = new RegExp('('+matchCodFisc.join('|')+')\\w+', 'g');
console.log(splitRegex);
let result = splitRegex.exec(myString)

console.log(result[1])```

Body:
I have an array of string like:

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]

and I want to check if in my string
(e.g. var myString= "Cod.Fisc.FGDTFR34L16G643W") exists that substring (in this case "Cod.Fisc").
If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"]. How can I do that using JavaScript?


问:
Integrate angular js directive inside angular 7 component
Is it possible to integrate Angular js directive inside Angular 7 component at the runtime. The Angular js is a separate project module with its own folder stucture.This folder structure includes directives as well. Can these angular js directives be imported into Angular 7 application by providing the directive's file path and used in Angular 7 component template. Kindly suggest if there is a way to do this. </p>

答:
This is NOT recommended. The architectures and life cycles of both are very different and you are just increasing the chances of errors, time and effort by doing so.

To answer your question: Yes, there is a way to do it as you can manipulate the DOM using any JS lib/framework and by using your ng7's @ViewChild/templateRefs to gain control of the element, but you will face issues while updating data to/from Angular7.

I'd highly suggest you make a new ng2+ component and import the code from your old project and work on it to make it into an Angular2+ component.