问:
Why is delaying the task not executing it fully or blocking the UI?
```<code>private async Task<string> httpClient(CancellationToken cancelToken)
{
    HttpClient hc = new HttpClient();

    hc.Timeout = new TimeSpan(0, 0, 10);

    //Task.Delay(5000).Wait(); using this one, it blocks the UI thread
    //await Task.Delay(5000); using this one, it doesn't execute the task after delay

    if (cancelToken.IsCancellationRequested)
    {
        return null;
    }

    HttpResponseMessage response = await hc.GetAsync(new Uri("http://google.com/"));

    response.EnsureSuccessStatusCode();

    string responseData = await response.Content.ReadAsStringAsync();

    return responseData;
}
</code>```

This is my async task and I have an issue trying to use delay inside of it. I have tried two methods and both seem to cause an issue with the task. Tried researching but couldn't find a way to fix my issue. Any help is appreciated

Other part of the code:

```<code>private async void Test()
{
    string response = await httpClient(token);
    Console.WriteLine("response: " + response);
}

private void button1_Click(object sender, EventArgs e)
{
    Task t = new Task(Test);
    t.Start();
    Console.WriteLine("task started");
    t.Wait();
    Console.WriteLine("task finished");
}
</code>```

答:
The problem is here:

```<code>private async void Test()
{
    string response = await httpClient(token);
    Console.WriteLine("response: " + response);
}
</code>```

As soon as you've made something async void you've completely removed any ability to track status. Your new Task(Test); is using new Task(Action), which will report completion as soon as the code first returns to the caller - i.e. at the first non-complete await (in your case: the Task.Delay). To do what you want, you should really be using the Task.Run(Func<Task>) API (or avoiding Task.Run / Task.Start completely, relying on the async plumbing itself), with a private async Task Test() method.

Your event handler could then be:

```<code>private async void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("about to start task");
    var t = Task.Run(Test);
    Console.WriteLine("task started");
    await t;
    Console.WriteLine("task finished");
}
</code>```

or to avoid the extra thread (as noted by Nkosi):

```<code>private async void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("about to start task");
    var t = Test();
    Console.WriteLine("task started");
    await t;
    Console.WriteLine("task finished");
}
</code>```

Body:
private async Task<string> httpClient(CancellationToken cancelToken)
{
    HttpClient hc = new HttpClient();

    hc.Timeout = new TimeSpan(0, 0, 10);

    //Task.Delay(5000).Wait(); using this one, it blocks the UI thread
    //await Task.Delay(5000); using this one, it doesn't execute the task after delay

    if (cancelToken.IsCancellationRequested)
    {
        return null;
    }

    HttpResponseMessage response = await hc.GetAsync(new Uri("http://google.com/"));

    response.EnsureSuccessStatusCode();

    string responseData = await response.Content.ReadAsStringAsync();

    return responseData;
}

This is my async task and I have an issue trying to use delay inside of it. I have tried two methods and both seem to cause an issue with the task. Tried researching but couldn't find a way to fix my issue. Any help is appreciated

Other part of the code:

private async void Test()
{
    string response = await httpClient(token);
    Console.WriteLine("response: " + response);
}

private void button1_Click(object sender, EventArgs e)
{
    Task t = new Task(Test);
    t.Start();
    Console.WriteLine("task started");
    t.Wait();
    Console.WriteLine("task finished");
}

Body:
The problem is here:

private async void Test()
{
    string response = await httpClient(token);
    Console.WriteLine("response: " + response);
}

As soon as you've made something async void you've completely removed any ability to track status. Your new Task(Test); is using new Task(Action), which will report completion as soon as the code first returns to the caller - i.e. at the first non-complete await (in your case: the Task.Delay). To do what you want, you should really be using the Task.Run(Func<Task>) API (or avoiding Task.Run / Task.Start completely, relying on the async plumbing itself), with a private async Task Test() method.

Your event handler could then be:

private async void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("about to start task");
    var t = Task.Run(Test);
    Console.WriteLine("task started");
    await t;
    Console.WriteLine("task finished");
}

or to avoid the extra thread (as noted by Nkosi):

private async void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine("about to start task");
    var t = Test();
    Console.WriteLine("task started");
    await t;
    Console.WriteLine("task finished");
}


来源: stackexchange

问:
How to extract nested values from JSON received from GoogleDistanceMatrix API in Java?
Trying to parse the following JSON return to java usable code:

```<code>{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361951
               },
               "duration" : {
                  "text" : "3 hours 51 mins",
                  "value" : 13876
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

      // Parse the whole JSON result.
      JSONObject o1 =(JSONObject)JSONValue.parse(outputString);

      JSONArray a1 = (JSONArray) o1.get("rows");//2
      for (int i = 0; i < a1.size(); i++) {
          JSONObject o2 = (JSONObject) a1.get(i);//3
          JSONArray a2 = (JSONArray) o2.get("elements");//4
          for (int j = 0; j < a2.size(); j++) {
              JSONObject o3 = (JSONObject) a2.get(j);//3
              JSONArray a3 = (JSONArray) o3.get("distance");//4
              for(int k =0; k < a3.size(); k++) {
              System.out.println(((JSONObject) a3.get(k)).get(
                      "text").toString());//5
              }

          }

      }
</code>```

I would like to access text value of distance and also text value of duration . I found code to access distance and duration but when I added the third for loop following the example of the old ones I get this expection

```<code>Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
</code>```

At this line:

```<code>   JSONArray a3 = (JSONArray) o3.get("distance");//4
</code>```

Any help or suggestions on how do it in other ways? Thanks

答:
Use JSONObject because its not array

```<code>JSONObject a3 = (JSONObject) o3.get("distance");
</code>```

then

```<code>  String text=a3.getString("text");
  String value=a3.getString("value");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to parse the following JSON return to java usable code:

{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361951
               },
               "duration" : {
                  "text" : "3 hours 51 mins",
                  "value" : 13876
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

      // Parse the whole JSON result.
      JSONObject o1 =(JSONObject)JSONValue.parse(outputString);

      JSONArray a1 = (JSONArray) o1.get("rows");//2
      for (int i = 0; i < a1.size(); i++) {
          JSONObject o2 = (JSONObject) a1.get(i);//3
          JSONArray a2 = (JSONArray) o2.get("elements");//4
          for (int j = 0; j < a2.size(); j++) {
              JSONObject o3 = (JSONObject) a2.get(j);//3
              JSONArray a3 = (JSONArray) o3.get("distance");//4
              for(int k =0; k < a3.size(); k++) {
              System.out.println(((JSONObject) a3.get(k)).get(
                      "text").toString());//5
              }

          }

      }

I would like to access text value of distance and also text value of duration . I found code to access distance and duration but when I added the third for loop following the example of the old ones I get this expection

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

At this line:

   JSONArray a3 = (JSONArray) o3.get("distance");//4

Any help or suggestions on how do it in other ways? Thanks

Body:
Use JSONObject because its not array

JSONObject a3 = (JSONObject) o3.get("distance");

then

  String text=a3.getString("text");
  String value=a3.getString("value");


问:
User Input to Array and then compare it to a random number?
I'm trying to make a classic lottery style code, where the objective is for the user to choose ten numbers to play with, and then those numbers are compared to a randomly generated number.

So far I got this:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
        Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
        Console.WriteLine("Go ahead and type them in.");

        int[] lotteri = new int[10]; //Array to catch ten numbers input.

        for (int i=0; i<lotteri.Length; i++)
            lotteri[i] = int.Parse(Console.ReadLine());

        Console.WriteLine("Very good! Now we'll see if you won anything!");

        Random randomNumber = new Random(1-100);

        Console.ReadKey();
    }
}
</code>```

That's as far as I got, I think the array is doing what it should (collecting the user input ten times before moving on).

The MAIN PROBLEM for me now is that I want the program to compare those numbers in the array to a randomly chosen number, and if either of those ten user input numbers match with the randomly generated number to tell the user that they've won (or if it doesn't, that they lost). I just can't seem to get it to work!

Secondary problem, but that I'm trying to learn is handling methods better, so if anyone got any tip on how to use the array in a method and then get it to main, that'd be very appreciated as well!

答:
Program is as follows:</p>

```<code>    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
            Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
            Console.WriteLine("Go ahead and type them in.");

            int[] lotteri = new int[10]; //Array to catch ten numbers input.
            for (int i = 0; i < lotteri.Length; i++)
            {
                lotteri[i] = int.Parse(Console.ReadLine());
            }

            Console.WriteLine("Very good! Now we'll see if you won anything!");

            Random rnd = new Random();
            int rnumber = rnd.Next(1, 100);
            bool isWin = false;
            isWin = lotteri.Contains(rnumber);

            Console.WriteLine("Lottery number is::" + rnumber);

            if (isWin)
            {
                Console.WriteLine("Very good! Now we'll see if you won anything!");
            }
            else
            {
                Console.WriteLine("Sorry...Better luck next time!!!");
            }

            Console.ReadKey();
        }
        catch (FormatException ex)
        {
            Console.WriteLine("Only number are allowed.");
        }
        catch
        {
            Console.WriteLine("Something went wrong.");
        }
        Console.ReadKey();
    }
</code>```

Body:
I'm trying to make a classic lottery style code, where the objective is for the user to choose ten numbers to play with, and then those numbers are compared to a randomly generated number.

