text:
Q: Allocating tasks to parallel workers so that expected cost is roughly equal I have an assignment problem where I'm trying to allocate a number of tasks with a known expected cost (runtime in seconds) to X parallel workers, subject to the constraint that each worker receives the same number of tasks (save for remainders), so that the total expected runtime per worker is roughly equal.
I'm using a data frame that defines the tasks to be executed, and for each task I can calculate a pretty accurate expected cost (runtime in seconds). E.g. something like this:
library("tibble")

set.seed(1232)
tasks <- tibble(task = 1:20, cost = runif(20, min = 1, max = 5)^2)
head(tasks)
#> # A tibble: 6 x 2
#>    task  cost
#>   <int> <dbl>
#> 1     1 22.5
#> 2     2 20.0
#> 3     3 21.3
#> 4     4  8.13
#> 5     5 18.3
#> 6     6 19.6

Created on 2019-11-21 by the reprex package (v0.3.0)
This is then used with foreach::foreach(...) %dopar% ... to execute the tasks in parallel. foreach() splits the tasks into roughly equal sized groups with size nrow(tasks)/X where X is the number of parallel workers (cores).
I'm currently shuffling the task list so that the cost is roughly equal for each worker, but there can still be substantial deviations, i.e. some workers get finished much earlier than others and thus it would have been better if they had had some more costly tasks. E.g.:
# shuffle tasks (in the original application cost is not random initially)
tasks <- tasks[sample(1:nrow(tasks)), ]

# number of workers
X <- 4
tasks$worker <- rep(1:X, each = nrow(tasks)/X)

# expected total cost (runtime in s) per worker
sapply(split(tasks$cost, tasks$worker), sum)
#>        1        2        3        4
#> 77.25278 35.25026 66.09959 64.05435

Created on 2019-11-21 by the reprex package (v0.3.0)
The second worker finishes in half the time as the other workers, so its capacity is wasted and the thing overall takes longer to finish.
What I'd like to do instead is have a way of re-ordering the task data frame so that when foreach splits it into X groups the total expected cost per group is more even.
I imagine this is a super-well known kind of problem and I just don't know the right verbiage to google (nor how to do it in R). Thanks for any help.
(EDIT) Mostly better alternative
For now, a relatively simple alternative that seems to do better than random shuffling. This orders the tasks by cost, assigns the first X tasks to workers 1 to X, then assigns the next chunk of X tasks in reverse order to workers X to 1, etc (this is "alt1" below).
(EDIT2) Added the RcppAlgos method
By Joseph Wood below.
library("tibble")
library("dplyr")
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library("ggplot2")
library("tidyr")
library("RcppAlgos")

getPartitions <- function(df, nWorkers, tol_ratio = 0.0001) {

  nSections <- nrow(df) / nWorkers
  avg <- sum(df$cost) / nWorkers
  tol <- avg * tol_ratio
  vec <- df$cost
  cond <- TRUE
  part <- list()

  for (i in 1:(nWorkers - 1)) {
      while (cond) {
          vals <- comboGeneral(vec, nSections,
                               constraintFun = "sum",
                               comparisonFun = "==",
                               limitConstraints = avg + (tol / 2),
                               tolerance = tol,
                               upper = 1)

          cond <- nrow(vals) == 0

          if (cond) {
              tol <- tol * 2
          } else {
              v <- match(as.vector(vals), df$cost)
          }
      }

      part[[i]] <- v
      vec <- df$cost[-(do.call(c, part))]
      avg <- sum(vec) / (nWorkers - i)
      tol <- avg * tol_ratio
      cond <- TRUE
  }

  part[[nWorkers]] <- which(!1:nrow(df) %in% do.call(c, part))
  part
}

race <- function() {
  N_TASKS = 100
  X = 4
  tasks <- tibble(task = 1:N_TASKS, cost = runif(N_TASKS, min = 1, max = 10)^2)

  # random shuffle
  tasks$worker <- rep(1:X, each = nrow(tasks)/X)
  rando <- max(sapply(split(tasks$cost, tasks$worker), sum))

  # alternative 1
  tasks <- tasks[order(tasks$cost), ]
  tasks$worker <- rep(c(1:X, X:1), length.out = nrow(tasks))
  alt1 <- max(sapply(split(tasks$cost, tasks$worker), sum))

  # modified version of ivan100sic's answer
  # sort by descending cost, after initial allocation, allocate costly tasks
  # first to workers with lowest total cost so far
  group <- factor(rep(1:(ceiling(nrow(tasks)/4)), each = X))
  tasks <- tasks[order(tasks$cost, decreasing = TRUE), ]
  tasks$worker <- c(1:X, rep(NA, length.out = nrow(tasks) - X))
  task_sets <- split(tasks, group)
  task_sets[[1]]$worker <- 1:X
  for (i in 2:length(task_sets)) {
    # get current total cost by worker
    total <- task_sets %>%
      bind_rows() %>%
      filter(!is.na(worker)) %>%
      group_by(worker) %>%
      summarize(cost = sum(cost)) %>%
      arrange(cost)
    task_sets[[i]]$worker <- total[["worker"]]
  }
  tasks <- bind_rows(task_sets)
  alt2  <- max(sapply(split(tasks$cost, tasks$worker), sum))

  # RcppAlogs by Joseph Wood below
  setParts <- getPartitions(tasks, X)
  worker   <- rep(1:4, each = N_TASKS/X)
  row_num  <- unsplit(setParts, worker)
  tasks$worker <- worker[order(row_num)]
  algo <- max(sapply(split(tasks$cost, tasks$worker), sum))

  c(ref = sum(tasks$cost) / X, rando = rando, alt1 = alt1, alt2 = alt2, algo = algo)
}

set.seed(24332)
sims <- replicate(1e3, race())
sims <- sims %>%
  t() %>%
  as_tibble() %>%
  pivot_longer(rando:algo, names_to = "Method")

ggplot(sims, aes(x = value, color = Method)) +
  geom_density() +
  scale_x_continuous(limits = c(0, max(sims$value))) +
  labs(x = "Total runtime (s)")

# this shows the estimated runtime relative to average total cost
# per worker (which may be unobtainable)
sims %>%
  group_by(Method) %>%
  summarize(time_relative_to_ref = mean(value - ref)) %>%
  arrange(time_relative_to_ref)
#> # A tibble: 4 x 2
#>   Method time_relative_to_ref
#>   <chr>                 <dbl>
#> 1 algo                 0.0817
#> 2 alt2                 0.307
#> 3 alt1                 4.97
#> 4 rando              154.

Created on 2020-02-04 by the reprex package (v0.3.0)

*

*"rando": randomly shuffle the task list

*"alt1": sort tasks by cost and alternate assigning to worker 1 to X, X to 1, etc.

*"alt2": based on ivan100sic's answer below, after the first allocation to workers 1 to X, allocate based on total cost per worker so far

*"algo": based on Joseph Woods's answer below

A: The following heuristic might give you good results:
Sort all the tasks by cost in descending order. For each task, assign it to the worker which has the minimum total assigned cost so far.

A: As @JohnColeman points out, this essentially boils down to partitioning. We are trying to partition the tasks equally such that the sum of the cost doesn't vary wildly.
The algorithm below does just that. The main idea is to successively find a set of tasks whose sum is close to the average. Once we find one, we remove them, and continue selecting.
The work horse of the algorithm below is comboGeneral from RcppAlgos*. This function allows one to find combinations of a vector meeting a constraint. In this case, we are looking for 5 numbers whose sum is close to sum(tasks$cost) / (number of workers) ~ 60.66425. Since we are looking for numbers close to and not exact, we can bound our constraint. That is, we can look for combinations such that the sum is within a given tolerance.
library(RcppAlgos)

getPartitions <- function(df, nWorkers, tol_ratio = 0.0001) {

    nSections <- nrow(df) / nWorkers
    avg <- sum(df$cost) / nWorkers
    tol <- avg * tol_ratio
    vec <- df$cost
    cond <- TRUE
    part <- list()

    for (i in 1:(nWorkers - 1)) {
        while (cond) {
            vals <- comboGeneral(vec, nSections,
                                 constraintFun = "sum",
                                 comparisonFun = "==",
                                 limitConstraints = avg + (tol / 2),
                                 tolerance = tol,
                                 upper = 1)

            cond <- nrow(vals) == 0

            if (cond) {
                tol <- tol * 2
            } else {
                v <- match(as.vector(vals), df$cost)
            }
        }

        part[[i]] <- v
        vec <- df$cost[-(do.call(c, part))]
        avg <- sum(vec) / (nWorkers - i)
        tol <- avg * tol_ratio
        cond <- TRUE
    }

    part[[nWorkers]] <- which(!1:nrow(df) %in% do.call(c, part))
    part
}

The output for the example given by the OP is as follows:
getPartitions(tasks, 4)
[[1]]
[1] 11 13  8 14 10

[[2]]
[1] 12  4 20  2 16

[[3]]
[1] 19  9 18  5  6

[[4]]
[1]  1  3  7 15 17

These are the rows from tasks that are to be passed to each worker. It runs instantly and returns a pretty even workload. Here are the estimated times for each worker:
sapply(getPartitions(tasks, 4), function(x) {
    sum(tasks$cost[x])
})
[1] 60.67292 60.66552 60.80399 60.51455

This is pretty good given that the ideal time would be mean(tasks$cost) * 5 ~= 60.66425.
Let's see how it performs. Below is a modified script for plotting that takes into account how varied each result is for a given method. We measure this with sd (standard deviation). It also returns the ideal solution for reference.
library("tibble")
library("dplyr")
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library("ggplot2")
library("tidyr")

race <- function() {
    N_TASKS = 100
    X = 4
    tasks <- tibble(task = 1:N_TASKS, cost = runif(N_TASKS, min = 1, max = 10)^2)
    ideal_soln <- sum(tasks$cost) / X

    # random shuffle
    tasks$worker <- rep(1:X, each = nrow(tasks)/X)
    rando_mx <- max(sapply(split(tasks$cost, tasks$worker), sum))
    rando_sd <- sd(sapply(split(tasks$cost, tasks$worker), sum))

    # alternative 1
    tasks <- tasks[order(tasks$cost), ]
    tasks$worker <- rep(c(1:X, X:1), length.out = nrow(tasks))
    alt1_mx <- max(sapply(split(tasks$cost, tasks$worker), sum))
    alt1_sd <- sd(sapply(split(tasks$cost, tasks$worker), sum))

    # modified version of ivan100sic's answer
    # sort by descending cost, after initial allocation, allocate costly tasks
    # first to workers with lowest total cost so far
    group <- factor(rep(1:(ceiling(nrow(tasks)/4)), each = X))
    tasks <- tasks[order(tasks$cost, decreasing = TRUE), ]
    tasks$worker <- c(1:X, rep(NA, length.out = nrow(tasks) - X))
    task_sets <- split(tasks, group)
    task_sets[[1]]$worker <- 1:X
    for (i in 2:length(task_sets)) {
        # get current total cost by worker
        total <- task_sets %>%
            bind_rows() %>%
            filter(!is.na(worker)) %>%
            group_by(worker) %>%
            summarize(cost = sum(cost)) %>%
            arrange(cost)
        task_sets[[i]]$worker <- total[["worker"]]
    }
    tasks <- bind_rows(task_sets)
    alt2_mx  <- max(sapply(split(tasks$cost, tasks$worker), sum))
    alt2_sd  <- sd(sapply(split(tasks$cost, tasks$worker), sum))

    ## RcppAlgos solution
    setParts <- getPartitions(tasks, X)
    algos_mx <- max(sapply(setParts, function(x) sum(tasks$cost[x])))
    algos_sd <- sd(sapply(setParts, function(x) sum(tasks$cost[x])))

    c(target_soln = ideal_soln,rando_max = rando_mx, alt1_max = alt1_mx,
      alt2_max = alt2_mx, algos_max = algos_mx, rando_std_dev = rando_sd,
      alt1_std_dev = alt1_sd, alt2_std_dev = alt2_sd, algos_std_dev = algos_sd)
}

set.seed(24332)
system.time(sims <- replicate(1e3, race()))
sims %>%
    t() %>%
    as_tibble() %>%
    pivot_longer(rando_std_dev:algos_std_dev, names_to = "Method") %>%
    ggplot(aes(x = value, color = Method)) +
    geom_density() +
    scale_x_continuous(limits = c(0, 100)) +
    labs(x = "Standard Deviation (s)")
Warning message:
Removed 719 rows containing non-finite values (stat_density).

It is hard to tell what is going on because the standard deviation for the rando method is so large. If we just look at alt1, alt2, and the algos approach we have:
sims %>%
    t() %>%
    as_tibble() %>%
    pivot_longer(alt1_std_dev:algos_std_dev, names_to = "Method") %>%
    ggplot(aes(x = value, color = Method)) +
    geom_density() +
    scale_x_continuous(limits = c(0, 5)) +
    labs(x = "Standard Deviation (s)")
Warning message:
Removed 335 rows containing non-finite values (stat_density)

And now alt2 and algos:
sims %>%
    t() %>%
    as_tibble() %>%
    pivot_longer(alt2_std_dev:algos_std_dev, names_to = "Method") %>%
    ggplot(aes(x = value, color = Method)) +
    geom_density() +
    scale_x_continuous(limits = c(0, 1.7)) +
    labs(x = "Standard Deviation (s)")

As you can see, the RcppAlgos solution gives the most balanced load every time.
And finally, here is an illustration that demonstrates how close each method is to the target solution:
summary(abs(t(sims)[, "algos_max"] - t(sims)[, "target_soln"]))
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
0.003147 0.057913 0.081986 0.081693 0.106312 0.179099

summary(abs(t(sims)[, "alt2_max"] - t(sims)[, "target_soln"]))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
0.01175 0.14321 0.23916 0.30730 0.40949 2.03156

summary(abs(t(sims)[, "alt1_max"] - t(sims)[, "target_soln"]))
  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
0.4979  2.9815  4.4725  4.9660  6.3220 16.5716

summary(abs(t(sims)[, "rando_max"] - t(sims)[, "target_soln"]))
 Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
13.16   98.14  143.64  154.10  200.41  427.81

We see that the RcppAlgos solution is around 3-4 times closer on average to the target solution than the second best method (alt2 in this case).
Update
For the most part, the alt2/alt1 methods perform relatively well and are very simple, which is a huge plus. However, there are many cases where they will fail. For example, given X workers and X - 1 tasks that you know take a substantially longer time than the other tasks, since those methods rely on sorting, they will predictably allocate too much to X - 1 workers. Simply change the following line in the function race():
## Original
tasks <- tibble(task = 1:N_TASKS, cost = runif(N_TASKS, min = 1, max = 10)^2)

## Modified
tasks <- tibble(task = 1:N_TASKS, cost = c(runif(X - 1, 15, 25),
                                           runif(N_TASKS - X + 1, min = 1, max = 10))^2)

Now rerun and observe:
set.seed(24332)
sims <- replicate(1e3, race())
sims <- sims %>%
    t() %>%
    as_tibble() %>%
    pivot_longer(rando:algo, names_to = "Method")

ggplot(sims, aes(x = value, color = Method)) +
    geom_density() +
    scale_x_continuous(limits = c(0, max(sims$value))) +
    labs(x = "Total runtime with Large Gap (s)")

sims %>%
    group_by(Method) %>%
    summarize(time_relative_to_ref = mean(value - ref)) %>%
    arrange(time_relative_to_ref)
# A tibble: 4 x 2
Method time_relative_to_ref
<chr>                 <dbl>
1 algo                  0.109
2 alt2                150.
3 alt1                184.
4 rando               839.

Although this is a contrived example, it shows that since the alt1/alt2 solutions makes assumptions about the underlying data, it will inevitably fail when presented with a more general problem.
* Disclosure: I am the author of RcppAlgos


text:
Q: Segmented nonlinear regression in R?
Possible Duplicate:
Change point analysis using R's nls()

I want to do a nonlinear regression with nls() but also include a specific type of segmented or piecewise regression. The Formula I want to implement is:
S ~ b0 + (A > T) * b1 * (A - T)

T should be the threshold value or breakpoint as identified by the nonlinear-segmented regression. I know that I can use "algorithm = plinear" but that does not work at all.

The data I have is:
A   S
0.000809371 1
0.003642171 3
0.009712455 4
0.010521827 2
0.004046856 4
0.015378054 5
0.000404686 0
0.000404686 0
0.000404686 0
0.000809371 0
0.000809371 3
0.037635765 3
0.008903084 2
0.016187426 5
0.043301364 1
0.000404686 1
0.002428114 1
0.003642171 1
0.013759312 4
0.051395077 9
0.394568501 9
0.005665599 1
0.013354626 1
0.028732681 3
0.026304567 2
0.004451542 1
0.050585705 2
0.00647497  1
0.010926512 0
0.013354626 1
1.695632841 4
0.013354626 2

A: EDIT:
As requested by OP, here a minimal example of how to include breakpoints in a nls. Actually, after reviewing the question and answers that is considered a duplicate, I believe they go way around to come at a solution. It can be as simple as :
Data <- data.frame(
  A = rnorm(100),
  S = sample(0:9,100,TRUE)
)

X <- nls(S~ B0 + B1*as.numeric(A > Tval)*(A-Tval),
        start=list(B0=1,B1=1,Tval=1),data=Data)

So you make sure that the ID variable is numeric (i.e. 0 if FALSE and 1 if TRUE) and proceed as usual.
Consider constructing a dummy variable :
Data <- data.frame(
  A = rnorm(100),
  S = sample(0:9,100,TRUE)
)
Tval <- 1
Data$Id <- ifelse( Data$A > Tval , 1, 0 ) # the dummy variable

nls(S~ B0 + B1*Id*(A-Tval),data=Data)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern not matching for less or more than 10 numbers I have created a code which matches only more than 10 digits or none,but what if input given is 5 digits?I want to show error if it is less or more than 10 digits.
code :

    Mobile Number
    <input type="number" name="mobileNumber" [(ngModel)]="mobile_no"  ngPattern=" /^[0-9]{10}$/;" class="form-control" id="mobileNumber" minlength="10" maxlength="10" required #mobileNumber="ngModel">

        Mobile number is required and it cannot be more than or less than 10 characters. Please enter a valid mobile number.

A: Try to do this:

        Mobile Number
        <input type="number" name="mobileNumber" [(ngModel)]="mobile_no"  ngPattern=" /^[0-9]{10}$/;" class="form-control" id="mobileNumber" minlength="10" maxlength="10" required #mobileNumber="ngModel">

            Mobile number is required and it cannot be more than or less than 10 characters. Please enter a valid mobile number.

            <ng-template #error>You should put 10 digits at least</ng-template>


text:
Q: Why is this code working without an Exception At a windows form I call a method at the load event. There I fill some TextBoxes with this:
     foreach (TabPage page in tabControl_Berichte.TabPages)
        {
            uc_MusterberichtProzessdetails bla = (uc_MusterberichtProzessdetails)page.Controls[0];

            object val = musterbericht.GetType().GetProperty(page.Name + "_Bem").GetValue(musterbericht, null);
                bla.tB_Bemerkung.Text = val.ToString();

            val = musterbericht.GetType().GetProperty(page.Name + "_Bearb").GetValue(musterbericht, null);
                bla.tB_Bearbeiter.Text = val.ToString();

            val = musterbericht.GetType().GetProperty(page.Name + "_Datum").GetValue(musterbericht, null);
                bla.tB_Datum.Text = val.ToString().Substring(0, 10);

            val = musterbericht.GetType().GetProperty(page.Name + "_Erledigt").GetValue(musterbericht, null);
                bla.chB_Erledigt.Checked = (bool)val;

            val = musterbericht.GetType().GetProperty(page.Name + "_Dauer").GetValue(musterbericht, null);
                bla.tB_Dauer.Text = val.ToString();
        }

All the properties are strings except of the "_Datum" which is a DateTime?
When the method is being called, the data will be loaded for each TabPage.
In my example one TabPage is loaded correct. At the 2nd TabPage the Date Property is null. So after this:
val = musterbericht.GetType().GetProperty(page.Name + "_Datum").GetValue(musterbericht, null);

val is null.
At the next row:
bla.tB_Datum.Text = val.ToString().Substring(0, 10);