So far I got this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
        Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
        Console.WriteLine("Go ahead and type them in.");

        int[] lotteri = new int[10]; //Array to catch ten numbers input.

        for (int i=0; i<lotteri.Length; i++)
            lotteri[i] = int.Parse(Console.ReadLine());

        Console.WriteLine("Very good! Now we'll see if you won anything!");

        Random randomNumber = new Random(1-100);

        Console.ReadKey();
    }
}

That's as far as I got, I think the array is doing what it should (collecting the user input ten times before moving on).

The MAIN PROBLEM for me now is that I want the program to compare those numbers in the array to a randomly chosen number, and if either of those ten user input numbers match with the randomly generated number to tell the user that they've won (or if it doesn't, that they lost). I just can't seem to get it to work!

Secondary problem, but that I'm trying to learn is handling methods better, so if anyone got any tip on how to use the array in a method and then get it to main, that'd be very appreciated as well!

Body:
Program is as follows:

    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Hello and Welcome to the Programming Lottery!"); //Just greetings and instructions.
            Console.WriteLine("You'll now get to choose ten different numbers to play with. ");
            Console.WriteLine("Go ahead and type them in.");

            int[] lotteri = new int[10]; //Array to catch ten numbers input.
            for (int i = 0; i < lotteri.Length; i++)
            {
                lotteri[i] = int.Parse(Console.ReadLine());
            }

            Console.WriteLine("Very good! Now we'll see if you won anything!");

            Random rnd = new Random();
            int rnumber = rnd.Next(1, 100);
            bool isWin = false;
            isWin = lotteri.Contains(rnumber);

            Console.WriteLine("Lottery number is::" + rnumber);

            if (isWin)
            {
                Console.WriteLine("Very good! Now we'll see if you won anything!");
            }
            else
            {
                Console.WriteLine("Sorry...Better luck next time!!!");
            }

            Console.ReadKey();
        }
        catch (FormatException ex)
        {
            Console.WriteLine("Only number are allowed.");
        }
        catch
        {
            Console.WriteLine("Something went wrong.");
        }
        Console.ReadKey();
    }


问:
Function on ngFor loop is called too many times
I have a checkbox component in a loop that makes a call to the controller to see if it's checked on initial load.  The list that it's looping through is only three items long but the function is being called 24 times.

HTML :

```<code>       <div class="MhSearchForm__Checkboxes">
        <div *ngFor="let propertyStatus of propertyStatuses" class="ml-3">
          <app-mh-check-box [option]="propertyStatus" [checked]="isChecked(propertyStatus)" (action)="statusSelected($event)"></app-mh-check-box>
        </div>
      </div>
</code>```

JS:

```<code>  isChecked(status) {
   console.log(status);
  }
</code>```

答: This is Normal, It is due to the fact that Angular will call that function every time the model changes, because it has no idea if the model change has an impact  That's expected and normal. </p>

Body:
I have a checkbox component in a loop that makes a call to the controller to see if it's checked on initial load.  The list that it's looping through is only three items long but the function is being called 24 times.

HTML :

          <app-mh-check-box [option]="propertyStatus" [checked]="isChecked(propertyStatus)" (action)="statusSelected($event)"></app-mh-check-box>

JS:

  isChecked(status) {
   console.log(status);
  }


问:
Split violin plot with ggplot2 with quantiles
In order to plot half densities, I am using the function described in this post: Split violin plot with ggplot2

However, when I want to draw the quantiles on the densities, like on a normal geom_violin() or geom_boxplot(), I obtain an error message.

I would also be interested in adding the number of observations above each half density.

Here is an example of what I would like to obtain:

```<code>data("diamonds")
library(ggplot2)

# Function described in a previous post
GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL){
  data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x))
  grp <- data[1,'group']
  newdata <- plyr::arrange(transform(data, x = if(grp%%2==1) xminv else xmaxv), if(grp%%2==1) y else -y)
  newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ])
  newdata[c(1,nrow(newdata)-1,nrow(newdata)), 'x'] <- round(newdata[1, 'x'])
  if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) {
    stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <=
                                              1))
    quantiles <- create_quantile_segment_frame(data, draw_quantiles)
    aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE]
    aesthetics$alpha <- rep(1, nrow(quantiles))
    both <- cbind(quantiles, aesthetics)
    quantile_grob <- GeomPath$draw_panel(both, ...)
    ggplot2:::ggname("geom_split_violin", grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob))
  }
  else {
    ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...))
  }
})

geom_split_violin <- function (mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...))
}

tmp <- diamonds[which(diamonds$cut %in% c("Fair", "Good")), ]

# Obtained plot
ggplot(tmp, aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin()

# Error due to internal functions (interleave, ...)
ggplot(tmp, aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin(draw_quantiles = 0.5)

# Function to return number of observation
give_n = function(x, y_up = y_upper) {
  data.frame(y = y_up * 1.06,
             label = paste("n =", length(x))
  )
}

# Code to add number of observations above each half density
new_plot = given_plot +
  # Give back only length of data
  stat_summary(fun.data = give_n, aes(x = as.factor(variable)), geom = "text")
</code>```

答:
We can make further adjustments to the function by @YAK, and add some adjustments to create_quantile_segment_frame:

```<code>GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin,
  draw_group = function(self, data, ..., draw_quantiles = NULL) {
    # Original function by Jan Gleixner (@jan-glx)
    # Adjustments by Wouter van der Bijl (@Axeman)
    data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x))
    grp <- data[1, "group"]
    newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y)
    newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ])
    newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"])
    if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) {
      stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1))
      quantiles <- create_quantile_segment_frame(data, draw_quantiles, split = TRUE, grp = grp)
      aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE]
      aesthetics$alpha <- rep(1, nrow(quantiles))
      both <- cbind(quantiles, aesthetics)
      quantile_grob <- GeomPath$draw_panel(both, ...)
      ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob))
    }
    else {
      ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...))
    }
  }
)

create_quantile_segment_frame <- function(data, draw_quantiles, split = FALSE, grp = NULL) {
  dens <- cumsum(data$density) / sum(data$density)
  ecdf <- stats::approxfun(dens, data$y)
  ys <- ecdf(draw_quantiles)
  violin.xminvs <- (stats::approxfun(data$y, data$xminv))(ys)
  violin.xmaxvs <- (stats::approxfun(data$y, data$xmaxv))(ys)
  violin.xs <- (stats::approxfun(data$y, data$x))(ys)
  if (grp %% 2 == 0) {
    data.frame(
      x = ggplot2:::interleave(violin.xs, violin.xmaxvs),
      y = rep(ys, each = 2), group = rep(ys, each = 2)
    )
  } else {
    data.frame(
      x = ggplot2:::interleave(violin.xminvs, violin.xs),
      y = rep(ys, each = 2), group = rep(ys, each = 2)
    )
  }
}

geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ...,
                              draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE,
                              show.legend = NA, inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position,
        show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...))
}
</code>```

Then simply plot:

```<code>ggplot(diamonds[which(diamonds$cut %in% c("Fair", "Good")), ],
       aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin(draw_quantiles = c(0.25, 0.5, 0.75))
</code>```

Body:
In order to plot half densities, I am using the function described in this post: Split violin plot with ggplot2

However, when I want to draw the quantiles on the densities, like on a normal geom_violin() or geom_boxplot(), I obtain an error message.

I would also be interested in adding the number of observations above each half density.

Here is an example of what I would like to obtain:

data("diamonds")
library(ggplot2)

# Function described in a previous post
GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin, draw_group = function(self, data, ..., draw_quantiles = NULL){
  data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x))
  grp <- data[1,'group']
  newdata <- plyr::arrange(transform(data, x = if(grp%%2==1) xminv else xmaxv), if(grp%%2==1) y else -y)
  newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ])
  newdata[c(1,nrow(newdata)-1,nrow(newdata)), 'x'] <- round(newdata[1, 'x'])
  if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) {
    stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <=
                                              1))
    quantiles <- create_quantile_segment_frame(data, draw_quantiles)
    aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE]
    aesthetics$alpha <- rep(1, nrow(quantiles))
    both <- cbind(quantiles, aesthetics)
    quantile_grob <- GeomPath$draw_panel(both, ...)
    ggplot2:::ggname("geom_split_violin", grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob))
  }
  else {
    ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...))
  }
})

geom_split_violin <- function (mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ..., draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...))
}

tmp <- diamonds[which(diamonds$cut %in% c("Fair", "Good")), ]