I can see during debugging that when the mouse hovers ToString() there is shown "" (empty string).
But if I now click F10 my Form will be shown. The method is stoped. The program runs (the following TextBoxes and tabs are not filled with data).
There is NO Exception!! I don't get it. And there is no try catch anywhere.
If I try this directly with an object wich is set to null an exception is thrown.
So what happens here? Why is my program still working??
(Now I test after each val = ... if val != null, so that's not the problem.)
EDIT:
I just tried this out:
    DateTime? dttest = null;
    object objtest = dttest;
    string strtest = objtest.ToString();

And here I get an exception at ToString().
At the example above I also tried
    val = musterbericht.GetType().GetProperty(page.Name + "_Datum").GetValue(musterbericht, null);
if (val.ToString().Length > 0)
    bla.tB_Datum.Text = val.ToString().Substring(0, 10);

Here it is almost the same behaviour as above. Here the method stops at the if (val.ToString().Length > 0) and the load event is being aborted. (Still no exception)
It looks like val.ToString() is working but val.ToString().xxxxx will cause this strange behaviour.

A: You can check the msdn docs, or use reflector/dotPeek to see that Nullable<T> overrides ToString() to return "" if null, instead of throwing.
DateTime? is just Nullable<DateTime>, which is why you're getting an empty string and no exception.
Edit: The method is probably "ending" when .Substring(0, 10) executes because you're going to get an ArgumentOutOfRangeException. The empty string has length 0, so you cannot ask for a substring of length 10.


text:
Q: Abstract class, how to avoid code duplication? I have the following code
internal abstract class Base
{
    public DateTime Time;
    public string Message;
    public string Log;
    public abstract void Invoke(string message);
}

internal class SubA : Base
{
    public override void Invoke(string message)
    {
        Time = DateTime.Now;
        // Do A
    }
}

internal class SubB : Base
{
    public override void Invoke(string message)
    {
        Time = DateTime.Now;
        // Do B
    }
}

I have these SubA and SubB classes which inherits from Base class, you can see that i have a code that repeating it self which is setting the Time, is there a way to move the setting of the time to the base class?

A: You could do something like this:
internal abstract class Base
{
    public DateTime Time;
    public string Message;
    public string Log;
    public void Invoke(string message){
         Time = DateTime.Now;
         this.InvokeInternal(message);
    }
    protected abstract void InvokeInternal(string message);
}

internal class SubA : Base
{
    protected override void InvokeInternal(string message)
    {
        // Do A
    }
}

internal class SubB : Base
{
    protected override void InvokeInternal(string message)
    {
        // Do B
    }
}

A: There a many possible solutions.
This depends on when you want to have this propertie set.
If you want it immediately you can do this in the constructor of your Base class.
internal abstract class Base
{
    public DateTime Time;
    public string Message;
    public string Log;
    public abstract void Invoke(string message);

    public Base()
    {
        Time = DateTime.Now;
    }
}

internal class SubA : Base
{
    public override void Invoke(string message)
    {
        // Do A
    }
}

internal class SubB : Base
{
    public override void Invoke(string message)
    {
        // Do B
    }
}

A: Use a virtual method instead:
internal abstract class Base
{
    public DateTime Time;
    public string Message;
    public string Log;
    public virtual void Invoke(string message) {
        Time = DateTime.Now;
    }
}

internal class SubA : Base
{
}

internal class SubB : Base
{
}

You can still override the method in subclasses where you want a different implementation.

A: internal abstract class Base
{
    public DateTime Time;
    public string Message;
    public string Log;
    public virtual void Invoke(string message)
    {
        Time = DateTime.Now;
    }

}

internal class SubA : Base
{
    public override void Invoke(string message)
    {
        base.Invoke(message);
        // Do A
    }
}

internal class SubB : Base
{
    public override void Invoke(string message)
    {
        base.Invoke(message);
        // Do B
    }
}

A: There are plenty of answers already. As an alternative (and a bit of a ninja) approach, I ll suggest Lambda expressions used with method properties.
In your case;
 public class Base
  {
    public DateTime Time;
    public string Message;
    public string Log;
    public Action<string> Invoke { get; set; }

    public Base()
    {
       this.Invoke = InvokeDefault;
    }

    private void InvokeDefault(string message)
    {
       Time = DateTime.Now;
    }
  }

This way, we provide a default behavior to the base class. With lambda expressions you can create instances with different Invoke methods as follows..
var myInstance= new Base
  {
    Invoke = () => { Time = DateTime.Now.AddDays(7); }
  };

The invoke method is overridden only for this instance of the Base class. This gives more flexibility and help avoid unnecessary subclasssing.
Check this awesome post from  Patrick Steele for details.

A: There are two practical options, depending on how rigorous you want your code contracts to be.
You can move the logic into a virtual method and allow the child types to overload the behaviour if they so choose to.
internal abstract class Base
{
    ...
    public virtual void Invoke(string message)
    {
        Time = DateTime.Now;
    }
}

internal class SubA : Base
{
    public override void Invoke(string message)
    {
        base.Invoke(message);
        // Do A
    }
}

internal class SubB : Base
{
    public override void Invoke(string message)
    {
        base.Invoke(message);
        // Do B
    }
}

This does however make it possible for derived types to not call the base method at all.
If it's catastrophic if the base functionality is not invoked and you want more certainty of the expected behaviour, you might want to make a stronger contract by providing an injection point into the middle of the base method:
internal abstract class Base
{
    ...
    public void Invoke(string message)
    {
        Time = DateTime.Now;
        this.InvokeCore(message);
    }

    protected abstract void InvokeCore(string message);
}

internal class SubA : Base
{
    public override void Invoke(string message)
    {
        // Do A
    }
}

internal class SubB : Base
{
    public override void InvokeCore(string message)
    {
        // Do B
    }
}


text:
Q: Showing distribution has a $\chi^2$ distribution with df = n Let $X_1,X_2,....,X_n$ denote independent identically distributed random variables such that $X_1$ has density $p_1(x;\theta)$ where
$\hspace{15mm}p(x;\theta) =\frac{1}{\sqrt{2\pi\theta}}e^{1/\theta}x^{-3/2}exp(-1/2(x+x^{-1})/\theta), x > 0$.
Show that $\frac{1}{\theta}T(x) = \frac{1}{\theta}\Sigma_{j}^{}(X_j + X_j^{-1}-2)$ has a $\chi^2$ distribution with df = n.
Attempted answer:
Since $\frac{1}{\theta}(X_i + X_i^{-1} -2)$ is an increasing function of X, let $t = \frac{1}{\theta}(X_i + X_i^{-1} -2)$. The pdf of t is:
$\hspace{15mm}g(t) =f(x)|\frac{dx}{dt}||_t$ --> So then $t = \frac{1}{\theta}(X_i + X_i^{-1} -2)$ --> $dt = \frac{1}{\theta}(1-X^{-2})dx$
After substitution we have
$\hspace{15mm}g(t)  =f(x)|\frac{dx}{dt}||_t$ = $(\frac{1}{2\pi\theta})^{1/2}exp{\frac{1}{-2\theta}}\frac{x^{-3/2}}{\frac{1}{\theta}(1-x^{-2})}$
$\hspace{15mm}=(\frac{\theta}{2\pi})^{1/2}exp(-\frac{t}{2})\frac{x^{1/2}}{(x^2-1)}$
$\hspace{15mm}=(\frac{1}{2\pi})^{1/2}exp(-\frac{t}{2})\frac{(x\theta)^{1/2}}{(x-1)}* \frac{1}{x+1}$
$\hspace{15mm}=(\frac{1}{2\pi})^{1/2}exp(-\frac{t}{2})t^{-1/2}* \frac{1}{x+1}$
The distribution would be $\Gamma(1/2,1/2)$ if the $\frac{1}{x+1}$ could be removed.

A: One approach is to work instead with the moment generating function.
Consider $t < 1/2$ and note that the moment generating function of
$h(X_{i}) = \frac{1}{\theta}(X_{i} + X_{i}^{-1} - 2)$ is
\begin{eqnarray}
M_{h(X)}(t) &=& E\Big[ \exp\Big\{ \frac{t}{\theta}( X_{i} + X_{i}^{-1} - 2)
\Big\}\Big] \\
&=& \frac{e^{-2t/\theta}}{\sqrt{2\pi\theta}}
\int_{0}^{\infty}e^{1/\theta} \exp\Big(\frac{t}{\theta}\{x + 1/x  \}\Big)x^{-3/2}\exp\Big(\frac{-1}{2\theta}\{x + 1/x\}\Big) dx \\
&=& \frac{e^{(1-2t)/\theta}}{\sqrt{2\pi\theta}}
\int_{0}^{\infty} x^{-3/2}\exp\Big(\frac{-(1 - 2t)}{2\theta}\{x + 1/x\}\Big) dx \\
&=& \frac{1}{\sqrt{1 - 2t}}
\int_{0}^{\infty} \frac{e^{(1-2t)/\theta}}{\sqrt{2\pi}}\sqrt{\frac{1 - 2t}{\theta}}x^{-3/2}\exp\Big(\frac{-(1 - 2t)}{2\theta}\{x + 1/x\}\Big) dx \\
&=&  \frac{1}{\sqrt{1 - 2t}}\int_{0}^{\infty}{ p(x; \eta) dx},
\qquad \textrm{where } \eta = \theta/(1 - 2t) \\
&=& \frac{1}{\sqrt{1 - 2t}}
\end{eqnarray}
This is exactly the mgf of a chi-squared random variable with one degree of
freedom. Hence, $h(X_{i}) \sim \chi_{1}^{2}$.
Since $\frac{1}{\theta}T(x) = \sum_{i=1}^{n} h(X_{i})$, this means
that $\frac{1}{\theta}T(x) \sim \chi_{n}^{2}$.


text:
Q: I can not get my Microsoft SQL Server trigger to run properly I am trying to have this trigger run each time information is inserted into a single table then run the information along with Visual Studio which it will send the information as a text file into my folder where I can use the information at a later time to log transactions.
Here is my table:
CREATE TABLE VDtoText
(
    AccountNumber INT NOT NULL,
    GarmentNumber INT NOT NULL,
    TicketNumber INT NOT NULL,
    SlotNum INT NULL,
    DateTimeAdded DateTime NOT NULL DEFAULT CURRENT_TIMESTAMP
)

Here is the trigger:
/* first run these both separately after creating table */
EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO

EXEC sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE;
GO

CREATE TRIGGER UpdateInsertPlz
ON VDtoText
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @sql NVARCHAR(4000)

    SELECT @sql = 'bcp SUVOAS.dbo.VDtoText out "C:\Users\benso\OneDrive\Desktop\Test\Final2\WC\WCtoPOS.txt" -c -t"," -T -S' + @@SERVERNAME
    PRINT @sql

    EXEC master..xp_cmdshell @sql
END;

DECLARE @sql NVARCHAR(4000)

SELECT @sql = 'bcp SUVOAS.dbo.VDtoText out "C:\Users\benso\OneDrive\Desktop\Test\Final2\WC\WCtoPOS.txt" -c -t"," -T -S' + @@SERVERNAME

PRINT @sql

EXEC master..xp_cmdshell @sql

This code by itself will properly send the information how I would like, but while it is in a trigger it just continues to attempt to execute and I just see a wheel spin the whole time on Microsoft SQL and Visual Studio continuously returns:

The thread 0x2a34 has exited with code 0 (0x0). The thread 0x3d38 has exited with code 0 (0x0). The thread 0x562c has exited with code 0 (0x0). The thread 0x5e14 has exited with code 0 (0x0). The thread 0x31fc has exited with code 0 (0x0).

and sends no information of the inserted data to the table.
Please Help :)


text:
Q: DatePicker Highlight Only One Weekday Ok so, below is the code, I'm trying to adapt apple's code to show only 1 weekday (the weekday the app was launched) every week, right now I can nail down a span of x days, but I'm trying to get 1 day each week to appear and the rest to be blocked out:
let dateRange: ClosedRange<Date> = {
    let calendar = Calendar.current
    let startComponents = DateComponents(year: 2022, month: 5, day: 1)
    let endComponents = DateComponents(year: 2022, month: 5, day: 12)
    return calendar.date(from:startComponents)!
        ...
        calendar.date(from:endComponents)!
}()

DatePicker("Date", selection: $date, in: dateRange, displayedComponents: [.date])
                .datePickerStyle(CompactDatePickerStyle())
                .labelsHidden()                      // dateRange called from in:

Any ideas? Kind of new to dates, it's heavy


text:
Q: Retrieve count (total) from non-default REST API I would like to query my server for this URL http://localhost:1337/api/posts/count?category=technology using Ember. I'm using the default RESTAdapter like this:
export default DS.RESTAdapter.extend({
  coalesceFindRequests: true,
  namespace: 'api',
)};

The Post model looks like this:
import DS from 'ember-data';

var Post = DS.Model.extend({
  title: DS.attr('string'),
  permalink: DS.attr('string'),
  body: DS.attr('string')
});

export default Post;

How do I make such a request?

A: I think you have at least two ways to achieve that when you don't have a control over your backend. Otherwise, you can still use the RESTful API (see the last section of my answer).
Override buildURL
The first one is to use the existing RESTAdapter functionalities and only override the buildURL method:
var PostAdapter = DS.RESTAdapter.extend({
  namespace: 'api',

  buildURL: function(type, id, record) {
    var originalUrl = this._super(type, id, record);
    if (this._isCount(type, id, record))  { // _isCount is your custom method
      return originalUrl + '/count';
    }
    return originalUrl;
  }
});

where in the _isCount method you decide (according to record property for example) if it's what you want. And then, you can pass the params using the store:
this.store.find('post', {
  category: technology
});

Override findQuery
The second way is to override the whole findQuery method. You can either use the aforementioned DS.RESTAdapter or use just DS.Adapter. The code would look as the following:
var PostAdapter = DS.Adapter.extend({
  namespace: 'api',

  findQuery: function(store, type, query) {
    // url be built smarter, I left it for readability
    var url = '/api/posts/count';

    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.getJSON(url, query).then(function(data) {
        Ember.run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null;
        Ember.run(null, reject, jqXHR);
      });
    });
  },

});