# Obtained plot
ggplot(tmp, aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin()

# Error due to internal functions (interleave, ...)
ggplot(tmp, aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin(draw_quantiles = 0.5)

# Function to return number of observation
give_n = function(x, y_up = y_upper) {
  data.frame(y = y_up * 1.06,
             label = paste("n =", length(x))
  )
}

# Code to add number of observations above each half density
new_plot = given_plot +
  # Give back only length of data
  stat_summary(fun.data = give_n, aes(x = as.factor(variable)), geom = "text")

Body:
We can make further adjustments to the function by @YAK, and add some adjustments to create_quantile_segment_frame:

GeomSplitViolin <- ggproto("GeomSplitViolin", GeomViolin,
  draw_group = function(self, data, ..., draw_quantiles = NULL) {
    # Original function by Jan Gleixner (@jan-glx)
    # Adjustments by Wouter van der Bijl (@Axeman)
    data <- transform(data, xminv = x - violinwidth * (x - xmin), xmaxv = x + violinwidth * (xmax - x))
    grp <- data[1, "group"]
    newdata <- plyr::arrange(transform(data, x = if (grp %% 2 == 1) xminv else xmaxv), if (grp %% 2 == 1) y else -y)
    newdata <- rbind(newdata[1, ], newdata, newdata[nrow(newdata), ], newdata[1, ])
    newdata[c(1, nrow(newdata) - 1, nrow(newdata)), "x"] <- round(newdata[1, "x"])
    if (length(draw_quantiles) > 0 & !scales::zero_range(range(data$y))) {
      stopifnot(all(draw_quantiles >= 0), all(draw_quantiles <= 1))
      quantiles <- create_quantile_segment_frame(data, draw_quantiles, split = TRUE, grp = grp)
      aesthetics <- data[rep(1, nrow(quantiles)), setdiff(names(data), c("x", "y")), drop = FALSE]
      aesthetics$alpha <- rep(1, nrow(quantiles))
      both <- cbind(quantiles, aesthetics)
      quantile_grob <- GeomPath$draw_panel(both, ...)
      ggplot2:::ggname("geom_split_violin", grid::grobTree(GeomPolygon$draw_panel(newdata, ...), quantile_grob))
    }
    else {
      ggplot2:::ggname("geom_split_violin", GeomPolygon$draw_panel(newdata, ...))
    }
  }
)

create_quantile_segment_frame <- function(data, draw_quantiles, split = FALSE, grp = NULL) {
  dens <- cumsum(data$density) / sum(data$density)
  ecdf <- stats::approxfun(dens, data$y)
  ys <- ecdf(draw_quantiles)
  violin.xminvs <- (stats::approxfun(data$y, data$xminv))(ys)
  violin.xmaxvs <- (stats::approxfun(data$y, data$xmaxv))(ys)
  violin.xs <- (stats::approxfun(data$y, data$x))(ys)
  if (grp %% 2 == 0) {
    data.frame(
      x = ggplot2:::interleave(violin.xs, violin.xmaxvs),
      y = rep(ys, each = 2), group = rep(ys, each = 2)
    )
  } else {
    data.frame(
      x = ggplot2:::interleave(violin.xminvs, violin.xs),
      y = rep(ys, each = 2), group = rep(ys, each = 2)
    )
  }
}

geom_split_violin <- function(mapping = NULL, data = NULL, stat = "ydensity", position = "identity", ...,
                              draw_quantiles = NULL, trim = TRUE, scale = "area", na.rm = FALSE,
                              show.legend = NA, inherit.aes = TRUE) {
  layer(data = data, mapping = mapping, stat = stat, geom = GeomSplitViolin, position = position,
        show.legend = show.legend, inherit.aes = inherit.aes,
        params = list(trim = trim, scale = scale, draw_quantiles = draw_quantiles, na.rm = na.rm, ...))
}

Then simply plot:

ggplot(diamonds[which(diamonds$cut %in% c("Fair", "Good")), ],
       aes(as.factor(color), carat, fill = cut)) +
  geom_split_violin(draw_quantiles = c(0.25, 0.5, 0.75))

ContentLicense: CC BY-SA 4.0


问:
DataTables combine detailed information and row reorder
I am trying to combine detailed information and row reorder using datatables
the sources are :
https://datatables.net/examples/api/row_details.html
and :
https://datatables.net/extensions/rowreorder/

while the details part work and i can drag the rows but it does not reorder them.

my code :

```<code>function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
    '<tr>'+
        '<td>Full name:</td>'+
        '<td>'+d.name+'</td>'+
    '</tr>'+
    '<tr>'+
        '<td>Salary:</td>'+
        '<td>'+d.salary+'</td>'+
    '</tr>'+
    '<tr>'+
        '<td>Extra info:</td>'+
        '<td>And any further details here (images etc)...</td>'+
    '</tr>'+
'</table>';
}

$(document).ready(function() {
var table = $('#example').DataTable( {
"rowReorder": true,

 "columns": [
        { "data": "seq" },
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "start date" },
        { "data": "salary" },
        {
            "className":      'details-control',

        }
    ],
 "columnDefs": [
 { targets: 0, visible: false },
            ]
} );

$('#example tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row( tr );

    if ( row.child.isShown() ) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child( format(row.data()) ).show();
        tr.addClass('shown');
    }
} );
} );
</code>```

my html :

```<code><table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Seq.</th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Start date</th>
            <th>Salary</th>
            <th></th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Seq.</th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Start date</th>
            <th>Salary</th>
            <th></th>
        </tr>
    </tfoot>
    <tbody>
        <tr>
            <td>2</td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
            <td></td>
        </tr>
        <tr>
            <td>22</td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
            <td></td>
        </tr>
        <tr>
            <td>6</td>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>2009/01/12</td>
            <td>$86,000</td>
            <td></td>
        </tr>
        <tr>
            <td>41</td>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>2012/03/29</td>
            <td>$433,060</td>
            <td></td>
        </tr>
        </tbody>
</table>
</code>```

any idea why the reordering fails?
i also loaded the necessary java scripts.

答:
Apparently it didn't work because you used columns.data option when your data source was HTML. This option needs to be used only when your data source is JavaScript array or provided via Ajax request.

See updated example for code and demonstration.

Body:
I am trying to combine detailed information and row reorder using datatables
the sources are :
https://datatables.net/examples/api/row_details.html
and :
https://datatables.net/extensions/rowreorder/

while the details part work and i can drag the rows but it does not reorder them.

my code :

function format ( d ) {
// `d` is the original data object for the row
return '
'+
    '
'+
        'Full name:	'+
        ''+d.name+'	'+
    '
'+
    '
'+
        'Salary:	'+
        ''+d.salary+'	'+
    '
'+
    '
'+
        'Extra info:	'+
        'And any further details here (images etc)...	'+
    '
'+
'
';
}

$(document).ready(function() {
var table = $('#example').DataTable( {
"rowReorder": true,

 "columns": [
        { "data": "seq" },
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "start date" },
        { "data": "salary" },
        {
            "className":      'details-control',

        }
    ],
 "columnDefs": [
 { targets: 0, visible: false },
            ]
} );

$('#example tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row( tr );

    if ( row.child.isShown() ) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child( format(row.data()) ).show();
        tr.addClass('shown');
    }
} );
} );

my html :

            Seq.
            Name
            Position
            Office
            Start date
            Salary

            Seq.
            Name
            Position
            Office
            Start date
            Salary

            2
            Tiger Nixon
            System Architect
            Edinburgh
            2011/04/25
            $320,800

            22
            Garrett Winters
            Accountant
            Tokyo
            2011/07/25
            $170,750

            6
            Ashton Cox
            Junior Technical Author
            San Francisco
            2009/01/12
            $86,000

            41
            Cedric Kelly
            Senior Javascript Developer
            Edinburgh
            2012/03/29
            $433,060

any idea why the reordering fails?
i also loaded the necessary java scripts.


问:
Enum values depending on controller site in thymeleaf
My enum:

```<code>public enum ADD_OR_EDIT {

    ADD("/user/add", "addForm"), EDIT("/user/edit", "editForm");

    private String thAction;
    private String thObject;

    ADD_OR_EDIT(String thAction, String thObject) {
        this.thAction = thAction;
        this.thObject = thObject;
    }
    //getters and setters ommited to clear view
}
</code>```

My controller line for edit

```<code>addAttribute("addOrEdit", ADD_OR_EDIT.EDIT);
</code>```

My controller line for add:

```<code>addAttribute("addOrEdit", ADD_OR_EDIT.ADD);
</code>```

The question is how to fix my thymeleaf form to get value depending on that.

For example:

```<code>   <form action="#" th:action="(@{addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${addOrEdit.thObject}"
      method="post">
</code>```

(This one doesn't work)

UPDATE:

The problem is with the second parameter of enum - thObject.

in add:

```<code>model.addAttribute("basicForm", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
</code>```

in edit:

```<code>model.addAttribute("editForm", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);
</code>```

Maybe the value of th:object is "addForm" instead of addForm and this cause an error.

UPDATE2:

This one works:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${basicForm})"
      method="post">
</code>```

This one works also:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${editForm})"
      method="post">
</code>```

So the case now is to connect them by enum like we did on thAction:
This doesnt work:

```<code><form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${{addOrEdit.thObject})"
      method="post">
</code>```

答:
use th:action="${addOrEdit.thAction}" instead of th:action="@{addOrEdit.thAction}"

update:

```<code>model.addAttribute("form", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
in edit:

model.addAttribute("form", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${form}"
      method="post">
</code>```

Body:
My enum:

public enum ADD_OR_EDIT {

    ADD("/user/add", "addForm"), EDIT("/user/edit", "editForm");

    private String thAction;
    private String thObject;

    ADD_OR_EDIT(String thAction, String thObject) {
        this.thAction = thAction;
        this.thObject = thObject;
    }
    //getters and setters ommited to clear view
}

My controller line for edit

addAttribute("addOrEdit", ADD_OR_EDIT.EDIT);

My controller line for add:

addAttribute("addOrEdit", ADD_OR_EDIT.ADD);

The question is how to fix my thymeleaf form to get value depending on that.

For example:

   <form action="#" th:action="(@{addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${addOrEdit.thObject}"
      method="post">

(This one doesn't work)

UPDATE:

The problem is with the second parameter of enum - thObject.

in add:

model.addAttribute("basicForm", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);

in edit:

model.addAttribute("editForm", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);

Maybe the value of th:object is "addForm" instead of addForm and this cause an error.

UPDATE2:

This one works:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${basicForm})"
      method="post">