and you use the store as in the previous example as well:
this.store.find('post', {
  category: technology
});

Obtaining 'count' from meta
If you have a complete control on your backend, you can leverage the power of metadata.
The server response then would be:
// GET /api/posts/:id
{
  "post": {
    "id": "my-id",
    "title": "My title",
    "permalink": "My permalink",
    "body": "My body"
  },

  "meta": {
    "total": 100
  }
}

and then you can obtain all the meta information from:
this.store.metadataFor("post");

Similarly, you can use this approach when getting all the posts from /api/posts.
I hope it helps!


text:
Q: python matplotlib backend change after program parameters reading I wrote a program and would like to give to the user the opportunity to run it either on compute with a graphical environment or not.
Currently through hard coding it I can do either one or the other by changing the matplotlib import at the top of my program file, before importing pyplot.
with graphical environment
import matplotlib
matplotlib.use("Qt4Agg")
import matplotlib.pyplot as plt
...

without graphical environment
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
...

the remaining code would look something like that:
...
import os, sys, argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--noX", action="store_true", dest="noX")
    params = parser.parse_args()

    data = [0,1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.plot(data)
    if not params.noX:
        plt.show()
    plt.savefig("foo.png")

    sys.exit(0)

if __name__ == "__main__":
    main()

Is it possible to change the backend based on the noX parameter value?

A: You can set the backend o a condition:
import matplotlib
if not params.noX:
    matplotlib.use("agg")
else:
    matplotlib.use("Qt4Agg")
import matplotlib.pyplot as plt

If you only plot inside main, move your import inside this function:
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--noX", action="store_true", dest="noX", default=False)
    params = parser.parse_args()

    import matplotlib
    if not params.noX:
        matplotlib.use("agg")
    else:
        matplotlib.use("Qt4Agg")
    import matplotlib.pyplot as plt

    data = [0,1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.plot(data)
    if not params.noX:
        plt.show()
    plt.savefig("foo.png")

    sys.exit(0)

if __name__ == "__main__":
    main()

If you want to do plotting everywhere, use special function to parse the
command line arguments and call it only once.
import argparse

def _parse_cmd_args():
    """Parse command line args.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--noX", action="store_true", dest="noX", default=False)
    params = parser.parse_args()
    return params

PARAMS = _parse_cmd_args()
# Want to prevent any further call to `_parse_cmd_args()`?
# Un-comment the following line:
# del _parse_cmd_args

import matplotlib
if not PARAMS.noX:
    matplotlib.use("agg")
else:
    matplotlib.use("Qt4Agg")
import matplotlib.pyplot as plt

def main():
    data = [0,1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.plot(data)
    if not PARAMS.noX:
        plt.show()
    plt.savefig("foo.png")
    sys.exit(0)

if __name__ == "__main__":
    main()

A: Did you try? As a general rule you can't change the backend. So you will have to pospone the decision until you know the value of noX. Keep in mind that you can import at any time and any place. It is adviced to import at the beginning of the file but that's not always possible.

A: Ok so combining the idea of Mike with the global import of plt I come up with something like that to do the trick. Sorry for bothering you, it was actually simpler than first envisaged.
import os, sys, argparse

import matplotlib
matplotlib.use("agg") if "--noX" in sys.argv else matplotlib.use("Qt4Agg")
import matplotlib.pyplot as plt

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--noX", action="store_true", dest="noX", default=False)
    params = parser.parse_args()

    data = [0,1,2,3,4,5]
    fig, ax = plt.subplots()
    ax.plot(data)
    if not params.noX:
        plt.show()
    plt.savefig("foo.png")

    sys.exit(0)
if __name__ == "__main__":
    main()


text:
Q: Interpret Wireshark Captures I am troubleshooting wireless connectivity problem in my home network. My Thinkpad X200 laptop which use Intel Wifi Link 5100 AGN is not able to surf the internet stably. Sometimes it works, but most of the time it couldn't load the page completely or not loaded at all.
This is not happening to my desktop PC which is connected to the same D-Link AP as well.
I managed to capture network traffic on my laptop with Wireshark which results in the image below:

From what I know, the black-background rows show that there are erros in TCP checksum / Bad TCP. Is this normal on any wireless network? If not, how can I fix my laptop so it can surf the internet stably as my desktop PC?
Edit: I tried to capture the TCP packet again while the page failed to completely load. It looks like this is related to massive "TCP Retransmission" in Wireshark logs somehow ..
Edit 2: Gave up on investigating this. Tried another ACP. Luckily, it works without those many retransmission message o__o' Many thanks to everyone for the answers!

A: TCP checksum / Bad TCP is very normal for Wireshark and other packet sniffing tools, it is because you have enabled the checksum offloading on your wireless card, you can disable it or ignore it.
TCP retransmission is the exact reason for the problems of your network.
The possible reasons are below:

*

*The acknowledgment packets are being transmitted via a slower path.

*The network load is very high.

*The receiver or router is overloaded.

A: The bad checksum errors are probably because you have TCP offload facilities in your network card.  What this means is that the checksum is calculated after Wireshark has captured the packet.
There is a page abput it in the Wireshark FAQ.
EDIT:
In response to the comments, it is probably not the source of the issue.  If the checksum was incorrect when the packet arrived at the destination then it would request a re-send.  However, i would suggest following the recommendation in the Wireshark documentation and turn off checksum offloading while you are running a trace.  On a modern PC that is only doing normal desktop tasks, I doubt you will notice any performance difference so it is probably easier to just leave it turned off until you get this problem fixed. (Or you give up investigating it.)

A: Intel's Centrino WiFi adapters that are usually in the X200 are generally OK but they have had issues with Power Management (CAM\PSP) WiFi features when connecting to some AP's. As a first step I'd suggest you go into the properties of the WLAN adapter and disable power management and under the advanced properties set the Transmit power to max.


text:
Q: Converting a list by values to another list with stream I have the following code which does work. My goal is to get a count of number of nodes that are up and down
 Map<Boolean, Long> counting = nodes.stream()
            .collect(Collectors.groupingBy(ClusterNode::IsUp,Collectors.counting()));

 List<DataPoint> dps = counting.keySet().stream()
            .map(k -> new DataPoint(timestamp, counting.get(k).toString(), cluster, k.toString()))
            .collect(Collectors.toList());

Wondering if there is a better way to do this using a stream.  Can it be combined into one operation?

A: You can write your operation as one statement, though technically, it consist of two Stream operations:
List<DataPoint> dps = nodes.stream()
 .collect(Collectors.partitioningBy(ClusterNode::IsUp, Collectors.counting()))
 .entrySet().stream()
 .map(e->new DataPoint(timestamp, e.getValue().toString(), cluster, e.getKey().toString()))
 .collect(Collectors.toList());

You could merge the second operation into the collector as finishing operation, e.g. via collectingAndThen and you could also replace the second Stream operation by two lookups of the well-known keys true and false, then, it would indeed be one Stream operation, however, to no actual benefit.


text:
Q: devise :password and :encrypted_password in devise rails gem, what is the difference between these two?
I have seen the :encrypted_password field in the generated schema but not :password field.
Any explanations if these two are interconnected with each other?

A: Devise::Models::DatabaseAuthenticatable has a setter for that:
def password=(new_password)
  @password = new_password
  self.encrypted_password = password_digest(@password) if @password.present?
end

So you should set the password as if there was a password field, devise will take care of encrypting it.
As @spickermann already pointed out - plain text password should never be stored anywhere and should filtered out from logs/error messages and so on, because this produces a huge security risk: the encrypted password leak is not totally harmless, but not dangerous that much.

A: password is the plain text the user set as his password (and plain text password should never be stored anywhere). encrypted_password this the encrypted version of this password.
You might want to read SecurePassword.

A: :password is the password that a user sets through a form.
:encrypted_password is what is stored in your database and retrieved to create a user session.
Essentially, :encrypted_password is a hashed and salted version of :password that can be safely stored in your database. See this answer if you need more information on why you shouldn't store plain text passwords in your database.


text:
Q: Jquery: is there another way to write this, maybe using .attr? I thought I could re-write the line below:
$('a').filter('[hash=' + inview + ']');

to something like this:
$('a').attr(href, inview);

obviously with var inview = yada yada yada defined above it.
or is there another way to write the first line up there,
using jquery and getting rid of the [hash=' for something like .attr or .something(inview)?

A: $('a[hash=' + inview + ']');

That should do it.

A: You want something like:
$('a[hash="' + inview + '"]')

$('a').attr('hash', inview);, which is what I assume you meant for your second line, actually sets the hash attribute to inview.

A: $('a').attr(href, inview);

For reference that would set the href of all a elements to inview


text:
Q: How to parse json array without json object title in android ? Help me [
   {
      "configurationId":1,
      "configurationName":"CGST",
      "configurationVal":"2.5"
   },
   {
      "configurationId":2,
      "configurationName":"SGST",
      "configurationVal":"2.5"
   },
   {
      "configurationId":3,
      "configurationName":"DELIVERY_CHARGE",
      "configurationVal":"0"
   },
   {
      "configurationId":4,
      "configurationName":"Admin_Mobile",
      "configurationVal":"9500100042,8939404592"
   },
   {
      "configurationId":5,
      "configurationName":"MIN_ORDER_AMOUNT",
      "configurationVal":"98"
   },
   {
      "configurationId":6,
      "configurationName":"Packing_charge",
      "configurationVal":"3"
   },
   {
      "configurationId":7,
      "configurationName":"available_areas",
      "configurationVal":"{\"availableAreas\":[{\"area_id\": \"1\",\"area_name\": \"Velachery\",\"pincode\": \"600042\"},{\"area_id\": \"2\",\"area_name\": \"Nanganallur\",\"pincode\": \"600061\"},{\"area_id\": \"3\",\"area_name\": \"Adambakkam\",\"pincode\": \"323546\"},{\"area_id\": \"4\",\"area_name\": \"Madipakkam\",\"pincode\": \"600091\"},{\"area_id\": \"5\",\"area_name\": \"Perungudi\",\"pincode\": \"600096\"},{\"area_id\": \"6\",\"area_name\": \"Pallikarani\",\"pincode\": \"600100\"}]}"
   },
   {
      "configurationId":8,
      "configurationName":"order_timing",
      "configurationVal":"[{\n\t\"start_time\": \"17:00:00\",\n\t\"end_time\": \"03:00:00\"\n}]"
   }
]

A: Use the following snippet to parse the JsonArray.
String jsonStr = "[{ "configurationId": 1, "configurationName": "CGST",........]";
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    int configurationId = jsonobject.getInt("configurationId");
    String configurationName = jsonobject.getString("configurationName");
    String configurationVal = jsonobject.getString("configurationVal");
}

For the last 2 "configurationVal" are JsonObject itself. So you've to parse again.
Hope it'll help.

A: My goal whenever I do a lot of coding for answers if to make sure you actually understand what you are doing and not just copy and paste my code into your project. If you never worked with instanceof, I advise you to read up on it. If you have ANY questions, please ask me.
I will get you started. Why? You showing no code in your post, so I will explain what to do with this.
    JSONArray object = new JSONArray(jsonData);
    //jsonData if the JSON String.
    String configVal = null;

    JSONArray configArray = null;
    JSONArray timingArray = null;

    boolean hasAreas = false;
    boolean hasTiming = false;
    try {
        for (int i = 0; i < object.length(); i++) {
            JSONObject getJSONObject = object.optJSONObject(i);

            if (getJSONObject.get("configurationVal") instanceof JSONObject) {
                JSONObject configValObject = getJSONObject.getJSONObject("configurationVal");
                configArray = configValObject.getJSONArray("availableAreas");
                hasAreas = true;
            } else if (getJSONObject.get("configurationVal") instanceof JSONArray) {
                timingArray = getJSONObject.getJSONArray("configurationVal");
                hasTiming = true;
            }  else {
                configVal = getJSONObject.getString("configurationVal");
            }

            String configName = getJSONObject.getString("configurationName");
            int configId = getJSONObject.getInt("configurationId");

            if (hasAreas) {
                System.out.println("ConfigVal: " + configVal + ", ConfigName: " + configName + ", ConfigId: " + configId + ", AreaInformation: " + configArray);
            }
            if (hasTiming) {
                System.out.println("ConfigVal: " + configVal + ", ConfigName: " + configName + ", ConfigId: " + configId + ", TimingInfo: " + timingArray);
            }
            if (!hasAreas && !hasTiming) {
                System.out.println("ConfigVal: " + configVal + ", ConfigName: " + configName + ", ConfigId: " + configId);
            }
            //Reset these...
            hasAreas = false;
            hasTiming = false;
            configVal = null;
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

This will print out the following.
ConfigVal: 2.5, ConfigName: CGST, ConfigId: 1
ConfigVal: 2.5, ConfigName: SGST, ConfigId: 2
ConfigVal: 0, ConfigName: DELIVERY_CHARGE, ConfigId: 3
ConfigVal: 9500100042,8939404592, ConfigName: Admin_Mobile, ConfigId: 4
ConfigVal: 98, ConfigName: MIN_ORDER_AMOUNT, ConfigId: 5
ConfigVal: 3, ConfigName: Packing_charge, ConfigId: 6
ConfigVal: , ConfigName: available_areas, ConfigId: 7, AreaInformation: [{"area_name":"Velachery","pincode":"600042","area_id":"1"},{"area_name":"Nanganallur","pincode":"600061","area_id":"2"},{"area_name":"Adambakkam","pincode":"323546","area_id":"3"},{"area_name":"Madipakkam","pincode":"600091","area_id":"4"},{"area_name":"Perungudi","pincode":"600096","area_id":"5"},{"area_name":"Pallikarani","pincode":"600100","area_id":"6"}]
ConfigVal: , ConfigName: order_timing, ConfigId: 8, TimingInfo: [{"start_time":"17: 00: 00","end_time ":"03: 00: 00"}]

Now, has you can see, the available_areas and order_timing is not parsed. I did, however, give you the information in a JSONArray. So you can follow what I did and parse it out. However, I would use a model for this with a List<>. It would be easier to work with.


text:
Q: Android application installation on an older version via eclipse I am a complete newbie to android development, though I know a thing or two about programming. I was trying to install an app that I had developed (a single .java file) in eclipse on my gingerbread phone, but the eclipse IDE fails to recognize my phone as a VALID device to install the app. Maybe because I have developed it in ADT 16 (4.1). Is there any way  to install the app on my phone?

A: You have to change the Minimum Version of your Android App, Right Click on the Project, Go to Properties, Select android & Change the Version from android 4.1 to the Version of your mobile Device.  Clean the Project & Run Again, Copy the new *.apk to android, It should work now


text:
Q: Where clause, multiple sets of conditions I am trying to produce a single table query result with error payment data filtered out by the conditions below. I am unable to get the query to filter out all of the sets of conditions, only the first 3. I have tried different ordering as well as making the last two condition sets a sub-query.
How can I filter out all the below conditions?
Again, 1,2 and 3 seem to have the desired result.Conditions 4 and 5 function, just not when following conditions 1,2 and 3
 select [history].[id]
            [history].[trans],
            CAST([history].[paid_dt] AS Date),
            CAST([history].[due_dt] AS Date),

     FROM [history]

     LEFT OUTER JOIN [information] ON [history].[id] = [information].[id]

    --Condition 1--
            WHERE NOT  ([history].[trans]  IN
            ('TRSF',
             'TRR',
              'BEG',
             'DTR',
             'LTC',
           ))

             OR
    --Condition 2--
            (CONVERT(date,[paid_dt]) = '2015-12-30'
            AND [trans] = 'ADJE')

            OR
    -- Condition 3--
            ([history].[paid_dt] = [information].[date]
            AND [history].[trans] LIKE '%ADJE%'
            AND [history].[due_dt] < '2017-01-01')

    --Condition 4--
            OR
                 (datepart(dd, [paid_dt]) = 8)
        --assume there is more to this condition--

           OR
    --Condition 5--
                 (CONVERT(date,[history].[paid_dt]) = '2018-01-08'
             and [history].[trans] = 'MANR'));

Just looking for insight as how to address

A: 'NOT' acts only on one condition.  If you don't want any of the other conditions to be returned if true... try surrounding all conditions following the 'NOT' keyword in parentheses.  Also, double check where you have your parentheses.  I'm still seeing an odd number of those maybe due to pasting.
WHERE NOT
    (
        (Condition 1)
         OR
        (Condition 2)
     )

You can also try getting away from the 'NOT' keyword by using <> references instead.


text:
Q: Makefile all command I'm in the process of learning c, and trying to get my head around makefiles. I'm following Learn C the Hard way.
On exercise 2, the extra credit states to make a command in my makefile that allows me to compile my .c file by typing just "make".
My makefile is:
CLAGS=-WALL -g

all: ex1

clean:
    rm ex1

This works - i.e. typing make clean removes the ex1 file, and typing make compiles ex1.c into an executable.
However, I'm confused as to why in the clean command, rm ex1 has to be indented on the line below clean, but for the all command, if I indent ex1 on the line below all, it throws an error. Why is this?
My other question is - how exactly does this work? Is all just a keyword that goes along the lines of "when make (with no command) is typed, do this"?
Any help is appreciated.
Thanks.

A: This:
clean:
    rm ex1

is a rule. This rule contains a single command, rm ex1. The command is a shell command. Each command in the rule must be indented with a TAB character (or Make will get confused).
This:
all: ex1

is a rule without commands. The "ex1" here is not a command, it is a prerequisite.
This:
all:
    ex1

is an invalid rule, because it contains an invalid command; "ex1" is not a valid shell command. (Just try it on the command line if you don't believe me.)
If you execute Make without specifying a target (by typing "make"), Make will use the default target, which is usually the first target in the makefile. (There are some exceptions you need not worry about now.) By convention, "all" is the name of rule that does most of what you want done, and it is often the default target; this is a convention, not something built into Make.

A: Because ex1 is a target that defaults to calling cc over a ex1.c file, you could make all: a target like this too
all:
    $(CC) -o $(EXECUTABLE) $(CFLAGS) $(LDFLAGS) ex1.c

don't copy and paste this, because i've used spaces and Makefiles require tabs instead.
An even better way would be to create an object files target and compiling only changed files while linking in the other target, like this
CC      = gcc
CFLAGS  = -Wall -Wextra -Werror
LDFLAGS = # empty if you are not going to link to any library
OBJ     = ex1.o
PROGRAM = ex1

all: $(OBJ)
    $(CC) $(CFLAGS) $(LDFLAGS) -o $(PROGRAM) $(OBJ)

%.o: %.c
    $(CC) $(CFLAGS) -c $<

clean:
    rm -fv *.o $(PROGRAM)

now you would easily add more .c files by just appending them to the OBJ macro, like this
OBJ = ex1.o ex2.o ... exn.o


text:
Q: PHP parse files function - Save to DB I have been at this most of the day today, so I normally have success with iterations and working with keys/values. This time its not easy easy it seems, running back and forth between the php docs and trailing difference sources, no luck but this is as close as I came.
So in this code, we are checking ../../uploads for all *.torrent files and parsing each one and saving as BLOB => database.
The code works wonderfully, with individual uploads. So I decided to loop it all together and send all of the files to the database based on their DB ID / FILE ID (which all match). So the logic there was easy.
This is the code I have
// Start parsing files => DB => LONGGLOB
foreach (glob("../../uploads/*.torrent") as $filename) {

    // Match file ID with database ID (WHERE CLAUS)
    $fileid = str_replace('.torrent', '', $filename);
    $filename1 = str_replace('../../uploads/', '', $filename);

    $fp = fopen('../../uploads/'.$filename1, 'rb');
    //$fp = fopen($_FILES['torrent']['tmp_name'], 'rb');
    $data = '';
    while (!feof($fp)) {
        $data .= fread($fp, 8192);
    }
    fclose($fp);

    $arr = bdecode($data);
    if ($arr === false) {
        die('invalid torrent');
    }

    // TODO: more validity checks for torrent?

    if (!array_key_exists('info', $arr)) {
        die('invalid torrent');
    }

    $arr['info']['private'] = 1;

    $infobc = bencode($arr['info']);
    if ($infobc === false) {
        die('bencoding error');
    }

    $info_hash = sha1($infobc);
    $total_size = 0;

    if (array_key_exists('files', $arr['info'])) {
        foreach ($arr['info']['files'] as $file) {
            if (array_key_exists('length', $file)) {
                $total_size += $file['length'];
            }
        }
    } else if (array_key_exists('length', $arr['info'])) {
        $total_size += $arr['info']['length'];
    }

    $description = 'dsfsdfDESCR';
    $name = 'dsfsdfNAME';

    // BEncode data and send it to DB
    $data = bencode($arr);
    $an = array_key_exists('anonymous', $_POST);
    $db->query_params("UPDATE torrents SET user_id = :user_id, name = :name, descr = :description, anon = :anonymous, data = :data, info_hash = :info_hash, size = :total_size WHERE torrent_id = :torrentid", array('user_id' => $_SESSION['user']['user_id'], 'name' => $name, 'description' => $description, 'anonymous' => $db->encode_bool($an), 'data' => $data, 'info_hash' => $info_hash, 'total_size' => $total_size, 'torrentid' => $fileid)) or die('db error');
}

I got it looping each file finally. But the issue now is it is revealing the first file, but its not continuing on and actually parsing file by file (lowest ID => highest ID, either order), producing errors in a snow ball effect.
I've made many many attempts already, down to complaints about fopen() 1st param, so I fixed that, now its not iterating properly. I believe its my logic here and i can't understand it.
So $data = bencode($arr) needs to parse each metafile and send it as it does perfectly with upload form as commented out ($fp). Any help is appreciated.
I've listed files using all different methods, this time its the blob function. How can I iterate each file and parse it => next file ??
The commented sections are perfectly working. But we need to parse per-file-id basis.

A: Answered another one myself again. I gotta stop running here at my last option, anyways this is the solution for those who need it. I got it an hour later and I thank php.net gratefully!
Solution:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dir = new DirectoryIterator('../../uploads');
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
            $getthelist = $fileinfo->getFilename();
            $fp         = fopen('../../uploads/' . $getthelist, 'rb');
            $data       = '';
            while (!feof($fp)) {
                $data .= fread($fp, 8192);
            }
            fclose($fp);
            $arr = bdecode($data);
            if ($arr === false) {
                die('invalid torrent');
            }
            if (!array_key_exists('info', $arr)) {
                die('invalid torrent');
            }
            $arr['info']['private'] = 1;
            $infobc                 = bencode($arr['info']);
            if ($infobc === false) {
                die('bencoding error');
            }
            $info_hash  = sha1($infobc);
            $total_size = 0;
            if (array_key_exists('files', $arr['info'])) {
                foreach ($arr['info']['files'] as $file) {
                    if (array_key_exists('length', $file)) {
                        $total_size += $file['length'];
                    }
                }
            } else if (array_key_exists('length', $arr['info'])) {
                $total_size += $arr['info']['length'];
            }
            $fileid = str_replace('.torrent', '', $getthelist);
            $data   = bencode($arr);
            $an     = array_key_exists('anonymous', $_POST);
            DB::run("UPDATE torrents SET data = :data, info_hash = :info_hash, size = :total_size WHERE torrent_id = :torrentid", array(
                'data' => $data,
                'info_hash' => $info_hash,
                'total_size' => $total_size,
                'torrentid' => $fileid
            )) or die('db error');
        }
    }
}

DirectoryIterator() was the answer here. While other methods worked, they were not as efficient or logical as this way. It works perfectly as expected.


text:
Q: How to build an open-ended Excel VBA Function that allows multiple input variables (arg1, arg2, arg3, arg4, arg5) I'm trying to make a simple averaging function that does a bit of extra data processing.
The problem I'm facing is that I can currently work with a range input with my code (AvgFunc(rng as Range)), however when selecting multiple inputs ([In a cell] =AvgFunc(A1, B8, C22)) it breaks.
So I decided instead of making a universal function code, I wrote a separate code to deal with the problem
Public Function AvgFunc_Selection(arg1 as Double, arg2 as Double, arg3 as Double, arg4 as Double, arg5 as Double)

However I'm obviously doing something wrong because I cannot get beyond that point.
Any suggestions on how to make a function that works with multiple inputs?
Here is the full code:
Public Function AvgFunc_Selection(arg1 As Double, arg2 As Double, arg3 As Double, arg4 As Double, arg5 As Double)

Dim temp1 As Double
Dim temp2 As Double
Dim Count As Integer

temp1 = arg1
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg2
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg3
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg4
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg5
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If

AvgFunc_Selection = temp2 / Count

End Function

A: This can be done much simpler using ParamArray and a loop, allowing an "endless" series of arguments:
Public Function AvgFunc_Selection(ParamArray Args() As Variant) As Double

    Dim Index   As Integer
    Dim Count   As Integer
    Dim Value   As Double
    Dim Average As Double

    If UBound(Args) = -1 Then
        ' No arguments passed.
    Else
        ' Calculate the count.
        Count = 1 + UBound(Args) - LBound(Args)
        ' Calculate the sum of values.
        For Index = LBound(Args) To UBound(Args)
            If IsNumeric(Args(Index)) Then
                Value = Value + CDbl(Args(Index))
            End If
        Next
        ' Calculate the average.
        Average = Value / Count
    End If

    AvgFunc_Selection = Average

End Function

A: So apparently my problem was not including the term "Optional" in front of each argument.
Here's the corrected code:
Public Function AvgFunc_Selection(Optional arg1 As Double, Optional arg2 As Double, Optional arg3 As Double, Optional arg4 As Double, Optional arg5 As Double)

Dim temp1 As Double
Dim temp2 As Double
Dim Count As Integer

temp1 = arg1
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg2
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg3
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg4
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If
temp1 = arg5
If temp1 > 0 Then
temp2 = temp2 + temp1
Count = Count + 1
End If

AvgFunc_Selection = temp2 / Count

End Function

That should work. It works for my application.


text:
Q: Am I using Factory and Impl classes properly? In my 2d destruction derby simulator I have a CargoTruck class and CargoTruckImpl that implement an interface called Truck. CargoTruck has a reference to CargoTruckImpl which is returned through the CargoTruckImplFactory.
But then I decided to add to this chain by having CargoTruckImpl and CargoTruckMovementImpl use the interface called Movement. CargoTruckImpl has a reference to CargoTruckMovementImpl which is returned back to CargoTruck through the MovementImplFactory.
CargoTruck->CargoTruckImpl->CargoTruckMovmentImpl
FuelTruck->FuelTruckImpl->FuelTruckMovmentImpl
Is adding to the chain like this bad? Am I violating the Separation Principle or the Open-Closed Principle by using Factory classes this way? Is there a better way of doing this?

A: It's great that you're applying some of the SOLID principles! However, I'd be a little suspicious about the number of Impl classes and Factory classes you're implementing (CargoTruck and CargoTruckImpl sound like the same class to me for example). It sounds like you might want to apply some DI principles here (or at least have something like Guice do some of this heavy lifting for you).
I always go back to Martin Fowler's article on DI when I start to worry about creating too many Factories etc, it might help clarify your thinking in this area.

A: What is MovementImplFactory doing for you here?  Abstract it and separate the instances into their domains.
This would have an AbstractMovementImplFactory being extended by CargoTruckMovementImplFactory and FireTrucImplkMovementFactory.
Then have your instances of the Trucks have references to the appropriate factories  For example, construct CargoTruckImpl to have a reference to CargoTruckMovementImplFactory.  When you need a movement for that truck, it can use its domain-specific factory to build it, and you've separated the movement logic from the truck logic.


text:
Q: how to link a binary vs a symlink and not an actual library? I have a meson file that declares a dependency:
meson.get_compiler('cpp').find_library('name'),
where name can be found in:

*

*/usr/lib/libname.so -> /usr/lib/libname.so.1.2.3

*/usr/lib/libname.so.1.2.3

I want meson to link vs. the symlink alone - so when running the executable on another machine, with another version of libname -it would still work, and not give me:
can't find libname.so.1.2.3

A: I created dependency for my test application with:
dep = meson.get_compiler('c').find_library('ssh')

The executable points to
ldd ./build/test_proj | grep libssh
libssh.so.4 => /lib/x86_64-linux-gnu/libssh.so.4 (0x00007f3d668b8000)

And, surely, this is a symbolic link with major number pointing
$ ls -alt /lib/x86_64-linux-gnu/libssh.so*
lrwxrwxrwx 1 root root     37 Aug 29 00:13 /lib/x86_64-linux-gnu/libssh.so -> /lib/x86_64-linux-gnu/libssh.so.4.8.4
lrwxrwxrwx 1 root root     15 Aug 18  2021 /lib/x86_64-linux-gnu/libssh.so.4 -> libssh.so.4.8.4
-rw-r--r-- 1 root root 445976 Aug 18  2021 /lib/x86_64-linux-gnu/libssh.so.4.8.4

Thus, it's major number that is crucial and decides on selection of library, not minor numbers.
I made an experiment: removed libssh.so.4 and linker cache (/etc/ld.so.cache) to force your situation so I have only:
$ ls -alt /lib/x86_64-linux-gnu/libssh.so*
lrwxrwxrwx 1 root root     37 Aug 29 00:13 /lib/x86_64-linux-gnu/libssh.so -> /lib/x86_64-linux-gnu/libssh.so.4.8.4
-rw-r--r-- 1 root root 445976 Aug 18  2021 /lib/x86_64-linux-gnu/libssh.so.4.8.4

In this case linkage failed:
ninja: Entering directory `build'
[2/2] Linking target test_proj
...
    libssh.so.4 => not found

So, I think you're missing libssh.so.4 link and major number is a must since it guarantees API conformance.


text:
Q: Boost not finding zlib package on Ubuntu 20.04 I'm trying to compile Boost with the zlib package built into Ubuntu, but it cannot find it and thus gives me a zlib : no upon running ./b2.
I definitely have it installed, as dpkg -L zlib1g-dev and dpkg -L zlib1g give me their locations.
I've tried manually passing in the directories as command-line options as suggested here, and I've also tried creating a user-config.jam file as suggested here, but nothing has worked.
Any ideas as to what might be the problem?

A: For unclear reasons, the solution was just to get rid of everything in the Boost directory and recompile + reinstall Boost. After that it was able to find zlib (and bzip2) without any problems.


text:
Q: How do I display random blog posts, favoring posts with high ratings? Let's say I have a Blog posts table that has a rating field which indicates the quality of the post. What is the most efficient way to randomly find a post, with a higher chance of returning a highly ranked post?
I will be implementing this in PHP, MySQL, and possibly Lucene.

A: An easy solution would be to include calls to RAND() and to the rating column and multiplying them together:
SELECT title, content FROM blog_posts ORDER BY (rating + 1) * RAND() DESC LIMIT 1;

If you found this gave too much precedence to items with a high rating, you could use SQRT:
SELECT title, content FROM blog_posts ORDER BY SQRT(rating + 1) * RAND() DESC LIMIT 1;

A: You could use a "weighted random" ordering, such as:
SELECT title, body FROM posts ORDER BY (score+1) * RAND() DESC LIMIT 5

The +1 is there to allow posts with 0 score to be selected. Depending on the average score of your post you may have to multiply the score by another constant factor (e.g. 0.5*score+1).
Depending on the distribution of your scores you may want to transform your score, for instance with LOG(score) or SQRT(score).

A: SQL COMMAND :
SELECT * FROM posts WHERE id = '$randomly_generated_ids' ORDER BY ratings ASC

for example $randomly_generated_ids can be "13,10,5,20"
Details for : ORDER BY


text:
Q: How to make smiley scrollable from input field In my chat system i am adding smileys from a list that i have.
QUESTIONS
I would like to make those smileys scrolls down like this website  does

only that i would like it to be in the input file so that right from the input file, my visitors can choose a smile and as they click the code goes to the input file.
So far this is the script i have that adds smileys on click

  </script>

<input type="text" id="description" name="description">

How can i achieve that please ?
Thanks

A: You can try inheriting from the website example you have provided. You need to add jquery and bootstrap JS as dependencies. Check this Fiddle
JS Code:
function textWithSmilies(text) { // Function that change the textarea content in a string including smilies icons
    // Create 2 array: 1 containing the smiley BBCode, the second containing a part of their file name
    var findSmiliesShortcuts = [/:smile:/g, /:sad:/g, /:arrow:/g, /:cool:/g, /:cry:/g, /:grin:/g, /:confused:/g, /:bigeyes:/g, /:evil:/g, /:exclaim:/g, /:geek:/g, /:idea:/g, /:lol:/g, /:mad:/g, /:green:/g, /:neutral:/g, /:question:/g, /:happy:/g, /:redface:/g, /:rolleyes:/g, /:surprised:/g, /:devil:/g, /:wink:/g];
    var replaceSmiliesImg = ['smile', 'sad', 'arrow', 'cool', 'cry', 'grin', 'confused', 'bigeyes', 'evil', 'exclaim', 'geek', 'idea', 'lol', 'mad', 'green', 'neutral', 'question', 'happy', 'redface', 'rolleyes', 'surprised', 'devil', 'wink'];

    for (i = 0; i < findSmiliesShortcuts.length; i++) {
        text = text.replace(findSmiliesShortcuts[i], ''); // Replace all smilies BBCode by their image
    }
    text = text.replace(/\n/g, '
'); // Replace new lines by

    return text;
}

$(function() {
    // This function allow to insert text or smiley in the textarea where the cursor is
    jQuery.fn.extend({
    insertAtCaret: function(myValue) {
      return this.each(function(i) {
        if (document.selection) {
          //For browsers like Internet Explorer
          this.focus();
          sel = document.selection.createRange();
          sel.text = myValue;
          this.focus();
        }
        else if (this.selectionStart || this.selectionStart == '0') {
          //For browsers like Firefox and Webkit based
          var startPos = this.selectionStart;
          var endPos = this.selectionEnd;
          var scrollTop = this.scrollTop;
          this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
          this.focus();
          this.selectionStart = startPos + myValue.length;
          this.selectionEnd = startPos + myValue.length;
          this.scrollTop = scrollTop;
        } else {
          this.value += myValue;
          this.focus();
        }
      })
    }
    });

    $('#myTextarea').val(''); // We first empty the textarea

    $('#myForm #clear').click(function() { // Clear everything when click on the "Clear" button
        $('#myTextarea').val('');
        $('#output').text('');
        $('#submitOutput').text('');
    });

    $('#myForm #submit').click(function() { // When click on "Submit" button
        $('#submitOutput').html('
' + textWithSmilies($('#myTextarea').val()) + '
'); // Add the textarea content in the
 markup
    });

    $('img#addSmiley').on('click', function() { // When click on a smiley
        smiley = $(this).attr('alt'); // We take it's attribute alt which contains the unique smiley BBCode choosen
        $('#myTextarea').insertAtCaret(smiley); // Call the function "insertAtCaret" and insert the smiley BBCode in the textarea where the cursor is

        var text = textWithSmilies($('#myTextarea').val()); // Call function "textWithSmilies" and change smilies BBCode by their icon
        $('#output').html(text); // Display in div=output markup

        return false;
    });

    $('#myTextarea').keyup(function(){ // When keyup in the textarea (when you pull up the key)
        var text = textWithSmilies($(this).val()); // Call function "textWithSmilies" and change smilies BBCode by their icon
        $('#output').html(text); // Display in div=output markup
    });
});

HTML Code:
<input type="text" id="description" name="description"/>

                    <button data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button">

                    </button>


text:
Q: Install Android Studio software without admin privileges on Windows 7 I'm trying to install Android Studio software to work, on a company machine which has no admin rights. Can I install Android Studio software without admin rights?
I tried direct extraction using 7zip, no luck.
I tried spoofing admin account, no luck.
I'm using Windows 7 machine, connected to a company network with my only ID that can login to the system.
Why don't Android Studio just run like Eclipse does it, huh!
Does any know how can this be achieved?
EDIT:
FYI when I tried using 7zip:

A: Yes, I did same thing what you want.
I downloaded android studio from
http://tools.android.com/download/studio/builds/2-3-0

unzip it and run studio which located in bin/Studio64.exe
It's working great, remember you need java installed to run it.
You can choose type of channels mention in same link under Download

You do not get SDK with this, so go to download sdk only  and download sdk from there
Open your android studio, go to project structure in file menu, change the sdk location to your downloaded sdk path. That's it. Now every thing is setup.


text:
Q: sql server - xml query - concat - adding space I want to take a xml string and convert it to sql-table semicolon-delimitate
declare @x xml --for example
set @x = '<root><row>a1b2</row><row>aa1bb2</row></root>'
SELECT T.c.query('.').query('for $i in row/*/text() return concat($i,";")').value('.', 'nvarchar(max)') AS result
FROM   @x.nodes('root/row') T(c)

The Result:
a1; b2;
aa1; bb2;

The Result I want: (no space)
a1;b2;
aa1;bb2;

>> Bonus: Remove last semicolon
a1;b2
aa1;bb2

Thank You!

A: A combination of REPLACE, REVERSE, and STUFF is how i was able to achieve this:
declare @x xml --for example
set @x = '<root><row>a1b2</row><row>aa1bb2</row></root>'
SELECT reverse(stuff(reverse(replace(T.c.query('.').query('for $i in row/*/text() return concat($i,";")').value('.', 'nvarchar(max)'), ' ', '')), 1, 1, '')) AS result
FROM   @x.nodes('root/row') T(c)

There might be a better way to get rid of the spaces since this would also replace any spaces in the XML node values as well.

A: This can be done much easier:
DECLARE @xml XML='<root>
  <row>
    a1
    b2
  </row>
  <row>
    aa1
    bb2
  </row>
</root>';

SELECT (
      STUFF(
      (
          SELECT ';' + v.value('.','nvarchar(max)')
          FROM r.nodes('*') AS B(v)
          FOR XML PATH('')
      ),1,1,'')
      )
FROM @xml.nodes('/root/row') AS A(r)

A: declare @x xml --for example
set @x = '<root><row>a1b2</row><row>aa1bb2</row></root>'
SELECT reverse(stuff(reverse(replace(T.c.query('.').query('for $i in row/*/text() return concat($i,";")').value('.', 'nvarchar(max)'), '; ', ';')), 1, 1, '')) AS result
FROM   @x.nodes('root/row') T(c)


text:
Q: Using implicit as type constraint As far as I know, there are two ways to add type constraint.
trait Dummy

First way
def doStuff[T <: Dummy](x: T) = x

Second way
def doStuff[T](x: T)(implicit x: T <:< Dummy) = x

Both achieve the same result.
I just wonder that what kind of scenarios I should use the upper bound or lower bound directly, or I should use implicit to append the constraint on the type.

A: One necessitates the creation of an implicit object on each invocation of the call, the other merely places a type constraint on the object passed into the function. In general, I would prefer the declaration wherein you state [T <: Dummy] rather than the implicit.
Where you'd use the implicit is when you want to create a type which can do certain things but only if it satisfies a certain constraint. Hence, you see the following in List[A] declaration:
 def sum(implicit ev: Numeric[A]) = ...

which is a nice way of saying "you can place any type 'A' in the class but if you want to use 'sum' it has to conform to..." Take for instance the following class definition:
 class Foo[T](value: T){
   def doubleString = value.toString() + value.toString()

   def specialSauce(implicit ev: T <:< Dummy): Dummy = ...
 }

This allows me the option to create some type of Foo[Int] and it will work but won't allow me to call the specialSauce method of the class unless T is a direct descendent of Dummy.


text:
Q: Characterization of globally lipschitz function in terms of derivatives I would like to know if the following generalization of the characterization of globally lipschitz functions in the class $\mathcal{C}^1$:

Let $f:I \to \mathbb{R}$, $I \subseteq \mathbb{R}$ an interval.
If $f \in \mathcal{C}^1$ then $f$ is globally lipschitz $\iff \exists
 L \ge 0.\forall t \in I.|f'(t)| \le L$

The generalization goes as follows:

A scalar function is globally lipschitz iff its derivative exists and is
  bounded except in a set of measure zero.

Is this still true? Has it been studied/asked before?

A: It is not true. The Cantor-Vitali function is continuous in $[0,1]$, differentiable almost everywhere with zero derivative, but it is not Lipschitz continuous.


text:
Q: A good tactic for mining hellstone?
Possible Duplicate:
How can I navigate and mine hell safely?

I'm wondering if there's a good tactic for mining hellstone. Since I have full Shadow armor, and still I get killed damn easily by mobs in Underworld, is there something I'm missing?
Should I get some special equipment?

A: Obsidian skin potions and water breathing potions are a great combination, as they allow you to mine from within the lava, where the only enemy you have to worry about are bone dragons.


text:
Q: Are there any issues when choosing \t as a delimiter inside keys in Redis? I'm looking into delimiters for namespaces in Redis keys. Because the article numbers and stuff I'm going to use as parts of the keys have a lot of chars like :, -, _ and so on. I was thinking to use a tabulator \t. Are there any known issues with that?

A: It's safe to use whatever characters you want inside redis keys, redis is binary safe.
We even use null characters inside keys in some specific situations. From a binary client (so not a command line tool like redis-cli) even null characters are fine.
This is described in the redis.io datatypes. A redis string is binary safe, and more advanced redis datatypes use redis strings.
A note on null characters inside keys:
A real-world scenario is the use of UUID byte sequences (instead of its ascii GUID representation) as keys. You would choose this for minimizing memory usage. Another is when using the MsgPack serialization format (natively supported in redis Lua scripting), which is binary, and certainly contains null characters now and then. The downside of using null characters is, ofcourse, readability when debugging or logging, the ability to do easy command-line piping, and/or usage of the interactive redis-cli client.
Hope this helps, TW


text:
Q: How do you deal with subsequent events in JavaScript when the previous one has not yet finished processing? How do you deal with subsequent events in JavaScript when the previous one has not yet finished processing?
I have a textbox with the onkeyup event defined. When the event occurs it invokes a function that can take longer to process than it can for the next onkeyup event to fire in most situations.
Is there a solid way of interrupting/abandoning the previous onkeyup event and just start on the next one?

A: You could do something along this line:
var isRunning = false;
var i = 0;
function runFunc() {
    i++;
    if (isRunning == false) {
        isRunning = true;
        keepRunning();
    }
}
function keepRunning() {
    while (i > 0) {
        realProcessing();
        i--;
    }
    isRunning = false;
}
var el = document.getElementById('field');
el.onkeyup = runFunc;

keepRunning() will keep executing the real processing function as many times as the keyup event was fired
I wrote this off my mind and didn't test it (shame on me), but this way you can probably achieve your results (or with something similar).
ps: I still think that you can have concurrency issues with the code above, and I'd be very interested in finding solutions to those (or someone proving me that there are no concurrency issues).

A: Javascript works like a GUI so no two events are processed at the same time.
The best solution if your processing is too heavy in my opinion would be changing your it so that it can be performed in small steps. Then when you get a keyup event you just do the first step and each step does a setTimeout call with a zero delay to trigger next step
This way restarting your computation is trivial.
It works because timeouts always are the lowest priorities (i.e. if there will be another keyup this will be processed immediately and you will restart the computation instead of continuing the previous one).


text:
Q: I am trying to automate dropdown list in selenium web driver using Page object model. Below is my code explanation: // Language Selection
    public static void SelectLanguage() {
        waitForElementToBeClickable(driver.findElement(By.xpath("//div[@class=\"lang-identifier\"]")));
        driver.findElement(By.xpath("//div[@class=\"lang-identifier\"]")).click();
        List<WebElement> elements = driver.findElements(By.xpath("//ul[@class=\"dropdown-menu pull-right\"]/li"));
        for (WebElement e : elements) {
            String text = e.getAttribute("value");
            System.out.println(e.getText());
            if (text.equalsIgnoreCase("English")) {
                e.click();
                break;
            } else if (e.getText().equalsIgnoreCase("Español")) {
                e.click();
                break;
            } else if (e.getText().equalsIgnoreCase("Italiano")) {
                e.click();
                break;
            } else if (e.getText().equalsIgnoreCase("Pусский")) {
                e.click();
                break;
            } else if (e.getText().equalsIgnoreCase("Français")) {
                e.click();
                break;
            } else if (e.getText().equalsIgnoreCase("Português")) {
                e.click();
                break;
            } else {
                System.out.println("Please select appropriate language");
            }
        }

    }

A: I would suggest a much simpler but more flexible version of your method.
Some suggestions:

*

*I would change your method to take the desired language as a parameter to significantly simplify the code but also make it very flexible.

*WebDriverWait, in most cases, will return the found element(s). Use that to simplify your code to a one-liner, e.g.
new WebDriverWait(...).until(ExpectedConditions.elementToBeClickable).click();

You didn't provide the code of your custom method, waitForElementToBeClickable, but if you really want to keep it, have it return the element(s) waited for to make it more useful and save having to write extra code.

*If you have nested double quotes, I would suggest you use a combination of double and single quotes. It's a personal preference but I think it makes it easier to read than \", e.g.
"//div[@class=\"lang-identifier\"]"

would turn into
"//div[@class='lang-identifier']"

*Instead of grabbing all options and then looping through them to compare the contained text to some desired string, use an XPath that contains the desired text instead, e.g. for "English" the XPath will look like
//ul[@class='dropdown-menu pull-right']/li[text()='English']

*NOTE: .getAttribute("value") gets the value of an INPUT and will not work on other elements, e.g. the LI elements in your elements variable. .getText() returns the text contained in an element but will not work on INPUTs.
After implementing these suggestions, the code turns into a two-liner and is very flexible.
public static void SelectLanguage(String language) {
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.lang-identifier"))).click();
    driver.findElement(By.xpath("//ul[@class='dropdown-menu pull-right']/li[text()='" + language + "']")).click();
}


text:
Q: Sudo for OpenLDAP I needed to install sudo-ldap support for LDAP enabled server.
The question:
On which machine (ldap-client or ldap-server) I have to build & install the package I dowloaded from www.sudo.ws ?
Thanks

A: If your goal is to use the sudo package built with LDAP support so that you can have the sudoers database distributed via LDAP, then you have to install this package on every server you want to use sudo!
Note: each server shall have libldap installed.
It is no required on your LDAP server per se.
But you can also install on it if you want to use this version of sudo.


text:
Q: How to Iterate only last column data of each row, When the table decreases exponentially I have a HTML table with tr and td.The values gets changed according to the Date selection given. I need to iterate each row, last column data and add them.  The value decreases by one for each row.
Please help me, How to get only last column data of each row. The image is attached below and it is highlighted.
ClickHere
HTML code

Time
Installs
1
2
3
4
5

October 2016
3
3
1
0
0
**0	**

November 2016
16056
10790
7861
7186
**7186	**
-

December 2016
85254
38098
33857
**33790	**
-
-

January 2017
24814
14883
**14839	**
-
-
-

February 2017
227
**226	**
-
-
-
-

March 2017
**0	**
-
-
-
-
-

If you see the above image, The values are decreasing exponencially and even the element tags are changing as cornelius-low, cornelius-high, cornelius-medium and so on.
I tried the below spinets of codes in keeping in loops. As the element tags are changing, unable to  fetch only 0, 7186, 33790, 14839, 226

A: Try to use below code to get last td of each tr:
List<WebElement> rows = driver.findelements(By.xpath('//table[@class="cornelius-table"]//tr[not(th)]'));
Iterator<WebElement> iter = rows.iterator();
while(iter.hasNext()) {
    WebElement tr = iter.next();
    td = tr.findelement(By.xpath('./td[not(@class="cornelius-empty")][last()]'));
    System.out.println(td.getText());
    }
}

A: @Andersson code should work for you. If not, then as per his suggestion there might be tbody popping up while the page is loaded. So, you can just replace his code to the one below (I have also added the WebElement Interface reference that was missing for td):
List<WebElement> rows = driver.findElements(By.xpath("//table[@class='cornelius-table']//tr"));
Iterator<WebElement> iter = rows.iterator();
while(iter.hasNext()) {
    WebElement tr = iter.next();
    WebElement td = tr.findElement(By.xpath("./td[not(@class='cornelius-empty') and last()]"));
    System.out.println(td.getText());
    }
}

If the above still doesn't work, you can try the below one, which is just the more optimized version using xpath:
List<WebElement> tabledata = driver.findElements(By.xpath("//table[@class='cornelius-table']//tr/td[not(@class='cornelius-empty') and last()]"));
for(WebElement td: tabledata)
 System.out.println(td.getText());

The above code will find all the last td element in each rows of table with class as cornelius-table and put it in a list tabledata. Then using for-each loop, iterate through the list tabledata, fetch and print the innerText.
EDIT I have modified the above code snippets as per the HTML snippet provided by OP.


text:
Q: Mass Linter submissions - (Like button related) - How to We operate a website with thousands of new content per month and use the Like button with OG tags.
However, very often the Like button does not work properly for content that was not refreshed by FB. As a FB admin on the site, I can manually paste the urls one by one in the Linter tool here http://developers.facebook.com/tools/debug but what would be the best way of making this process more automatic ? (Create a links page pointing to Linter with appended urls and then click on those one by one, RSS, submission engine, ... ?)
Thanks in advance.

A: This page does not require authentication so you could write a script that mass submits them via cURL or wget one by one via this url: https://developers.facebook.com/tools/debug/og/object?q=http://example.com

A: The solution such a Rss Feed facebook Linter might help.
It debugs all URLs in Feed.

A: I came across a Facebook mass url debugger
that reads the RSS feed of a website and lints them.


text:
Q: Execute php script from Python script Here I'm trying to execute a PHP script using Python but I get

Error : php not found

Should I have to install lammp(I'm using lubuntu 16.04) or is there any way to execute it directly without doing installation?
Here is my Python Script for calling php script.
import subprocess
#subprocess.call(["php", "textcleaner.php","bill.jpg out.jpg"])
proc = subprocess.Popen("php textcleaner.php, src.jpg", shell=True,stdout=subprocess.PIPE)
script_response = proc.stdout.read()

A: You must install PHP to execute php scripts on your system.

A: Either you don't have php installed or your python can't call the php library without a direct link.
If you don't have it installed you need to install it
apt-get install php5 libapache2-mod-php5

Or if you do have it installed change php to /usr/bin/php


text:
Q: Access properties in custom UIVIew I created Custom UIView with bunch of labels. label1, label2,
UIView *testContentView = [[[UINib nibWithNibName:@"testContentView" bundle:nil] instantiateWithOwner:nil options:nil] objectAtIndex:0];

How do I access the label and setting text ?

A: You need to define them on your interface.
@interface TestContentView : UIView

@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;

@end

And then...
testContentView.label1.text = @"foo";
testContentView.label2.text = @"bar";

Edit
Added IBOutlet to the properties since you are using a NIB, you will also need to wire these up in Interface Builder.

A: In order to access your custom properties, you need to cast the UIView to a TestContentView.
TestContentView *testContentView = (TestContentView *)[[[UINib nibWithNibName:@"testContentView" bundle:nil] instantiateWithOwner:nil options:nil] objectAtIndex:0];


text:
Q: MPMoviePlayerViewController problem with presentMoviePlayerViewControllerAnimated the problem is that if the movie has finished, the dismissMoviePlayerViewController is called automatically.
This means that the MoviePlayerViewController disappear, but I want he should be on screen if the movie has finished and only the 'Done' Button should do the dismiss...
here is my code:
- (void) buttonTapped:(id)sender {
 NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"dishes" ofType:@"mov"]];
 MPMoviePlayerViewController *movViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

 [url release];
 if(movViewController) {
  [movViewController.moviePlayer setShouldAutoplay:NO];
  [self presentMoviePlayerViewControllerAnimated:movViewController];
 }
}

Even the [movViewController.moviePlayer setShouldAutoplay:NO]; does nothing.
Thank you for answering
xnz

A: I think you are confused with what you are seeing versus what is actually happening. While the movie plays, the controls, including the Done button, are hidden. When the movie ends, they stay hidden. To un-hide them, the user has to touch the display somewhere, and the controls will reveal themselves - the VCR controls as well as the Done button and progress slider.


text:
Q: Why Doesn't Modal FadeOut Slowly? I inherited this modal/overlay/content close/empty method that works, but abruptly:
method.close = function () {
    $modal.hide();
    $overlay.hide();
    $content.empty();
    $(window).unbind('resize.modal');
};

To fade out gradually, I modified the method like below, but elements are left behind and subsequent clicks don't open new modals loaded with content, only the overlay:
method.close = function () {
    $modal.fadeOut('slow', function() {
        $(this).hide();
    });
    $overlay.fadeOut('slow', function() {
        $(this).hide();
    });
    $content.fadeOut('slow', function() {
        $(this).empty();
    });
    $(window).unbind('resize.modal');
};

What am I missing?
UPDATE: The solution is a single nested callback, based on garryp's answer, like this:
method.close = function() {
    $overlay.fadeOut('slow', function() {
        $overlay.hide();
        $content.empty();
    });
    $modal.hide();
    $(window).unbind('resize.modal');
};

A: Hide is asynchronous; the calls you have in your original code do not block while the transition occurs, execution moves immediately to the next. You need to use callbacks, like this:
var me = $(this); //Added to ensure correct this context
$modal.fadeOut('slow', function () {
    me.hide(function () {
        $overlay.fadeOut('slow', function () {
            me.hide(function () {
                $content.fadeOut('slow', function () {
                    me.empty();
                });
            });
        });
    });
});

Assuming the rest of your code is correct this should ensure the transitions fire one after the next.

A: Firstly, you do not need $(this).hide(). JQuery fadeOut automatically set display: none at the end of fading animation (read more: http://api.jquery.com/fadeout/).
That mean, in your case $content element will also have display: none after fadeOut animation. I expect you forgot to add $content.show() in modal open method.


text:
Q: A regular expression to find I want a case insensitive  expression that will logically find:
(stringA OR stringB) AND stringC.
So if stringA is "dr" stringB is "doctor" and stringC is "presume", I want these results:
Dr. Livinsgston I presume           TRUE
Doctor Livingston I presume         TRUE
Mr. Livingston I presume            FALSE

It does not matter where in the tested string the values reside, though if I could have the expression require that (A or B) precede the C in the tested string, that would be even better.
Is this doable with a regexp?

A: The Python solution posted above does the job; but on the off-chance that you also just wanted to learn how to do something like this, here's a possible solution (in JavaScript; syntax may vary in other languages):
/(dr|doctor).*?presume/i.test(...);

The i at the end makes it case-insensitive (equivalent to just converting the tested string to lower case beforehand). the | between the words in parenthesis makes it so that these two words can be interchangeable. The .*? just means that there can be pretty much anything between the stuff in parenthesis and presume.
Note that this means that presume has to be before the stuff in parenthesis. Honestly though, if order matters you're in for a lot of pain with regexes.

A: In Perl, you could do something like..
(?:[Dd]r|Doctor).*(?:presume)

Regular expression:
(?:                        group, but do not capture:
  [Dd]                     any character of: 'D', 'd'
     r                     match 'r'
     |                     OR
     Doctor                match 'Doctor'
)                          end of grouping
 .*                        any character except \n (0 or more times)
  (?:                      group, but do not capture (1 or more times)
    presume                match 'presume'
  )                        end of grouping

Short explanation of assertions. See Regex lookahead, lookbehind and atomic groups
(?=)    Positive look ahead assertion
(?!)    Negative look ahead assertion
(?<=)   Positive look behind assertion
(?<!)   Negative look behind assertion
(?>)    Once-only subpatterns
(?(x))  Conditional subpatterns
(?#)    Comment (?# Pattern does x y or z)

A: Very doable with regex, but there is absolutely no reason to use regex in this case. You didn't add a language, so here's a simple solution in python:
def check_string(test_string):
    lowered_string = test_string.lower()
    doctor = lambda s: "dr" in s or "doctor" in s
    presume = lambda s: "presume" in s
    return doctor(lowered_string) and presume(lowered_string)

In general you want to avoid using regex whenever possible, and you can easily make a check case-insensitive by just doing your check against a lower-case version of your string (like I did above.)
If you want to match it with a regex here's a version of d'alar'cop's answer that actually works (moved to python to keep my answer internally consistent):
import re
return bool(re.match( r'(dr|doctor).*?presume',test_string.lower()))

A: Yes, you can do this with regexp. With grep you can simply do this
echo Doctor Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
TRUE
echo Dr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
TRUE
echo Mr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE
FALSE