This one works also:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${editForm})"
      method="post">

So the case now is to connect them by enum like we did on thAction:
This doesnt work:

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="(${{addOrEdit.thObject})"
      method="post">

Body:
use th:action="${addOrEdit.thAction}" instead of th:action="@{addOrEdit.thAction}"

update:

model.addAttribute("form", basicForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.ADD);
in edit:

model.addAttribute("form", editForm);
model.addAttribute("addOrEdit",ADD_OR_EDIT.EDIT);

<form action="#" th:action="(${addOrEdit.thAction})" class="form-horizontal form-narrow" th:object="${form}"
      method="post">


问:
SQlite3 context manager with file locking in python 2.7
Is this the good way to do file locking with re-entrance in a context manager under Python 2.7? I just want to be sure the rlock() is going to be effective so I could get a multi-threaded application to use a single database file.</p>

```<code>import sqlite3
import threading
import os

class ConnectionHolder:
    def __init__(self, connection):
        self.path = connection
        self.lock = threading.RLock()

    def __enter__(self):
        self.lock.acquire()
        self.connection = sqlite3.connect(self.path)
        self.cursor = self.connection .cursor()
        return self.cursor

    def __exit__(self, exc_class, exc, traceback):
        self.connection .commit()
        self.connection .close()
        self.lock.release()

conn_holder = ConnectionHolder(os.path.join(os.path.dirname(__file__), 'data/db/database.db'))

if __name__ == '__main__':
    with conn_holder as c:
        c.execute("SELECT * FROM 'sample_table'")
        result = c.fetchall()
        print result
</code>```

答: I finally fond in my code a place where I was running a long loop (about 2 minutes) before commiting. I correct this and, as @DB suggested, increase busy timeout to 30 seconds. Problem seem to be resolved. Thanks guys!</p>

Body:
Is this the good way to do file locking with re-entrance in a context manager under Python 2.7? I just want to be sure the rlock() is going to be effective so I could get a multi-threaded application to use a single database file.

import sqlite3
import threading
import os

class ConnectionHolder:
    def __init__(self, connection):
        self.path = connection
        self.lock = threading.RLock()

    def __enter__(self):
        self.lock.acquire()
        self.connection = sqlite3.connect(self.path)
        self.cursor = self.connection .cursor()
        return self.cursor

    def __exit__(self, exc_class, exc, traceback):
        self.connection .commit()
        self.connection .close()
        self.lock.release()

conn_holder = ConnectionHolder(os.path.join(os.path.dirname(__file__), 'data/db/database.db'))

if __name__ == '__main__':
    with conn_holder as c:
        c.execute("SELECT * FROM 'sample_table'")
        result = c.fetchall()
        print result


问:
Help with rotating xy-pixel coordinates, unsure about my function
Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.

Is this the right way to do it?:

Each pixels distance from the middlepoint is its radius.
Then in python code

```<code>new_x = avg_pos_x+(math.cos(math.radians(105))*radius)
new_y = avg_pos_y-(math.sin(math.radians(105))*radius)
</code>```

It seems to work, but then again some pixels appear to be a bit random.

Edit:
Forgot that to rotate each pixel 105 degrees I also calculated the angle between the middlepoint and pixel and added 105 degrees to that.

答:
Rather than figuring out where each pixel in the original image goes, you should figure out where each pixel in the new image came from.  You can do this just by rotating negative 105 degrees.

```<code>old_x = avg_pos_x+(math.cos(math.radians(-105))*radius)
old_y = avg_pos_y-(math.sin(math.radians(-105))*radius)
</code>```

Then copy the color of (old_x, old_y) to (x, y).  Here's where you could do interpolation if you like -- e.g. taking a weighted average color of the four pixels whose centers form a square containing (old_x, old_y).

By doing the transformation in reverse, you're sure to figure out the color for each pixel of the new image exactly once.  If you do it "forwards", some pixels in the new image will be hit more than once, and some won't be hit at all.  These pixels not being hit at all might be your "random" pixels -- holes in your final image that end up with a default color or somesuch.

ContentLicense: CC BY-SA 2.5

Body:
Ok I have a small set of pixels (a character) stored with xy-coordinates. Now I want to rotate the image around its middlepoint with, let's say, a 105 degrees.

Is this the right way to do it?:

Each pixels distance from the middlepoint is its radius.
Then in python code

new_x = avg_pos_x+(math.cos(math.radians(105))*radius)
new_y = avg_pos_y-(math.sin(math.radians(105))*radius)

It seems to work, but then again some pixels appear to be a bit random.

Edit:
Forgot that to rotate each pixel 105 degrees I also calculated the angle between the middlepoint and pixel and added 105 degrees to that.

Body:
Rather than figuring out where each pixel in the original image goes, you should figure out where each pixel in the new image came from.  You can do this just by rotating negative 105 degrees.

old_x = avg_pos_x+(math.cos(math.radians(-105))*radius)
old_y = avg_pos_y-(math.sin(math.radians(-105))*radius)

Then copy the color of (old_x, old_y) to (x, y).  Here's where you could do interpolation if you like -- e.g. taking a weighted average color of the four pixels whose centers form a square containing (old_x, old_y).

By doing the transformation in reverse, you're sure to figure out the color for each pixel of the new image exactly once.  If you do it "forwards", some pixels in the new image will be hit more than once, and some won't be hit at all.  These pixels not being hit at all might be your "random" pixels -- holes in your final image that end up with a default color or somesuch.


问:
EMR cluster monitoring configuration: Ganglia + InfluxDb
i have an EMR cluster. It is set up by terraform script

```<code>resource "aws_emr_cluster" "emr-test" {
   name = "emr-test"
   applications = [..., "Ganglia", ...]
   ...
}
</code>```

I would like to integrate ganglia with influxDb+Grafana. Found an example of cofiguration: example.

That requires to update gmetad.conf file on master node. Is that possible to do that with terraform script? emr step?

答:
You can use the bootstrap_action attribute to list actions that should run before Hadoop is started on the cluster nodes. You can also apply filters to only run those actions on the master node:</p>

```<code>resource "aws_emr_cluster" "emr-test" {

  ...

  bootstrap_action {
    path = "s3://your-bucket/update-gmetad.sh"
    name = "update-gmetad-on-master-node"
    args = ["instance.isMaster=true"]
  }

}
</code>```

Body:
i have an EMR cluster. It is set up by terraform script

resource "aws_emr_cluster" "emr-test" {
   name = "emr-test"
   applications = [..., "Ganglia", ...]
   ...
}

I would like to integrate ganglia with influxDb+Grafana. Found an example of cofiguration: example.

That requires to update gmetad.conf file on master node. Is that possible to do that with terraform script? emr step?

Body:
You can use the bootstrap_action attribute to list actions that should run before Hadoop is started on the cluster nodes. You can also apply filters to only run those actions on the master node:

resource "aws_emr_cluster" "emr-test" {

  ...

  bootstrap_action {
    path = "s3://your-bucket/update-gmetad.sh"
    name = "update-gmetad-on-master-node"
    args = ["instance.isMaster=true"]
  }

}


问:
How to run multiple perl Dancer2 apps in same nginx server
I figured that I can manage multiple apps using location in nginx.

But it seems like I cannot run multiple dancer2 apps in same server with different ports (like localhost:3000, localhost:4000).

Anyway I'm putting this here with a hope that experts can show me some light.

答:
When you have multiple Dancer2 applications, you can compose them together using either Plack::App::URLMap or the wrapper syntax for it available in Plack::Builder:

```<code>use MyApp::Main;
use MyApp::Admin;

builder {
    mount '/'      => MyApp::Main->to_app;
    mount '/admin' => MyApp::Admin->to_app;
};
</code>```

The effect of the mounting is that these applications will be completely separate and Plack::Builder will assure only the appropriate application handles a given request.

Source: http://advent.perldancer.org/2014/9

Body:
When you have multiple Dancer2 applications, you can compose them together using either Plack::App::URLMap or the wrapper syntax for it available in Plack::Builder:

use MyApp::Main;
use MyApp::Admin;

builder {
    mount '/'      => MyApp::Main->to_app;
    mount '/admin' => MyApp::Admin->to_app;
};

The effect of the mounting is that these applications will be completely separate and Plack::Builder will assure only the appropriate application handles a given request.

Source: http://advent.perldancer.org/2014/9


问:
Jenkins Groovy: What triggered job
```<code>Jenkins.instance.getAllItems(AbstractProject.class).each {it ->
println it.fullName
println it.getLastBuild().getTime()
}
</code>```

I want to get list of jobs triggered automatically. Now i have list of all jobs.

答:
You can get the Cause which triggered the build.

```<code>Jenkins.instance.getAllItems(AbstractProject.class).each {
  hudson.model.Cause cause = it.getLastBuild().getCause(hudson.model.Cause.class)
  println "Is triggered by user: " + (cause.class == hudson.model.Cause.UserIdCause.class)
}
</code>```

This class has many subclasses, which you can you to determine what triggered the build:

Cause.LegacyCodeCause, Cause.RemoteCause, Cause.UpstreamCause,
  Cause.UpstreamCause.DeeplyNestedUpstreamCause, Cause.UserCause,
  Cause.UserIdCause, SCMTrigger.SCMTriggerCause,
  TimerTrigger.TimerTriggerCause

Title: Jenkins Groovy: What triggered job

Body:
Jenkins.instance.getAllItems(AbstractProject.class).each {it ->
println it.fullName
println it.getLastBuild().getTime()
}

I want to get list of jobs triggered automatically. Now i have list of all jobs.

Body:
You can get the Cause which triggered the build.

Jenkins.instance.getAllItems(AbstractProject.class).each {
  hudson.model.Cause cause = it.getLastBuild().getCause(hudson.model.Cause.class)
  println "Is triggered by user: " + (cause.class == hudson.model.Cause.UserIdCause.class)
}

This class has many subclasses, which you can you to determine what triggered the build:

Cause.LegacyCodeCause, Cause.RemoteCause, Cause.UpstreamCause,
  Cause.UpstreamCause.DeeplyNestedUpstreamCause, Cause.UserCause,
  Cause.UserIdCause, SCMTrigger.SCMTriggerCause,
  TimerTrigger.TimerTriggerCause


问:
jersey - ClassNotFoundException org.glassfish.jersey.servlet.ServletContainer
When I deploy my rest api with jersey to a tomcat 7.0 server I get an error that has been discussed on stackoverflow quite often but I haven't been able to resolve it:

```<code>java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:495)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:477)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:113)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

Things I have checked:

Avoiding duplicate jersey versions

```<code><dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey2.version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey2.version}</version>
</dependency>
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>
</code>```

So, ServletContainer is definitely imported

I notice however in the dependency hierarchy that the jersey servlet container is also imported through another library (dropwizard-core -> dropwizard-jersey -> jersey-container-servlet: 2.16) and the versions differ (my version is 2.25.1). But it says omitted for conflict with 2.25.1

Where is Apache Tomcat v7.0 package library

My project was originally a pure Maven project and I added the Dynamic Web Project facet lateron. When I compare to a test project where I successfully tested a jersey rest api, I don't see the Apache Tomcat v7.0 libraries on my build path. In my test project I see

versus

WebContent/WEB-INF/lib is empty

As mentioned in this question the jersey libraries should be deployed to my WEB-INF/lib/ folder. I did Project -> Deployment Assembly -> Add -> Java Build Path Entries -> Maven Dependencies -> Finish. But as soon as I do Project -> Maven -> Update the step above is reset (i.e. I don't see Maven Dependencies in the Web Deployment Assembly anymore. Despite this is strange, in the successful test jersey project the lib folder is also empty.

EDIT

There is something more fundamental going wrong. In the successful jersey rest api, I got the subfolder structure

target

+---- generated-sources

+---- JerseyRestDemo-0.0.1-SNAPSHOT

+---- m2e-wtp

+---------- web-resources

+----------------- META-INF

+-----------------------maven

+---- maven-archiver

+--------- pom.properties

+---- test-classes

WebContent

+---- META-INF

+--------- MANIFEST.MF

+---- WEB-INF

+--------- lib

+----------web.xml

However, in my current project I just see

target

+----- generated-sources

+---------- annotations

+----- maven-status

+---------- maven-compiler-plugin

+--------------- compile

WebContent

+---- META-INF

+--------- MANIFEST.MF

+---- WEB-INF

+--------- lib

+----------web.xml

Thanks for your help

答: I converted the project again from maven to webapp following this post and then it worked</p>

Body:
When I deploy my rest api with jersey to a tomcat 7.0 server I get an error that has been discussed on stackoverflow quite often but I haven't been able to resolve it:

java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:495)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:477)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:113)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1133)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5362)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1700)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1690)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Things I have checked:

Avoiding duplicate jersey versions

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey2.version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey2.version}</version>
</dependency>
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>

So, ServletContainer is definitely imported

I notice however in the dependency hierarchy that the jersey servlet container is also imported through another library (dropwizard-core -> dropwizard-jersey -> jersey-container-servlet: 2.16) and the versions differ (my version is 2.25.1). But it says omitted for conflict with 2.25.1

Where is Apache Tomcat v7.0 package library

My project was originally a pure Maven project and I added the Dynamic Web Project facet lateron. When I compare to a test project where I successfully tested a jersey rest api, I don't see the Apache Tomcat v7.0 libraries on my build path. In my test project I see

versus

WebContent/WEB-INF/lib is empty

As mentioned in this question the jersey libraries should be deployed to my WEB-INF/lib/ folder. I did Project -> Deployment Assembly -> Add -> Java Build Path Entries -> Maven Dependencies -> Finish. But as soon as I do Project -> Maven -> Update the step above is reset (i.e. I don't see Maven Dependencies in the Web Deployment Assembly anymore. Despite this is strange, in the successful test jersey project the lib folder is also empty.

EDIT

There is something more fundamental going wrong. In the successful jersey rest api, I got the subfolder structure

target

+---- generated-sources

+---- JerseyRestDemo-0.0.1-SNAPSHOT

+---- m2e-wtp

+---------- web-resources

+----------------- META-INF

+-----------------------maven

+---- maven-archiver

+--------- pom.properties

+---- test-classes

WebContent

+---- META-INF

+--------- MANIFEST.MF

+---- WEB-INF

+--------- lib

+----------web.xml

However, in my current project I just see

target

+----- generated-sources

+---------- annotations

+----- maven-status

+---------- maven-compiler-plugin

+--------------- compile

WebContent

+---- META-INF

+--------- MANIFEST.MF

+---- WEB-INF

+--------- lib

+----------web.xml

Thanks for your help


问:
get auto_increment value, with build?
In my user registration routine, i have this code :

```<code>@user = User.new(attribs)

@user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots

success = @user && @user.save
if success && @user.errors.empty?
</code>```

This works great in creating an inventory and a user bound to that inventory. However, now i want to add a new inventory_item in every registration. I tried something like :

```<code>@user = User.new(attribs)

inventory = @user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots
InventoryItem.create(:inventory_id => inventory.id, :game_item => GameItem.find_by_name('Fist'), :is_equipped => 1)
</code>```

I thought it would not work (beacuse inventory is not built before inventory_item, and of course it didn't. What is the correct way to do that ?

答:
The best way of automatically adding an item to the inventory would be to do so in the inventory model. There, you can add an after_create method that will run every time an inventory is created. This way, you can remove this added layer of complexity from your model, and don't have to worry about the inventory id.

```<code>class Inventory < ActiveRecord::Base
  # other associations
  has_many :inventory_items

  after_create :create_starting_items

  protected
    def create_starting_items
      inventory_items.create do |item|
        item.game_item   = GameItem.find_by_name('Fist')
        item.is_equipped = true # This should likely be a boolean
      end
    end
end
</code>```

You can extend this functionality to the user model and create the inventory as an after_create as well, allowing the controller to only create the user and have the model(s) take care of associated inventories and items.

Title: get auto_increment value, with build?

Body:
In my user registration routine, i have this code :

@user = User.new(attribs)

@user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots

success = @user && @user.save
if success && @user.errors.empty?

This works great in creating an inventory and a user bound to that inventory. However, now i want to add a new inventory_item in every registration. I tried something like :

@user = User.new(attribs)

inventory = @user.build_inventory(:max_slots => 10) # create the user inventory, starting with 10 slots
InventoryItem.create(:inventory_id => inventory.id, :game_item => GameItem.find_by_name('Fist'), :is_equipped => 1)

I thought it would not work (beacuse inventory is not built before inventory_item, and of course it didn't. What is the correct way to do that ?

Body:
The best way of automatically adding an item to the inventory would be to do so in the inventory model. There, you can add an after_create method that will run every time an inventory is created. This way, you can remove this added layer of complexity from your model, and don't have to worry about the inventory id.

class Inventory < ActiveRecord::Base
  # other associations
  has_many :inventory_items

  after_create :create_starting_items

  protected
    def create_starting_items
      inventory_items.create do |item|
        item.game_item   = GameItem.find_by_name('Fist')
        item.is_equipped = true # This should likely be a boolean
      end
    end
end

You can extend this functionality to the user model and create the inventory as an after_create as well, allowing the controller to only create the user and have the model(s) take care of associated inventories and items.


问:
Kotlin generate constructor that sets default values to nulled arguments
Let's take the class of a data class:

```<code>data class User(
    val userNumber: Int = -1,
    val name: String,
    val userGroups; List<String> = emptyList(),
    val screenName: String = "new-user"
)
</code>```

When calling this function from Kotlin, it is pretty straightforward. I can simply use the named-argument syntax to do so. Calling from Java, I have to specify all values, or use the @JvmOverloads annotation, which generates the following constructors (in addition to the constructor that kotlin generates with the bit-mask for default values):

```<code>User(int userNumber, @NotNull String name, @NotNull List userGroups,
     @NotNull String screenName)
User(int userNumber, @NotNull String name, @NotNull List userGroups)
User(int userNumber, @NotNull String name)
User(@NotNull String name)
</code>```

Now, if I want to create a User object in Java equivalent to User(name="John Doe", userGroups=listOf("admin", "super") I can't do it with the above constructors. I CAN however do it if I put val userNumber: Int = -1 at the end in the data class declaration (the generation of constructors seems to depend on the order the optional arguments are defined in). Which is fine, because expecting kotlin to generate all permutations is going to heavily bloat some classes.

The biggest problem that tools like Jackson simply don't work as they have no idea which constructor to use (and not like I can annotate one of the generated ones specially).

So, is there a way to generate a (single) constructor like:

```<code>User(Integer userNumber, String name, List<String> userGroups, String screenName) {
    this.userNumber = (userNumber == null) ? -1 : userNumber;
    this.userGroups = (userGroups == null) ? Collections.emptyList() : userGroups;
    //...
}
</code>```

Currently I am using the above approach, but manually defining the constructors where I need them.

EDIT

I should clarify, creating a similar constructor doesn't work, obviously because both the signatures would clash on the JVM. This is what it would like in my case:

```<code>data class User(
    val userNumber: Int = -1,
    val name: String,
    val userGroups; List<String> = emptyList(),
    val screenName: String = "new-user"
) {
    companion object {
        @JvmStatic
        @JsonCreator
        fun constructionSupport(
            @JsonProperty("userNumber") userNumber : Int?,
            @JsonProperty("name") name : String,
            @JsonProperty("userGroups") userGroups : List<String>?,
            @JsonProperty("screenName") screenName : String?
        ) = User(
            userNumber = userNumber ?: -1,
            name = name,
            userGroups = userGroups ?: emptyList(),
            screenName = screenName ?: "new-user"
        )
    }
}
</code>```

Also note the redundancy where I have to write the default values for the properties twice. I Now that I look at it, I doubt there exists a solution for this. Maybe this is a good use-case for a kapt based side-project of mine :)

答:
Better solution is to add possibility to library understand Kotlin functional. For example, for Jackson exists jackson-module-kotlin. With this library we can use default arguments in data classes.

Example:

```<code>data class User(
        val userNumber: Int = -1,
        val name: String,
        val userGroups: List<String> = emptyList(),
        val screenName: String = "new-user"
)

fun main(args: Array<String>) {
    val objectMapper = ObjectMapper()
            .registerModule(KotlinModule())

    val testUser = User(userNumber = 5, name = "someName")

    val stringUser = objectMapper.writeValueAsString(testUser)
    println(stringUser)

    val parsedUser = objectMapper.readValue<User>(stringUser)
    println(parsedUser)

    assert(testUser == parsedUser) {
        println("something goes wrong")
    }
}
</code>```

Body:
Let's take the class of a data class:

data class User(
    val userNumber: Int = -1,
    val name: String,
    val userGroups; List<String> = emptyList(),
    val screenName: String = "new-user"
)

When calling this function from Kotlin, it is pretty straightforward. I can simply use the named-argument syntax to do so. Calling from Java, I have to specify all values, or use the @JvmOverloads annotation, which generates the following constructors (in addition to the constructor that kotlin generates with the bit-mask for default values):

User(int userNumber, @NotNull String name, @NotNull List userGroups,
     @NotNull String screenName)
User(int userNumber, @NotNull String name, @NotNull List userGroups)
User(int userNumber, @NotNull String name)
User(@NotNull String name)

Now, if I want to create a User object in Java equivalent to User(name="John Doe", userGroups=listOf("admin", "super") I can't do it with the above constructors. I CAN however do it if I put val userNumber: Int = -1 at the end in the data class declaration (the generation of constructors seems to depend on the order the optional arguments are defined in). Which is fine, because expecting kotlin to generate all permutations is going to heavily bloat some classes.

The biggest problem that tools like Jackson simply don't work as they have no idea which constructor to use (and not like I can annotate one of the generated ones specially).

So, is there a way to generate a (single) constructor like:

User(Integer userNumber, String name, List<String> userGroups, String screenName) {
    this.userNumber = (userNumber == null) ? -1 : userNumber;
    this.userGroups = (userGroups == null) ? Collections.emptyList() : userGroups;
    //...
}

Currently I am using the above approach, but manually defining the constructors where I need them.

EDIT

I should clarify, creating a similar constructor doesn't work, obviously because both the signatures would clash on the JVM. This is what it would like in my case:

data class User(
    val userNumber: Int = -1,
    val name: String,
    val userGroups; List<String> = emptyList(),
    val screenName: String = "new-user"
) {
    companion object {
        @JvmStatic
        @JsonCreator
        fun constructionSupport(
            @JsonProperty("userNumber") userNumber : Int?,
            @JsonProperty("name") name : String,
            @JsonProperty("userGroups") userGroups : List<String>?,
            @JsonProperty("screenName") screenName : String?
        ) = User(
            userNumber = userNumber ?: -1,
            name = name,
            userGroups = userGroups ?: emptyList(),
            screenName = screenName ?: "new-user"
        )
    }
}

Also note the redundancy where I have to write the default values for the properties twice. I Now that I look at it, I doubt there exists a solution for this. Maybe this is a good use-case for a kapt based side-project of mine :)

Body:
Better solution is to add possibility to library understand Kotlin functional. For example, for Jackson exists jackson-module-kotlin. With this library we can use default arguments in data classes.

Example:

data class User(
        val userNumber: Int = -1,
        val name: String,
        val userGroups: List<String> = emptyList(),
        val screenName: String = "new-user"
)

fun main(args: Array<String>) {
    val objectMapper = ObjectMapper()
            .registerModule(KotlinModule())

    val testUser = User(userNumber = 5, name = "someName")

    val stringUser = objectMapper.writeValueAsString(testUser)
    println(stringUser)

    val parsedUser = objectMapper.readValue<User>(stringUser)
    println(parsedUser)

    assert(testUser == parsedUser) {
        println("something goes wrong")
    }
}


问:
How to take backup of multiple stash?
I understand that we can use
    git stash show -p > stash.diff to take backup of a stash.

Now I want to take backup of at least 20 stashes. What's a good way to take backup of all the stashes?

答:
This snippet will list the IDs of all your existing stashes, and then create separate diff files for each.</p>

```<code>for stash in `git stash list | awk -F':' '{print $1}'`
do
    git stash show $stash -p > $stash.diff
done
</code>```

Title: How to take backup of multiple stash?

Body:
This snippet will list the IDs of all your existing stashes, and then create separate diff files for each.

for stash in `git stash list | awk -F':' '{print $1}'`
do
    git stash show $stash -p > $stash.diff
done


问:
Searching for string in the whole schema
I have Oracle database with many schemas. I'd like to find xyz string in all the tables in one specific schema. I've tried to do it as in accepted answer here (Search All Fields In All Tables For A Specific Value (Oracle)). Unfortunately, I get error:

3 ORA-00903: invalid table name
ORA-06512: at line 8 SQL.sql 30 2
```

<p>where line 8 is </p>

```SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||
```

How can I do this full search? I've also tried other googled solutions but none of them worked for me.

答:
Adapted from the other answer, run this query:

```<code>SELECT
    'SELECT '''|| owner||table_name||column_name|| ''' as locn, COUNT(*) FROM "' || owner || '"."' || table_name ||'" WHERE "'||column_name||'" = ''[VALUE YOURE LOOKING FOR HERE]'' UNION ALL'
FROM
  all_tab_columns
WHERE owner <> 'SYS' and data_type LIKE '%CHAR%'
</code>```

Replace the [VALUE YOURE LOOKING FOR HERE] with the value you're looking for. Replace the square brackets too. Do not touch any apostrophes.

Then run the query, and it'll produce a huge number of sql statements. Copy them out of your query tool results grid, paste them into the query area panel, delete the last union all and then run them. And wait. For a very long time. Eventually it'll produce a list of every table and column name, together with the count of the number of times that value you're looking for appears in that column

Body:
I have Oracle database with many schemas. I'd like to find xyz string in all the tables in one specific schema. I've tried to do it as in accepted answer here (Search All Fields In All Tables For A Specific Value (Oracle)). Unfortunately, I get error:

3 ORA-00903: invalid table name
ORA-06512: at line 8 SQL.sql 30 2

where line 8 is

SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||

How can I do this full search? I've also tried other googled solutions but none of them worked for me.

Body:
Adapted from the other answer, run this query:

SELECT
    'SELECT '''|| owner||table_name||column_name|| ''' as locn, COUNT(*) FROM "' || owner || '"."' || table_name ||'" WHERE "'||column_name||'" = ''[VALUE YOURE LOOKING FOR HERE]'' UNION ALL'
FROM
  all_tab_columns
WHERE owner <> 'SYS' and data_type LIKE '%CHAR%'

Replace the [VALUE YOURE LOOKING FOR HERE] with the value you're looking for. Replace the square brackets too. Do not touch any apostrophes.

Then run the query, and it'll produce a huge number of sql statements. Copy them out of your query tool results grid, paste them into the query area panel, delete the last union all and then run them. And wait. For a very long time. Eventually it'll produce a list of every table and column name, together with the count of the number of times that value you're looking for appears in that column


问:
Released apk is not able to login
I'm not able to login to released apk but debug apk is working fine. google_services.json file is missing to released apk i'm not getting why its happening like this. please some one help me to solve this. Below i listed my app-level dependencies.

```<code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:cardview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.wrapp.floatlabelededittext:library:0.0.6'
compile 'com.google.code.gson:gson:2.3.1'
compile 'de.greenrobot:eventbus:2.4.0'
compile 'com.github.nirhart:parallaxscroll:1.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.github.aakira:expandable-layout:1.4.2@aar'
compile 'de.hdodenhof:circleimageview:2.1.0'

compile 'com.loopj.android:android-async-http:1.4.6'

compile 'com.google.android.gms:play-services:8.1.0'
compile files('libs/opencsv-2.2.jar')
compile files('libs/google-play-services_lib.jar')
}
apply plugin: 'com.google.gms.google-services'
</code>```

project-level dependencies

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:2.1.0'
}
</code>```

i'm getting this error
E/TokenRequestor: You have wrong OAuth2 related configurations, please check. Detailed error: UNREGISTERED_ON_API_CONSOLE

please anybody help me out.

答:
You need to update the SHA-1 of release build from the Cloud Console.

Open https://console.cloud.google.com/

Select your application from the Drop Down at the top

APIs and Services -> Credentials

Add a key with SHA-1 for the release as well. (You might already having debug key registered)

Update: Add signing config to your app's build.gradle file and run singingReport from the gradle task.

```<code>android {
    ...
    signingConfigs {
        release {
            storeFile file("release-key.keystore")
            storePassword 'passwotd'
            keyAlias 'alias'
            keyPassword 'password'
        }
    }

    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }

        debug {
            debuggable true
        }
    }
}
...
</code>```

Now, click on the "Gradle" button in the Android studio on the right side panel.
Click "project name" -> ":app" -> "Tasks" -> "android" -> Double click "signingReport"

After it completes, click on the "Gradle Console" at the bottom right corner. It will show all the SHA-1 for all the keys.

Find the release build key's SHA-1.

Hope it helps

Title: Released apk is not able to login

Body:
I'm not able to login to released apk but debug apk is working fine. google_services.json file is missing to released apk i'm not getting why its happening like this. please some one help me to solve this. Below i listed my app-level dependencies.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:design:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:cardview-v7:22.2.0'
compile 'com.android.support:recyclerview-v7:22.2.0'
compile 'com.github.bumptech.glide:glide:3.6.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.wrapp.floatlabelededittext:library:0.0.6'
compile 'com.google.code.gson:gson:2.3.1'
compile 'de.greenrobot:eventbus:2.4.0'
compile 'com.github.nirhart:parallaxscroll:1.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.github.aakira:expandable-layout:1.4.2@aar'
compile 'de.hdodenhof:circleimageview:2.1.0'

compile 'com.loopj.android:android-async-http:1.4.6'

compile 'com.google.android.gms:play-services:8.1.0'
compile files('libs/opencsv-2.2.jar')
compile files('libs/google-play-services_lib.jar')
}
apply plugin: 'com.google.gms.google-services'

project-level dependencies

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:2.1.0'
}

i'm getting this error
E/TokenRequestor: You have wrong OAuth2 related configurations, please check. Detailed error: UNREGISTERED_ON_API_CONSOLE

please anybody help me out.

Body:
You need to update the SHA-1 of release build from the Cloud Console.

Open https://console.cloud.google.com/

Select your application from the Drop Down at the top

APIs and Services -> Credentials

Add a key with SHA-1 for the release as well. (You might already having debug key registered)

Update: Add signing config to your app's build.gradle file and run singingReport from the gradle task.

android {
    ...
    signingConfigs {
        release {
            storeFile file("release-key.keystore")
            storePassword 'passwotd'
            keyAlias 'alias'
            keyPassword 'password'
        }
    }

    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }

        debug {
            debuggable true
        }
    }
}
...

Now, click on the "Gradle" button in the Android studio on the right side panel.
Click "project name" -> ":app" -> "Tasks" -> "android" -> Double click "signingReport"

After it completes, click on the "Gradle Console" at the bottom right corner. It will show all the SHA-1 for all the keys.

Find the release build key's SHA-1.

Hope it helps


问:
iframe url content should aplly css styles using jquery
I need to change the iframe url css styles

```<code><iframe id="anil" width="400" height="480" src="https://getbootstrap.com/docs/3.3/examples/starter-template/"></iframe>
</code>```

Tried it using jquery but couldn't solve it

```<code>$("iframe").contents().find("body").css("background-color","yellow");
</code>```

答: You can not access by javascript the content of an iframe for security reasons.</p>

Body:
I need to change the iframe url css styles

Tried it using jquery but couldn't solve it

$("iframe").contents().find("body").css("background-color","yellow");


问:
Warning: file_get_contents failed to open stream: Connection timed out in includes/simple_html_dom.php on line 75
All of a sudden my cronjob has stopped working properly where it grabs content through file_get_contents and started giving the following warning and fatal error. Does anyone know why it is doing this?:</p>

```<code>Warning: file_get_contents(http://seriesgate.me/search/indv_episodes/The+Social+Network): failed to open stream: Connection timed out in includes/simple_html_dom.php on line 75

Fatal error:  Call to a member function find() on a non-object in includes/seriesgate.class.php on line 25
</code>```

答:
The Connection timed out error is a network problem for sure.

First, that's maybe your network connection problem take too long to get response from server. Please check your local/server/hosting internet connection; domain name, IP, port,... typo.

Secondly, that's maybe destination problem. For example, seriesgate.me is down for everyone, not only you. I know this question is 3 years old and the site is down. But this is best practice that you should check your destination when it's say something like Connection timed out.

Body:
All of a sudden my cronjob has stopped working properly where it grabs content through file_get_contents and started giving the following warning and fatal error. Does anyone know why it is doing this?:

Warning: file_get_contents(http://seriesgate.me/search/indv_episodes/The+Social+Network): failed to open stream: Connection timed out in includes/simple_html_dom.php on line 75

Fatal error:  Call to a member function find() on a non-object in includes/seriesgate.class.php on line 25


问:
Rails Active Model Json serializer: returning has_many record as has_one
I have a Active Model JSON Serializer for a model, which has a has_many relation, that I want to include in the JSON response.

I would like the record to be included as has_one instead of has_many record - to only include the first record:

```<code>class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_many :body_parts
end
</code>```

Here, body_parts should be returned as has one :body_part. What is the best way to do that?

答:
Isn't it as simple as:

```<code>class Person
  def body_part
    body_parts.first
  end

  # or

  has_one :body_part, -> { order(id: :asc) }
end

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_one :body_part
end
</code>```

In both cases you need to specific what exactly does it mean to be the first body part.

Body:
I have a Active Model JSON Serializer for a model, which has a has_many relation, that I want to include in the JSON response.

I would like the record to be included as has_one instead of has_many record - to only include the first record:

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_many :body_parts
end

Here, body_parts should be returned as has one :body_part. What is the best way to do that?

Body:
Isn't it as simple as:

class Person
  def body_part
    body_parts.first
  end

  # or

  has_one :body_part, -> { order(id: :asc) }
end

class PersonSerializer < ActiveModel::Serializer
  attributes :name, :symbol
  has_many :stats
  has_one :body_part
end

In both cases you need to specific what exactly does it mean to be the first body part.


问:
xml element prefix alternative
When writing the element, is there a way to address specific elements from some namespace by not using a prefix, e.g. some kind of long name that includes the namespace joined with the element name everywhere?
As I understand it, prefix is used as a convenience.

For example, can this

```<code><new:element xlmns:new='urn:some:custom:ns'>text...</new:element>
</code>```

be represented without prefix form?

答:
You can use an xmlns attribute on every element.

```<code><element xlmns='urn:some:custom:ns'>text...</element>
</code>```

… although I believe this approach prevents you from using attributes from a namespace other than the one the element belongs to.

Title: xml element prefix alternative

Body:
When writing the element, is there a way to address specific elements from some namespace by not using a prefix, e.g. some kind of long name that includes the namespace joined with the element name everywhere?
As I understand it, prefix is used as a convenience.

For example, can this

<new:element xlmns:new='urn:some:custom:ns'>text...</new:element>

be represented without prefix form?

Body:
You can use an xmlns attribute on every element.

<element xlmns='urn:some:custom:ns'>text...</element>

… although I believe this approach prevents you from using attributes from a namespace other than the one the element belongs to.


问:
@EJB injection vs lookup - performance issue
I have a question related with possible performance issue while using @EJB annotation. Imagine following scenario

```<code>public class MyBean1 implements MyBean1Remote{
 @EJB
 private MyBean2Remote myBean2;
 @EJB
 private MyBean2Remote myBean3;
 ...
 @EJB
 private MyBean20Remote myBean20;
}
</code>```

There is a bean with many dependencies to other beans. According to EJB spec if I would like to inject MyBean1Remote to some other bean, container would have to take all required dependencies from its pool inject it into MyBean1Remote and then inject reference to MyBean1Remote stub.

so in following scenario container needs to reserved 20 ejbs (myBean1 and its 19 dependencies)

```<code>public class MyAnotherBean implement MyAnotherRemote{
  @EJB
  private MyBean1Remote myBean1
}
</code>```

Let say that in most cases we will use only single dependency per each business method of myBean1. As a result each time  we want to inject that bean we force container to reserves many unnecessery EJBs. Lets also assume that we are operating on remote beans so probably container would also need to perform some load balancing algorithm prior injecting dependent beans.

Questions:

Wouldn't that cause unnecessary resource reservation and more over performance issue while operating in cluster environment?

Maybe good old ServiceLocator could be better solution because with this approach we would ask for specific EJB when we really need it ?

答:
In most cases and especially when using stateless session beans, your bean instances will be pooled. One of the rationales behind pooling is that dependency injection lookups might be relatively expensive, so the bean is pooled with (stubs for) all its dependencies already injected.

So every time you call a method on MyAnotherBean, This bean with its 20 transitive dependencies isn't created with all those dependencies resolved on the fly. Instead, a fully instantiated instance is selected from the pool and the method call is directed to that.

Also note that unless you are doing JNDI federation you normally can't easily inject remote EJBs.

Body:
I have a question related with possible performance issue while using @EJB annotation. Imagine following scenario

public class MyBean1 implements MyBean1Remote{
 @EJB
 private MyBean2Remote myBean2;
 @EJB
 private MyBean2Remote myBean3;
 ...
 @EJB
 private MyBean20Remote myBean20;
}

There is a bean with many dependencies to other beans. According to EJB spec if I would like to inject MyBean1Remote to some other bean, container would have to take all required dependencies from its pool inject it into MyBean1Remote and then inject reference to MyBean1Remote stub.

so in following scenario container needs to reserved 20 ejbs (myBean1 and its 19 dependencies)

public class MyAnotherBean implement MyAnotherRemote{
  @EJB
  private MyBean1Remote myBean1
}

Let say that in most cases we will use only single dependency per each business method of myBean1. As a result each time  we want to inject that bean we force container to reserves many unnecessery EJBs. Lets also assume that we are operating on remote beans so probably container would also need to perform some load balancing algorithm prior injecting dependent beans.

Questions:

Wouldn't that cause unnecessary resource reservation and more over performance issue while operating in cluster environment?

Maybe good old ServiceLocator could be better solution because with this approach we would ask for specific EJB when we really need it ?


问:
Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder
When I try to run my Android project on Eclipse ADT, I see this in the Console:

```<code>[2017-03-24 15:34:41 - Dex Loader] Failed to load C:\Users\jaimemontoya\android-sdks\build-tools\26.0.0-preview\lib\dx.jar
</code>```

[2017-03-24 15:34:41 - CouponClub] Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder!

I am using Eclipse Neon.2 Release (4.6.2):

This is the package configuration I have as seen from the Android SDK Manager:

What I understand from that error is that it failed to load dx.jar because it is trying to load it "from the SDK folder". The message even uses an exclamation mark to say that! What SDK folder is it referring to? I thought in this case "C:\Users\jaimemontoya\android-sdks" would be considered an SDK folder. Do you know where it is expecting to find the "dx.jar" file?

答:
in eclipse preferences -> java -> installedJREs
add x86 installed version of Java jre path and select it
then restart eclipse</p>

Body:
When I try to run my Android project on Eclipse ADT, I see this in the Console:

[2017-03-24 15:34:41 - Dex Loader] Failed to load C:\Users\jaimemontoya\android-sdks\build-tools\26.0.0-preview\lib\dx.jar

[2017-03-24 15:34:41 - CouponClub] Unknown error: Unable to build: the file dx.jar was not loaded from the SDK folder!

I am using Eclipse Neon.2 Release (4.6.2):

This is the package configuration I have as seen from the Android SDK Manager:

What I understand from that error is that it failed to load dx.jar because it is trying to load it "from the SDK folder". The message even uses an exclamation mark to say that! What SDK folder is it referring to? I thought in this case "C:\Users\jaimemontoya\android-sdks" would be considered an SDK folder. Do you know where it is expecting to find the "dx.jar" file?


问:
How to prevent the same multiplication numbers being asked twice in a row
sorry to bother you once again but I have one more add on to be made to this program. It works fine but how could it be made so it wouldn't ask the same multiplication question twice in a row? For example when it asks what is 1*2 it shouldn't ask it again right away (although there's only a small chance on that).</p>

```<code>import java.util.Random;
import javax.swing.JOptionPane;

public class Main{

  public static void main(String[] args) {

  boolean correctAnswer;
  Random number = new Random();
  int nmb1;
  int nmb2;
  int multi;

  while (true) {
    nmb1 = number.nextInt(10) + 1;
    nmb2 = number.nextInt(10) + 1;
    multi = nmb1 * nmb2;

    // read the user's input ...
    do {
        correctAnswer = multiplication(nmb1,nmb2,multi);
    }
    while (correctAnswer != true);
    // .. and repeat until the user types the correct answer

    JOptionPane.showMessageDialog(null, "Right");
  }
   }

  public static boolean multiplication(int number1,int number2,int answer)
  {

  int question;

     question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

      if (question != answer) {
          JOptionPane.showMessageDialog(null, "Wrong, try again");

          return false;
      }

  return true;

  }

}
</code>```

答:
There are many ways to do that, in this example, It computes all combinations of number pair, and then It shuffle the number pairs and finally It asks for every number pair.</p>

```<code>public class Main{

    public static void main(String[] args) {

        boolean correctAnswer;
        int nmb1;
        int nmb2;
        int multi;

        // It computes all combinations
        List<int[]> asks = new ArrayList<>(100);
        for (int i = 1; i < 11; i++) {
            for (int j = 1; j < 11; j++) {
                asks.add(new int[]{i,j});
            }
        }

        // It shufles
        Collections.shuffle(asks);

        // It asks for every number pair
        for (int[] numbers : asks){ // instead of while(true)
            nmb1 = numbers[0];
            nmb2 = numbers[1];
            multi = nmb1 * nmb2;

            // read the user's input ...

            ...
        }
</code>```

Body:
sorry to bother you once again but I have one more add on to be made to this program. It works fine but how could it be made so it wouldn't ask the same multiplication question twice in a row? For example when it asks what is 1*2 it shouldn't ask it again right away (although there's only a small chance on that).

import java.util.Random;
import javax.swing.JOptionPane;

public class Main{

  public static void main(String[] args) {

  boolean correctAnswer;
  Random number = new Random();
  int nmb1;
  int nmb2;
  int multi;

  while (true) {
    nmb1 = number.nextInt(10) + 1;
    nmb2 = number.nextInt(10) + 1;
    multi = nmb1 * nmb2;

    // read the user's input ...
    do {
        correctAnswer = multiplication(nmb1,nmb2,multi);
    }
    while (correctAnswer != true);
    // .. and repeat until the user types the correct answer

    JOptionPane.showMessageDialog(null, "Right");
  }
   }

  public static boolean multiplication(int number1,int number2,int answer)
  {

  int question;

     question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

      if (question != answer) {
          JOptionPane.showMessageDialog(null, "Wrong, try again");

          return false;
      }

  return true;

  }

}

Body:
There are many ways to do that, in this example, It computes all combinations of number pair, and then It shuffle the number pairs and finally It asks for every number pair.

public class Main{

    public static void main(String[] args) {

        boolean correctAnswer;
        int nmb1;
        int nmb2;
        int multi;

        // It computes all combinations
        List<int[]> asks = new ArrayList<>(100);
        for (int i = 1; i < 11; i++) {
            for (int j = 1; j < 11; j++) {
                asks.add(new int[]{i,j});
            }
        }

        // It shufles
        Collections.shuffle(asks);

        // It asks for every number pair
        for (int[] numbers : asks){ // instead of while(true)
            nmb1 = numbers[0];
            nmb2 = numbers[1];
            multi = nmb1 * nmb2;

            // read the user's input ...

            ...
        }


问:
ActualHeight and ActualWidth in Webview
I'm creating a webview in c# code in UWP application. I have attached a LoadCompleted event to it. When this event gets trigger ActaulHeight And ActualWidth is 0. I tried to set its MinWidth and MinHeight to 500. But its is not working.

I did the same thing by creating a webview control in XAML but in that case ActualHeight and ActualWidth is 500.

Here is the code :

```<code> public WebView _webView { get; set; }

 public ViewPage()
{
   this.InitializeComponent();
     _webView = new WebView
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Top,
            Source = new Uri(@"https://www.google.com"),
            MinHeight = 500,
            MinWidth = 500
        };
}

  private void _webView_LoadCompleted(object sender, NavigationEventArgs e)
    {
       // Here, when  I debug _webview ActualHeight and ActaulWidth is zero.
    }
</code>```

答:
ActualWidth and ActualHeight reflect the size of the UI element in the layout. In the C# code you only created an instance of WebView class, but didn't really place it anywhere on the page, hence these values were zero.

On the contrary, when you used XAML, not only you created an instance of WebView class, but also embedded this UI element into the page that was displayed when you ran the app, so ActualWidth and ActualHeight contained actual dimensions of the UI element on that page.

Title: ActualHeight and ActualWidth in Webview

Body:
I'm creating a webview in c# code in UWP application. I have attached a LoadCompleted event to it. When this event gets trigger ActaulHeight And ActualWidth is 0. I tried to set its MinWidth and MinHeight to 500. But its is not working.

I did the same thing by creating a webview control in XAML but in that case ActualHeight and ActualWidth is 500.

Here is the code :

 public WebView _webView { get; set; }

 public ViewPage()
{
   this.InitializeComponent();
     _webView = new WebView
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Top,
            Source = new Uri(@"https://www.google.com"),
            MinHeight = 500,
            MinWidth = 500
        };
}

  private void _webView_LoadCompleted(object sender, NavigationEventArgs e)
    {
       // Here, when  I debug _webview ActualHeight and ActaulWidth is zero.
    }


问:
NameValueCollection to URL Query?
I know i can do this

```<code>var nv = HttpUtility.ParseQueryString(req.RawUrl);
</code>```

But is there a way to convert this back to a url?

```<code>var newUrl = HttpUtility.Something("/page", nv);
</code>```

答: In AspNet Core 2.0 you can use QueryHelpers AddQueryString method.</p>

Title: NameValueCollection to URL Query?

Body:
I know i can do this

var nv = HttpUtility.ParseQueryString(req.RawUrl);

But is there a way to convert this back to a url?

var newUrl = HttpUtility.Something("/page", nv);