text:
Q: Determining all possible combinations from a list of values that sum to desired total I was asked a programming question by a friend about how to determine all possible combinations of values from a set can be added to make a desired total.  I have a solution, but it is less than elegant (its basically just a series of for-loops and if-statements).  I'm sure dplyr has a solution that I can't think of, as I know how useful it is but I just haven't gotten very good at it yet.  I will post the question and my script below.
Question:
There is a target with six rings on it, each ring is worth a different value. These values are either 1, 2, 3, 4, 5, or 6. How many different combinations of rings can you use to score EXACTLY 9 points?
So to consider:
  Order is not important
  You can use as few or as many values as you want
  You can get the same value more than once (so 9 1's is a totally valid option)
I had considered first using combn() from combinat package, but combn() does not replace values.
Then I decided to use a series of nested for loops and if statements (I truncated it to where you could only use a max of 6-values, because while I may have free time, I'm not a masochist about to write a loop that allows up to 9-values). So essentially, it is running through 6 for-loops worth of possible values.  I included the number 0 to the list of possible values to represent no attempt when I only need 2 values instead of 6 (so 4+5+0+0+0+0 is a valid output in this loop, but it wouldn't be able to do 4+5 as it would always try to add more non-zero values).
## Create a vector x with possible values
x = c(1,2,3,4,5,6)

## Add in value 0 because I need to be able to write this dumb loop that allows many terms to be used, but also allows smaller amounts of terms to be used

x = c(x,0);x

## Creating empty data.frame to input solutions to so that I can check for uniqueness of solution
df = data.frame("a" = as.numeric(),
            "b" = as.numeric(),
            "c" = as.numeric(),
            "d" = as.numeric(),
            "e" = as.numeric(),
            "f" = as.numeric())

for (a in x){
  for (b in x){
    for (c in x){
      for (d in x){
        for (e in x){
          for (f in x){
            m = sum(a,b,c,d,e,f)
            if(m == 9) {
              p = 0
              n = c(a,b,c,d,e,f)
              if (nrow(df) == 0){
                df[1,] = n
              }
              if (nrow(df) >= 1){
                for (i in (1:nrow(df))){
                  if(setequal(n,df[i,]) == TRUE){
                    p = p+1
                    }}
                if(p == 0){
                  df = rbind(df,n)
                }
              }
            }
          }
        }
      }
    }
  }
}

## Convert any 0 values to NA
df[df==0] = NA

## Check Solutions
df

I created an empty data.frame to store solutions, and then within the loop, I created a test to see if a new solution in the loop matches a combination of values previously found, and if so, it would not rbind() that to the data.frame.
I'm sure there is a better way to do this, one that allows a dynamic max number of values (so it could be soft coded in this case to change the max number of values in each solution to 9 instead of my hard-coded 6, or drop it to 5 if my desired total was 5 instead of 9). If you have any suggestions to make this less of a clunky, loop-filled mess, it would be appreciated!

A: You can maybe try this :
    library(modelr)
    library(dplyr)
    range = 1:6
    df = data.frame("a" = range,
              "b" =  range,
              "c" =  range,
              "d" =  range,
              "e" =  range,
              "f" =  range)
    data_grid(df,a,b,c,d,e,f) %>%
      mutate(sum = a+b+c+d+e+f) %>%
      filter(sum == 9) %>% nrow

This is the function :
foo <- function(sum_needed, max_value){
  range <- 1:max_value
  df = data.frame("a" = range,
                "b" =  range,
                "c" =  range,
                "d" =  range,
                "e" =  range,
                "f" =  range)
  result <- data_grid(df,a,b,c,d,e,f) %>%
    mutate(sum = a+b+c+d+e+f) %>%
    filter(sum == sum_needed) %>% nrow
  return(result)
}
foo(9,6)
#[1] 56

A: x = 1:6
mysum = 9

#Repeat each element of x as long the sum of repetitions does not exceed mysum
temp = rep(x, floor(mysum/x))

#Calculate total unique combinations of temp that sum up to mysum
sum(sapply(1:max(floor(mysum/x)),
           function(i) sum(rowSums(unique(t(combn(temp, i)))) == mysum)))
#[1] 26

Following should list all the combinations
sapply(1:max(floor(mysum/x)), function(i){
    temp2 = unique(t(combn(temp, i)))
    temp2[rowSums(temp2) == mysum,]
    })


text:
Q: What's the difference between Program Fixpoint and Function in Coq? They seem to serve similar purposes. The one difference I've noticed so far is that while Program Fixpoint will accept a compound measure like {measure (length l1 + length l2) }, Function seems to reject this and will only allow {measure length l1}.
Is Program Fixpoint strictly more powerful than Function, or are they better suited for different use cases?

A: This may not be a complete list, but it is what I have found so far:

*

*As you already mentioned, Program Fixpoint allows the measure to  look at more than one argument.

*Function creates a foo_equation lemma that can be used to rewrite calls to foo with its RHS. Very useful to avoid problems like Coq simpl for Program Fixpoint.

*In some (simple?) cases, Function can define a foo_ind lemma to perform induction along the structure of recursive calls of foo. Again, very useful to prove things about foo without effectively repeating the termination argument in the proof.

*Program Fixpoint can be tricked into supporting nested recursion, see https://stackoverflow.com/a/46859452/946226. This is also why Program Fixpoint can define the Ackermann function when Function cannot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Javascript stores objects as keys We know that

let obj1 = {};
obj1.x = "value";

let obj2 = {"key":"value"};
obj2[obj1] = "another value";
console.log(obj2[obj1]);

Above will print the "another value" properly on the console. Need to understand how. Does it store the address of obj1 for the key to match with the value?

A: Object property names can be strings or Symbols. Anything that is not a Symbol will be converted to a string.
A plain object's toString method will convert it to "[object Object]".
You can see that string if you log the entire object.

let obj1 = {};
obj1.x = "value";

let obj2 = {"key":"value"};
obj2[obj1] = "another value";
console.log(obj2);

console.log(obj1.toString());

This does, of course, mean that if you try to set ob2[obj3] at some point, with another object, then even if obj3 is a different object it will still be converted to the same string and overwrite the previous value.


text:
Q: Exponential of a function times derivative Exponential of a derivative $e^{a\partial}$ is simply a shift operator, i.e.
\begin{equation}
e^{a\partial}f(x)=f(a+x)
\end{equation}
This can be easily verified from a Taylor series
\begin{equation}
e^{a\partial}=\sum_{n=0}^\infty \frac{(a\partial)^n}{n!}
\end{equation}
and
\begin{equation}
f(x)=\sum_{n=0}^\infty c_n\frac{x^n}{n!}
\end{equation}
and applying one on another by using $\partial^mx^n=\frac{n!}{(n-m)!}x^{n-m}$ for $n\ge m$ and zero otherwise.
What if, instead of constant $a$, there is a function $g(x)$? In other words, I'm looking for $e^{g(x)\partial}f(x)$. Now, the derivative operator also acts on $g(x)$, which makes things very complicated and and seemingly intractable. For example, $[g(x)\partial]^2=g(x)[g'(x)+g(x)\partial]\partial$ and it gets worse for higher orders.
Also, where can I find the list of identities such as $e^{a\partial}f(x)=f(a+x)$? Searching for function (or exponential or logarithm) of a derivative gets clogged with results about derivative of a function (or exponential or logarithm).

A: The question is answered affirmative (and in a much simpler way) elsewhere:

How to derive these Lie Series formulas

Summary. First solve the differential equation:
$$
g(x) = \frac{1}{\phi'(x)} \quad \Longrightarrow \quad \phi(x) = \int \frac{dx}{g(x)}
$$
Then we have (barring division by zero and other issues):
$$
e^{g(x)\partial} f(x) = f(\phi^{-1}(\phi(x)+1))
$$
Update, triggered by another question (but where?)
By definition, for a function $\phi$ and its inverse:
$$
y = \phi(x) \quad \Longleftrightarrow \quad x = \phi^{-1}(y)
\quad \Longleftrightarrow \quad \phi^{-1}(\phi(x)) = x
$$
From this, an elementary result in calculus follows:
$$
\frac{dy}{dx} \frac{dx}{dy} = 1 = \frac{d\phi(x)}{dx} \frac{d\phi^{-1}(y)}{dy}
\quad \Longrightarrow \\ \frac{d\phi^{-1}(y)}{dy} = \frac{1}{\phi'(x)} = \frac{1}{\phi'(\phi^{-1}(y))}
\quad \Longrightarrow \\ \frac{d\phi^{-1}(x)}{dx} = \frac{1}{\phi'(\phi^{-1}(x))}
$$
There is an application with the Lie series. We have:
$$
u(t) = e^{t\,g(x)\frac{d}{dx}} x = \phi^{-1}(\phi(x)+t)
\quad \mbox{with} \quad g(x) = \frac{1}{\phi'(x)} \\
u(0) = e^{0\,g(x)\frac{d}{dx}} x = x = \phi^{-1}(\phi(x))
$$
It follows that:
$$
\frac{du}{dt} = \frac{d\phi^{-1}(\phi(x)+t)}{dt} =
\frac{1}{\phi'(\phi^{-1}(\phi(x)+t))} = \frac{1}{\phi'(u(t))}
$$
In short:
$$
u(t) = e^{t\,g(x)\frac{d}{dx}} x \quad \Longleftrightarrow \quad \dot{u}(t) = g(u(t)) \quad \mbox{with} \quad x = u(0)
$$

A: Instead of translation of a function $f(x) \to f(x+a)$ , let us consider scaling.
This means that we are going to make intervals of the independent variable smaller, or larger,
with a factor $\lambda > 0$. The transformed function is then defined by:
$$
  f_\lambda(x) = f(\lambda\,x)
$$
Like with translations, it would be nice to develop the function $f_\lambda(x)$
into a Taylor series expansion around the original $f(x)$. But this is not as
simple as in the former case. Unless some clever trick is devised, which reads as
follows. Define a couple of new variables, $a$ and $y$, and a new function $\phi$ :
$$
  \lambda = e^a \qquad ; \qquad x = e^y \qquad ; \qquad \phi(y) = f(e^y)
$$
Then, indeed, we can develop something into a Taylor series:
$$
  f_\lambda(x) = f(e^a\, e^y) = f(e^{a+y}) = \phi(y+a) = e^{a \frac{d}{dy}} \phi(y)
$$
A variable such as $y$, which renders the transformation to be like a translation, is called a canonical variable. In the case of
a scaling transformation, the canonical variable is obtained by taking the
logarithm of the independent variable: $y = \ln(x)$.
Working back to the original variables and the original function:
$$
   \phi(y) = f(e^y) = f(x) \qquad ; \qquad a = ln(\lambda)
$$ $$
   \frac{d}{dy} = \frac{dx}{dy}\frac{d}{dx} = e^y\frac{d}{dx} = x\frac{d}{dx}
$$
Where the operator $x\,d/dx$ is called the infinitesimal operator of
a scaling transformation. Such an infinitesimal operator always equals differentiation
to the canonical variable, which converts the transformation into a translation.
We have already met, of course, the infinitesimal operator for the translations
themselves, which is simply given by $(d/dx)$. This leads rather quickly
to the following:
$$
  f_\lambda(x) = f(\lambda\, x) = e^{\ln(\lambda)\, x\frac{d}{dx}} f(x)
$$
Which is somewhat bogus, because of some artificial restrictions imposed by our heuristics: $x=e^y$ had to be positive, for example. So let's specify this for the scaling transformation of $x$ itself,
which is represented by the series $\;e^{\ln(\lambda)\, x\, d/dx} x$ :
$$
  e^{ln(\lambda) \,x \frac{d}{dx}} x = x + \ln(\lambda)\, x\frac{dx}{dx}
  + \frac{1}{2} \ln^2(\lambda)\, x\frac{d(x\,dx/dx)}{dx} + \cdots
$$ $$
  = \left[1 + \ln(\lambda) + \frac{1}{2} \ln^2(\lambda) + \cdots \right] x
  = e^{\ln(\lambda)} x = \lambda\, x
$$
Similarly (Update):
$$
  e^{ln(\lambda) \,x \frac{d}{dx}} x^n = x^n + \ln(\lambda)\, x\frac{dx^n}{dx}
  + \frac{1}{2} \ln^2(\lambda)\, x\frac{d(x\,dx^n/dx)}{dx} + \cdots \\
 = x^n + \ln(\lambda)\,n\,x^n + \frac{1}{2} \ln^2(\lambda)\,n^2\,x^n + \frac{1}{6} \ln^3(\lambda)\,n^3\,x^n + \cdots \\
 = \left[1 + \ln(\lambda^n) + \frac{1}{2} \ln^2(\lambda^n) + \frac{1}{6} \ln^3(\lambda^n) + \cdots \right] x^n
 = e^{\ln(\lambda^n)} x^n = \lambda^n\, x^n
$$
Suppose that $f(x)$ can be written as a Taylor series expansion, then for all $x \in \mathbb{R}$ :
$$
e^{ln(\lambda) \,x \frac{d}{dx}} \left[ a_0 + a_1 x + a_2 \frac{1}{2} x^2 + \cdots \right] = a_0 + a_1 (\lambda\,x) + a_2 \frac{1}{2} (\lambda\,x)^2 + \cdots
\\ \Longrightarrow \qquad e^{ln(\lambda) \,x \frac{d}{dx}} f(x) = f(\lambda\,x)
$$
(End of update) Since $\lambda$ must be positive, there exists no continuous transition towards
problems where values are, at the same time, inverted or mirrored, like
in: $$
   f_\lambda(x) = f(-\lambda\,x)
$$
For this to happen, the scaling transformation would to have to pass through a
point where things are contracted to zero:
$$
   f_\lambda(x) = f(0\,x)
$$
This already reveals a glimpse of the topological issues which may be
associated with Lie Groups : remember that keyword. To be honest, I haven't seen any other generalization of your problem in 1-D, except the above scaling example.

Update. Well, not really. After some digging in my old notes, I've found a little bit more.Consider the operation $\;e^\alpha\,x\;$ with $\;\alpha = g(x)\frac{d}{dx}$ .
Then by definition:
$$
e^{\alpha \,x} = 1 + \alpha\, x + \frac{1}{2} \alpha \left( \alpha\, x \right)
+ \frac{1}{3} \alpha \left( \frac{1}{2} \alpha \left( \alpha\, x \right)\right) + \cdots \\
$$
This can be written recursively as:
$$
e^\alpha \, x = x + \alpha_1 x + \alpha_2 x + \alpha_3 x + \cdots \qquad ; \qquad\alpha_1 = \alpha \qquad ; \qquad \alpha_n = \frac{1}{n} \alpha \, \alpha_{n-1}
$$
We have seen cases where $\;g(x) = a\;$ and $\;g(x) = \ln(\lambda)\,x$ .
Now let's try another example, with $\;g(x) = x^2$ :
$$
\alpha_1 x = x^2 \frac{d}{dx} x = x^2 \\
\alpha_2 x = \frac{1}{2} x^2 \frac{d}{dx} x^2 = x^3 \\
\alpha_3 x = \frac{1}{3} x^2 \frac{d}{dx} x^3 = x^4 \\
\cdots \\
\alpha_n = \frac{1}{n} x^2 \frac{d}{dx} x^n = x^{n+1} \\
$$
Consequently, say for real $0 < x < 1$ :
$$
e^{x^2\,d/dx} x = x + x^2 + x^3 + \cdots + x^n + \cdots = \frac{x}{1-x}
$$
Which can perhaps be generalized to functions $f(x)$ that have a Taylor expansion.
One might think now that the above results may be combined as follows:
$$
e^{(ax^2+bx+c)d/dx}x = e^{c\,d/dx}e^{bx\,d/dx}e^{ax^2\,d/dx}x = e^{ax^2\,d/dx}e^{bx\,d/dx}e^{c\,d/dx}x
$$
But it can readily be verified that such is not the case. The reason is that the operators $\;x^2\,d/dx$ ,
$x\,d/dx$ , $d/dx\;$ do not commute. Define the commutator $\left[\,,\right]$ of two operators $\alpha$ and $\beta$ as: $$\left[\alpha\,,\beta\right] = \alpha\beta - \beta\alpha$$ Then prove that:
$$
 \left[ x^2\frac{d}{dx}, x\frac{d}{dx} \right] \ne 0 \qquad ; \qquad \left[ x^2\frac{d}{dx}, \frac{d}{dx} \right] \ne 0 \qquad ; \qquad \left[ x \frac{d}{dx} , \frac{d}{dx} \right] \ne 0
$$
Late revision. I've ordered the following book and reading it now:
Sophus Lie, Vorlesungen über Differentialgleichungen
mit bekannten Infinitesimalen Transformationen, bearbeitet und
herausgegeben von Dr. Georg Wilhelm Scheffers,Leipzig (1891). Availability:
Amazon ,
bol.com .

Formulated in somewhat outdated notation I find the following IMHO
astonishing Theorem on page 50 and next. Operator notation is mine:
$$
  \boxed{ \; e^{t \phi(x) \frac{d}{dx}} f(x) = f\left(e^{t \phi(x) \frac{d}{dx}} x\right) \; }
$$
Here $\phi(x)$ and $f(x)$ are "neat" but for the rest quite arbitrary functions.
Therefore the differential operator and the function are
always commutative, which is quite a non-trivial fact. When applied to the
last of the above examples (slightly modified) we have via page 75 of the book:
$$
  e^{t x^2 \frac{d}{dx}} f(x) = f\left(\frac{x}{1-x t}\right)
$$
So it is indeed sufficient to apply the operator $\exp(t \phi(x) d/dx)$ to the
independent variable $x$ only. If that results in a closed form, then you can
apply the Theorem and have a closed form for any other function $f(x)$ as well.

Sad remark. The book by Georg Scheffers is abundant with "non rigorous"
notions, especially infinitesimals. The latter are quite essential for
understanding the book. For me, as a physicist by education, this represents
no problem at all. But I know from bad experience that those good old infinitesimals represent sort of a taboo for modern mathematics. Therefore, in retrospect, it can be understood very well why this approach by
Georg Scheffers hasn't found wide audience among professional mathematicians.
Even worse. I find that professional mathematicians rather have distorted the
original theory as meant by Sophus Lie a great deal. Such that essential parts of it,
like the above Theorem, tend to be erased from common mathematical knowledge. Which I hope not.


text:
Q: Kotlin: How to send data from RecyclerView adapter to a Fragment I'm new to Android and new to Kotlin (coming from iOS Swift development). I have an activity that has a fragment, inside the fragment is a RecyclerView. When the user taps on a row in the RecyclerView I want to show a dialog and take some action.
In the adapter I have the CustomViewHolder and onClickListener. From there I can capture the row the user tapped on easily. But how do I pass this information back to the fragment so that I can take action / display a dialog?
thanks!

A: Have your adapter take a lambda as a parameter...for example
class YourAdapter(val listener: (YourDataType) -> Unit)

In your view holder you'd then invoke that listener when user clicks on row.
holder.itemView.setOnClickListener { listener(data) }

In your fragment you'd have something like:
    yourAdapter = YourAdapter {
        // invoked when user clicks on row
    }


text:
Q: CanvasJs: straight line rather than regular graph Using CanvaJs, I just get a straight line rather than a regular graph. What is wrong in the code please?
This is what the .csv file look like:
course_id,userid_DI,registered,viewed,explored,certified,final_cc_cname_DI,LoE_DI,YoB,gender,grade,start_time_DI,last_event_DI,nevents,ndays_act,nplay_video,nchapters,nforum_posts,roles,incomplete_flag
LavalX/CB22x/2013_Spring,MHxPC130442623,1,0,0,0,United States,NA,NA,NA,0,2012-12-19,2013-11-17,,9,,,0,,1
LavalX/CS50x/2012,MHxPC130442623,1,1,0,0,United States,NA,NA,NA,0,2012-10-15,,,9,,1.0,0,,1
LavalX/CB22x/2013_Spring,MHxPC130275857,1,0,0,0,Canada,NA,NA,NA,0,2013-02-08,2013-11-17,,16,,,0,,1
LavalX/CS50x/2012,MHxPC130275857,1,0,0,0,United States,NA,NA,NA,0,2012-09-17,,,16,,,0,,1
LavalX/ER22x/2013_Spring,MHxPC130275857,1,0,0,0,France,NA,NA,NA,0,2012-12-19,,,16,,,0,,1

I'm trying to display on X axis data of column 11 (start_time_DI) and on Y axis data of column 3 (registered)
I am trying to draw the number of registration per date.
That is the code:
<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Figure

Thank you.

A: I have created a jsfiddle with your data/code and it seems to be working fine. As you can see all values in column 3 are equal to one. In case the expected chart is not straight line, make sure that you are providing the right
data.dataPoints.push({
                label: rowData[11],
                y: parseInt(rowData[2])
            });


text:
Q: Are multithreaded apps bound to a single core? I'm running a .NET remoting application built using .NET 2.0. It is a console app, although I removed the [STAThread] on Main.
The TCP channel I'm using uses a ThreadPool in the background.
I've been reported that when running on a dual core box, under heay load, the application never uses more than 50% of the CPU (although I've seen it at 70% or more on a quad core).
Is there any restriction in terms of multi-core for remoting apps or ThreadPools?
Is it needed to change something in order to make a multithreaded app run on several cores?
Thanks

A: Multithreaded applications will use all of your cores.
I suspect your behavior is due to this statement:

The TCP channel I'm using uses a ThreadPool in the background.

TCP, as well as most socket/file/etc code, tends to use very little CPU.  It's spending most of its time waiting, so the CPU usage of your program will probably never spike.  Try using the threadpool with heavy computations, and you'll see your processor spike to near 100% CPU usage.

A: Multi-threaded apps are not required to be bound to a single core. You can check the affinity (how many cores it operates on) of a thread by using ProcessThread.ProcessorAffinity. I'm not sure what the default behavior is, but you can change it programmatically if you need to.
Here is an example of how to do this (taken directly from TechRepublic)
Console.WriteLine("Current ProcessorAffinity: {0}",
                  Process.GetCurrentProcess().ProcessorAffinity);

Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)2;

Console.WriteLine("Current ProcessorAffinity: {0}",
                  Process.GetCurrentProcess().ProcessorAffinity);

And the output:

Current ProcessorAffinity: 3
Current ProcessorAffinity: 2

The code above, first shows that the process is running on both cores. Then it changes to only use the second core and shows that it is now using only the second core. You can read the .NET documentation on ProcessorAffinity to see what the various numbers mean for affinity.

A: There shouldn't be.
There are several reasons why you could be seeing this behavior:

*

*Your threads are IO bound.
In that case you won't see a lot of parallelism, because everything will be waiting on the disk. A single disk is inherently sequential.

*Your lock granularity is too small
Your app may be spending most of it's time obtaining locks, rather than executing your app logic. This can slow things down considerably.

*Your lock granularity is too big
If your locking is not granular enough, your other threads may spend a lot of time waiting.

*You have a lot of lock contention
Your threads might all be trying to lock the same resources at the same time, making them inherently sequential.

*You may not be partitioning your threads correctly.
You may be running the wrong things on multiple threads. For example, if you are using one thread per connection, you may not be taking advantage of available parallelism within the task you are running on that thread. Try splitting those tasks up into chunks that can run in parallel.

*Your process may not have a lot of available parallelism
You might just be doing stuff that can't really be done in parallel.
I would try and investigate each one to see what the cause is.


text:
Q: Entity-Framework Core Multi-Level dynamic query I'm trying to do a multi-level category with self join, but when i tried to get the data dynamically i couldnt so i wrote this query which is not dynamic any ideas how to make it dynamic
`
var data = Context.MultiLevelCategories
                .Where(mlc => mlc.ParentCategoryId == null)
                .Select(mlc=>new MultiLevelCategoryDetailsDto()
                {
                    Id = mlc.Id,
                    Name = mlc.Name,
                    ParentId = mlc.ParentCategoryId,
                    Children = mlc.Children.Select(mlc1 => new
                                       MultiLevelCategoryDetailsDto()
                    {
                        Id = mlc1.Id,
                        Name = mlc1.Name,
                        ParentId = mlc1.ParentCategoryId,
                        Children = mlc1.Children.Select(mlc2 => new
                                       MultiLevelCategoryDetailsDto()
                        {
                            Id = mlc2.Id,
                            Name = mlc2.Name,
                            ParentId = mlc2.ParentCategoryId,
                            Children = mlc2.Children.Select(mlc3 => new
                                       MultiLevelCategoryDetailsDto()
                            {
                                Id = mlc3.Id,
                                Name = mlc3.Name,
                                ParentId = mlc3.ParentCategoryId,
                                Children = mlc3.Children.Select(mlc4 => new
                                        MultiLevelCategoryDetailsDto()
                                {
                                    Id = mlc4.Id,
                                    Name = mlc4.Name,
                                    ParentId = mlc4.ParentCategoryId
                                })`enter code here`
                            })
                        })
                    })
                })

`

A: Maybe the navigation property can help you, but be careful with the cycle reference.
Read efcore documents:

*

*Related data and serialization

*Relationships


text: Q: Catching HTML errors in HTMLLoader / mx:HTML I'm building an application to convert old HTML code to modern, responsive HTML. The app has one text area where the user can enter HTML code which is then displayed in an mx:HTML component (using the htmlText property). Unfortunately the code to convert has a bunch of errors, such as missing/not closed tags. During debugging I see console messages warning about it, e.g. about:blank:29 HTML ERROR: <p> is not allowed inside <tr>. Inserting <p> before the <table> instead. I would like to show these messages in my application but I can't figure out where the traces are created... can anyone help?


text:
Q: Why can I "captureless-capture" an int variable, but not a non-capturing lambda? The following function is valid (as of C++20):
void foo() {
    constexpr const int b { 123 };
    constexpr const auto l1 = [](int a) { return b * a; };
    (void) l1;
}

even though l1 does not capture anything, supposedly, it is still allowed to "captureless-capture" the value of b, as it is a const (it doesn't even have to be constexpr; but see @StoryTeller's comment).
But if I try to capture something more complex in a new lambda:
void foo() {
    constexpr const int b { 123 };
    constexpr const auto l1 = [](int a) { return b * a; };
    (void) [](int c) { return l1(c) * c; };
}

This fails to compile. Why? The compiler should have no trouble calling l1 from within the lambda; so why is b ok for captureless-capture, and l1 isn't?
See this on GodBolt.

A: This has to do with odr-use.
First, from [basic.def.odr]/10:

A local entity is odr-usable in a scope if:

*

*either the local entity is not *this, or an enclosing class or non-lambda function parameter scope exists and, if the innermost such scope is a function parameter scope, it corresponds to a non-static member function, and

*for each intervening scope ([basic.scope.scope]) between the point at which the entity is introduced and the scope (where *this is considered to be introduced within the innermost enclosing class or non-lambda function definition scope), either:

*

*the intervening scope is a block scope, or

*the intervening scope is the function parameter scope of a lambda-expression that has a simple-capture naming the entity or has a capture-default, and the block scope of the lambda-expression is also an intervening scope.

If a local entity is odr-used in a scope in which it is not odr-usable, the program is ill-formed.

So in this example, a is odr-usable but b is not:
void foo() {
    constexpr const int b { 123 };
    constexpr const auto l1 = [](int a) { return b * a; };
    (void) l1;
}

And in this example, similarly, the a and c are odr-usable, but neither b or nor l1 are.
void foo() {
    constexpr const int b { 123 };
    constexpr const auto l1 = [](int a) { return b * a; };
    (void) [](int c) { return l1(c) * c; };
}

But the rule isn't just "not odr-usable", it's also "odr-used". Which one(s) of these are odr-used? That's [basic.def.odr]/5:

A variable is named by an expression if the expression is an id-expression that denotes it. A variable x whose name appears as a potentially-evaluated expression E is odr-used by E unless

*

*x is a reference that is usable in constant expressions ([expr.const]), or

*x is a variable of non-reference type that is usable in constant expressions and has no mutable subobjects, and E is an element of the set of potential results of an expression of non-volatile-qualified non-class type to which the lvalue-to-rvalue conversion ([conv.lval]) is applied, or

*x is a variable of non-reference type, and E is an element of the set of potential results of a discarded-value expression ([expr.context]) to which the lvalue-to-rvalue conversion is not applied.

For the b * a case, b is "a variable of non-reference type that is usable in constant expressions" and what we're doing with it is applying "the lvalue-to-rvalue conversion". That's the second bullet exception to the rule, so b is not odr-used, so we don't have the odr-used but not odr-usable problem.
For the l1(c) case, l1 is also "a variable of non-reference type that is usable in constant expressions"... but we're not doing an lvalue-to-rvalue conversion on it. We're invoking the call operator. So we don't hit the exception, so we are odr-using l1... but it's not odr-usable, which makes this ill-formed.
The solution here is to either capture l1 (making it odr-usable) or make it static or global (making the rule irrelevant since l1 wouldn't be a local entity anymore).


text:
Q: grunt.util.spawn doesn't give output Grunt.util.spawn is not calling the done function. Here is the code. when the command gets executed from command prompt it is failing and throws an error message which is not captured in gruntjs..what is happening
module.exports = (grunt)->
grunt.initConfig
    concurrent:
        dev: ['watch']
    slim:
        dev:
            expand: true
            src:  'views'
            dest: 'views/'
    watch:
        slim:
            files: 'views/**.slim'
            tasks:['slim']

grunt.registerMultiTask 'slim', 'Server Slim Compiler', ->
    console.log 'In the slim'
    options = {}
    options.cmd = 'dirld'
    options.grunt = true
    console.log options
    grunt.util.spawn options, (err,res,cod)->
        console.log 'in the spawn'
        if err
            grunt.log.error err
        else
            grunt.log.oklns 'success'
            grunt.log.writeln res

grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-concurrent'
grunt.registerTask 'default', ['concurrent:dev']

A: grunt.util.spawn is asynchronous so you need to make your slim task async. See: http://gruntjs.com/frequently-asked-questions#why-doesn-t-my-asynchronous-task-complete
grunt.registerMultiTask 'slim', 'Server Slim Compiler', ->
  done = @async()
  grunt.util.spawn options, (err,res,cod) ->
    done() # Im done, continue onto the next task


text:
Q: How can I add multiple IAM users to Systems Manager with diffent SSM? AWS I want to log into a IAM user through AWS and my EC2 through systems manager. Then I want to log into different IAM user and access same EC2 except with a different SSM so home dir isn't the same and they don't have access to each others files. How can I do this?
I am able to log into systems manager from different IAM accounts but it still uses the same SSM.

A: what do you mean "different SSM"??? there is only one AWS Systems manager. Based on your tag, I think you mean System Manager Session Manager...
In Session Manager you are interacting with ssm-user account that is created for you by AWS. So, it really doesn't matter which IAM account you are using - on the box itself it's the same account


text:
Q: Sending a GET/POST request in axios to receive a blob in React/Express Application I have a youtubeVideos Downloader app and I have to send a get request(with URl) to download the video in react/express application.I am confused as to what to use Should I use GET or POST , If I Use GET have to use query paramaters which I dont like to use as I have to do extra work to make the url input by users that I have to escape the "?" and I thought of Using Post with req.body.url so then I can use it in my route handler . I need help which way to go ?
My index.js file in express :
app.post('/api/getmevideo', async (req, res) => {

    try {
        const videoURL = req.body.url;
        const videoName = await downloadVideoAsync(videoURL);
        const videoPath = path.join(__dirname + `/videos/${videoName}.mp4`);
        res.sendFile(videoPath, function() {
            fs.unlinkSync(videoPath);
        });
    }
    catch(ex) {
        res.send({
            message : "something went wrong"
        })
    }

  });

My Axios code in App.js in React :
downloadHandler() {
         if(this.state.inputText !== '') {
                axios({
                        url: '/api/getmevideo',
                        method: 'POST',
                        responseType: 'blob', // important
                    }, { url : this.state.inputText }).then((response) => {
                            const url = window.URL.createObjectURL(new Blob([response.data]));
                            const link = document.createElement('a');
                            link.href = url;
                             link.setAttribute('download', 'video.mp4');
                            document.body.appendChild(link);
                            link.click();
                        });
                    }
    }

Thanks!


text:
Q: Chef integration with CI for DEV and PROD deployments We have two environments, DEV and PROD. Each environment has 3 nodes:

*

*DEV

*

*devapp01 (Tomcat)

*devapp02 (Tomcat; identical to 01 and load-balanced)

*devdb01 (MySQL)

*PROD

*

*app01 (Tomcat)

*app02 (Tomcat; identical to 01 and load-balanced)

*db01 (MySQL)

The Tomcat instances serve WARs that are produced by a CI build.
We need the software stack on all DEV machines to be configured identically to those on PROD. We have set up a simple Chef server to manage configs on all nodes, and have created recipes for app and DB servers.
On the Chef server, we currently have an auto-update feature that runs every 30 minutes to check all nodes and make sure they're in synch with their respective recipes. The way our in-house "chef" (a sys admin) set everything up, there's a part of a recipe that does an existential check on Tomcat's webapps directory to determine whether an update should be performed or not. In other words, if Tomcat's webapp's directory has a WAR inside of it already, then when the auto-update runs every 30 mins, since webapps isn't empty, Chef won't go out to the CI server and pull in the new WAR.
To combat this, our chef cooked up a "clean slate" recipe that will first delete exploded WARs from Tomcat's webapps dir. So as long as that recipe executes first, TOMCAT_HOME/webapps will be executed before the Tomcat check; it then removes itself from the Chef runlist. His reasoning for this removal was that - in production - if we are
always deleting Tomcat's webapps dir then we will be redeploying prod nodes every 30 minutes.
So on DEV, we do want every CI build to produce a new WAR being deployed to our Tomcat instances (devapp01/02). In PROD, we want to manually kick off the deployment, which according to how this chef has configured everything, involves manually adding the clean slate recipe so that the CI server can deploy the new WAR.
I'm wondering how other people/teams have used CI and Chef in conjunction in the past, and if they ran into similar issues. My concrete question is: how can we accomplish letting CI drive all the DEV deployments, but still make PROD deployments a manual process?

A: You should take a look at CloudMunch for this as this is one of the scenarios that has been envisaged already there.
CloudMunch integrates natively into chef server and provides a manual workflow to allow deployment into staging or production environments.
Disclaimer: I work at CloudMunch.

A: The easiest way is to have separate Chef organizations (or even servers) for dev and prod. This gives you strong separation by default. You CI pushes to dev, prod pushes are done purposefully.
Chef Inc is also working on Policyfiles, which are an interesting replacement for Environments that shouldn't suffer from the same metadata/cookbook version leakage problems.


text:
Q: How to apply a hover effect to a single component present in react-table's row. Though there are multiple columns {
                id: "checkbox",
                accessor: "",
                Cell: ({ original }) => {
                  return (
                    <Checkbox
                      className="checkbox"
                      color={"#4caf50"}
                      onChange={() => this.toggleRow(original.id)}
                      checked={this.state.selected[original.id] === true}
                    />
                  );
                },
                Header: x => {
                  return (
                    <Checkbox
                      className="checkbox"
                      color={"#4caf50"}
                      onChange={() => this.toggleSelectAll()}
                      checked={this.state.selectAll === 1}
                    />
                  );
                },
                sortable: false,
                width: 45
              },

Here is the checkbox column code in react-table but I want to show the checkbox for the specific row on which mouse is hovered, otherwise it the other rows should contain images instead of checkbox.

A: I think it's practical to use jQuery.
First of all, npm i jquery
In React imports, add import $ from 'jquery' and inside componentDidMount() function add the code, similar to this:
When a mouse is hovered over a column element, add a checkbox class to it. When done, remove class.
Classes are added through $("#id").addClass("class-name") and removed with $("#id").removeClass("class-name")


text:
Q: Render .ics file attachment within Outlook (like Gmail) I'm sending an email when a user books an event - the email contains a .ics file attachment containing the event information.
When sent to a Gmail account, it renders the event detail within the email body (like the image below), automatically adding the event to their calendar:

...but I'm struggling to get the same behaviour when sending the email (with attachment) to an Outlook email account.
Longshot - but has anyone dealt with this, or would be able to point me in a  direction?
Can provide the .ics file if required.

A: This usually corresponds to a MIME structure issue, especially if you got it working with some clients. See Multipart email with text and calendar: Outlook doesn't recognize ics


text:
Q: Why does od linenumber increment by 2? Example:
od /bin/bash | head -n4

Gives the output
0000000 042577 043114 000402 000001 000000 000000 000000 000000
0000020 000002 000076 000001 000000 002540 000102 000000 000000
0000040 000100 000000 000000 000000 146600 000017 000000 000000
0000060 000000 000000 000100 000070 000011 000100 000034 000033
My question is, Why doesn't each line number (shown above in bold) increment by 1?
It goes from 0 to 2 to 4 and so forth.
Shouldn't it be 0, 1, 2 ... 7?

A: The leftmost column is not a line number but rather the byte offset presented in octal form.  Each line of default od output has 16 bytes in it.  So, the offset goes 0, 16 (octal 20), 32 (octal 40), etc.


text:
Q: How to launch system apps programmatically or how to filter out launchable system apps? I want to make  a list of installed and system applications. system applications means the pre-installed applications (applications which are installed at the time of manufacture).
For this i categorized all the apps using (ApplicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 - which are system apps and others are installed apps.
Now my problem is i want to launch these  apps on click of list items.But i could not launch system apps like Contacts,Dialer etc...
How to launch system apps programmatically or how to filter out launchable system apps?

A: I could not found exact answer.But i think it will helpful
List<PackageInfo> list = packageManager.getInstalledPackages(0);
for (PackageInfo pi : list) {
 try {
    ApplicationInfo appInfo = getPackageManager() .getApplicationInfo(pi.packageName, 0);
        //check whether the app is launchable or not
    if (packageManager .getLaunchIntentForPackage(appInfo.packageName) != null) {
     //check whether the app is an installed / system app
     if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
        //system apps.........
     } else {
        //installed apps............
     }
    }

   } catch (Exception e) {}
}


text:
Q: How to keep the wedding betrothal to Elaena Glenmore in episode 2 of Game of Throne? At the end of episode 2 "The Lost Lords", my choices show that I lost the betrothal to Elaena Glenmore. I did not forge the letter at the beginning, so I wonder: Was the letter forging a requirement? Or could I have saved the betrothal by certain choices alone during the conversation?

A: There are two ways to keep the betrothal:

*

*If, as Mira, you forged the letter from Margery, Elaena will tell you about the letter. When she says she feels she's being forced to marry you, tell her it's her choice. She'll say yes.

*If Mira didn't forge the letter, tell Elaena that you can pay her father in ironwood. She'll accept, in exchange for half the ironwood.

A: It's said in a thread that the option to offer offer ironwood keeps the betrothal even without forging the letter.


text:
Q: Curl A with no phi-dependence So I know from wikipedia curl A is given by this: enter image description here
Then, how would this change if there were no phi-dependence, that is if A was only composed of p and z?
Thanks in adavnace.


text:
Q: SQL Group two columns and select recent date/timestamp So I have a table called phone_messages. This is an example query that I have written. What I am trying to do is group together rows that have character_id 22 or target_character_id 22. Because in each phone_message stored in the database these is two entries. Basically phone conversations. What I am trying to do is group get the last message send in each of the groups.
My Original Query:
SET @character_id = 22;
SET @t = 'text';

SELECT character_id, target_character_id, message, `type`, MAX(`date`) date FROM
    `phone_messages`
WHERE
    (
        `character_id`=@character_id
    ) AND `type`=@t
GROUP BY
    character_id, target_character_id

character_id | target_character_id | message | type | date
"22"    "33"    "correct"   "text"  "2020-08-25 23:28:31"
"33"    "22"    "perfect see you then"  "text"  "2020-08-25 23:28:43"
"57"    "22"    "where is this mega mall" "text" "2020-09-05 19:05:25"
"22"    "57"    "the tool shop down south"  "text"  "2020-09-05 19:05:45"

My desired output for this would be
character_id | target_character_id | message | type | date
"33"    "22"    "perfect see you then"  "text"  "2020-08-25 23:28:43"
"22"    "57"    "the tool shop down south"  "text"  "2020-09-05 19:05:45"

How would I go about doing this? Sorry for any lack of understanding in my question.

A: Just to confirm

*

*For each 'pair' of callers (one of who is "22")

*You would like to get the latest text which went either way (either to or from 22)

The answer here uses the following approach

*

*For each row, determine the other party (this is called second_character_id in the query)

*For each other party, order the 'text' rows based on the date sent

*Get the latest row for each party

WITH Call_list AS
    (SELECT *,
        @character_id AS `primary_character_id`,
        CASE
            WHEN `character_id` = @character_id THEN `target_character_id`
            ELSE `character_id` END AS `second_character_id`
    FROM
        `phone_messages`
    WHERE
        (`character_id`= @character_id OR `target_character_id`= @character_id)
        AND (`type`= @t )
    ),
Sorted_Call_List AS
    (SELECT *,
            ROW_NUMBER() OVER
                (PARTITION BY `primary_character_id`, `second_character_id`
                ORDER BY `Date` DESC
                ) AS char_rn
    FROM Call_list
    )
SELECT `character_id`, `target_character_id`, `message`, `type`, `date`
FROM   Sorted_Call_List
WHERE  char_rn = 1;

With this answer I also included the primary_character_id - which in this case is always 22 - in case you wanted to expand it to have multiple people.
Here is a db<>fiddle with the data setup and approach.
Note that there is an additional query at the bottom there - that was my previous attempt where I misunderstood the requirements. In that answer, it finds the latest 'incoming' and latest 'outgoing' text to/from 22, regardless of who they came from.

A: If you want the most recent message for each pair, regardless of ordering, then you can use ROW_NUMBER() with LEAST() and GREATEST():
SET @character_id = 22;
SET @t = 'text';

SELECT pm.*
FROM (SELECT pm.*,
           ROW_NUMBER() OVER (PARTITION BY LEAST(character_id, target_character_id), GREATEST(character_id, target_character_id)
                              ORDER BY date DESC
                             ) as seqnum
      FROM phone_messages pm
      WHERE character_id = @character_id AND
            type = @t
     ) pm
WHERE seqnum = 1;


text:
Q: How to: `GeneralizedLinearModelFit` with `Dataset` with cofactors Please do not think of this question as a more general extension of LinearModelFit with Dataset asked by @alan, and answered by @Weach.
The original question (or at least the solution) pertained more to how to overload LinearModelFit to work on Dataset.
While overloading GeneralLinaerModelFit for Dataset would be nice; here, however, the question is more in relation to "data wrangling" / how to input my data to get the desired results.
Suppose you have a Dataset as follows:
numberOfRecords = 100;  (* records in the dataset *)

numberOfGroups = 2;    (* groups:    g1,...,gn *)
numberOfSegments = 4;  (* segments:  s1,...,sn *)
numberOfCofactors = 3; (* cofactors: c1,...,cn *)
numberOfFeatures = 5;  (* features  x1,...,xn *)

(* in this case binary *)
responseVector = RandomInteger[{0, 1}, {numberOfRecords, 1}];
groupVector = RandomInteger[{1, numberOfGroups}, {numberOfRecords, 1}];
segmentVector =
  RandomInteger[{1, numberOfSegments}, {numberOfRecords, 1}];

featureMatrix =
  RandomReal[{-10, 10}, {numberOfRecords, numberOfFeatures}];
cofactorMatrix =
  RandomReal[{-10, 10}, {numberOfRecords, numberOfCofactors}];

(* join data together *)
data = Table[
   Join[
    responseVector[[r]],
    groupVector[[r]],
    segmentVector[[r]],
    featureMatrix[[r]],
    cofactorMatrix[[r]]
    ], {r, numberOfRecords}
   ];

(* construct header *)
header = Join[
  {"y", "g", "s"},
  Table["x" <> ToString[i], {i, 1, numberOfFeatures}],
  Table["c" <> ToString[i], {i, 1, numberOfCofactors}]
  ]

(* map header to each record *)
assoc = AssociationThread[header, #] & /@ data;
(* make dataset *)
ds = Dataset@assoc;

The goal is to do the following:
per group, taking into account the cofactors, predict the response at each segment.
So the result should look something like this (given the demo data)

From the Details and Options tab of the documents, I can not really see how I should format my data to get the results I am looking for.
Any help and explanation would be greatly appreciated.


text:
Q: Funny Characters Before and at End of Logs with Google Cloud Winston Logging (Nodejs) I am using the google-cloud/logging-winston nodejs package for logging, and I created my custom formatter for output this way:
const winston = require('winston');
const { LoggingWinston } = require('@google-cloud/logging-winston');
const { format } = winston;
const { combine, label, json, timestamp, printf, colorize, simple } = format;
const path = require('path');

const customFormats = (category) => combine(
    label({label: category}),
    colorize({all: true}),
    // simple()
    timestamp(),
    json(),
    printf((info) => `${info.timestamp} - [${info.label?`${info.label}`:"NO_LABEL"}] - [${info.level}] : ${info.message}`));

It logs as expected, but there are funny characters before and after the log messages when viewed on Google cloud console. Below are some examples of the log:
2021-01-16T10:58:00.836Z - [DEFAULT] - [[32minfo[39m] : [32mValidating route @/bills/airtime/send[39m
2021-01-16T10:58:00.841Z - [AIRTIME] - [[31merror[39m] : [31mAirtime recharge error Low account balance[39m

I don't know what these mean: "[32m", "[31m" or "[39m" but they make it hard to read my logs.

A: Those characters are called ANSI Escape Codes or Escape Sequences. They are used to modify how terminals display text. For example to change the color or make text bold. This might make messages look better on a terminal but make processing logfiles more difficult.
Those characters are not added by Google Cloud logging but by either the application or the logger software on your system.
ANSI escape code
If you examine the example code in your question, notice label and colorize. Those functions are generating the escape codes.
const customFormats = (category) => combine(
    label({label: category}),
    colorize({all: true}),


text:
Q: Value of a contour Integral If we have the contour integral $\frac{1}{2\pi i} \oint_y \frac{f(C)}{(C-z)^2}dC$, where $f: \mathbb{C} \to \mathbb{C}$ is holomorphic and $y$ a closed circle with centre at $z\in \mathbb{C}$, which is traced anticlockwise. Am I correct in saying that the value of this contour integral is $f'(z)$?

A: Yes, it is a particular case of Cauchy integral formula. More generally, we have:
$$ f^{(n)}(z)= \frac{n!}{2 \pi i} \int_{\gamma} \frac{f(\zeta)}{(\zeta - z)^{n+1}} d \zeta  $$
where $f: U \rightarrow \mathbb{C}$ is holomorphic. $\gamma$ is some contour enclosing $z$, not necessarily a circle. This result can be generalised in various ways: just to cite a few, one is the so-called Cauchy-Pompeiu formula, while another one is the extension to several variables.


text:
Q: Switch interface implementation without overhead Given an interface and two (or more) implementations I struggle to easily switch the implementation when extending the functionality.
For example assume that there is interface INumber which supports Inc and String and two implementations NumberInt32 and NumberInt64 with their obvious implementation. Assume that I want to implement an EvenCounter on top of INumber. The EvenCounter only has a IncTwice and shall call Inc twice. I struggle to get the types right without using an extra struct surrounding the INumber in EvenCounter.
type INumber interface {
    Inc()
    String() string
}

type NumberInt32 struct {
    number int32
}

func NewNumberInt32() INumber {
    ret := new(NumberInt32)
    ret.number = 0
    return ret
}

func (this *NumberInt32) Inc() {
    this.number += 1
}

func (this *NumberInt32) String() string {
    return fmt.Sprintf("%d", this.number)
}

// type NumberInt64.... // obvious

Here is where I struggle
type EvenCounter1 INumber // nope, additional methods not possible
type EvenCounter2 NumberInt32 // nope
func (this *EvenCounter2) IncTwice() {
for i:=0; i < 2; i+=1 {
    // this.Inc() // Inc not found
    // INumber(*this).Inc() // cannot convert
    // in, ok := *this.(INumber) // cannot convert
    // v, ok := this.(INumber) // cannot convert
    // a concrete conversion a) does not work and b) won't help
    // here it should be generic
    // v, ok := this.(NumberInt32)
    // How do I call Inc here on this?
    }
}

Just embedding in a struct works...
type EvenCounter3 struct {
    n INumber
}

func (this *EvenCounter3) IncTwice() {
    n := this.n // that is a step I want to avoid
    n.Inc() // using this.n.Inc() twice makes it slower
    n.Inc()
}

func (this *EvenCounter3) String() string {
    return this.n.String()
}

I could live with the need to implement delegation manually for each method, but
obviously I would want to rely on INumber and not the specific implementation (that
would mean changing lots of places to try another implementation, However, I would want to avoid the extra indirection and (most likely?) extra space. Is there a
way to avoid the struct and directly say EvenCounter is a (specific) INumber with additional methods?
BTW the real example is a set of integers and a map of integers to integers with millions of instances all intertwined (and no, just map[int]bool won't suffice - too slow, bitset is interesting depening on use case, etc.) and testing different implementations of the set and map easily by changing 2-3 lines in the code (ideally just the type and maybe
the generic creation of instances resp. making copies)
Any help appreciated and I hope this hasn't been asked yet...

A: Your variant using embedding does not actually embed. Embedded fields are anonymous and Go then delegates automatically.
This simplifies your example to:
type EvenCounter3 struct {
    INumber
}

func (this *EvenCounter3) IncTwice() {
    this.Inc() // using this.n.Inc() twice makes it slower
    this.Inc()
}

Note that String() is automatically delegated ("promoted" in Go speak).
As to calling Inc() twice making it slower, well, that's a limitation of using interfaces. The point of an interface is to not expose the implementation, so you cannot access its internal number variable.

A: I'm not sure I understood correctly what you're trying to achieve. Perhaps something like this?
package main

import "fmt"

type Num interface {
        Inc()
        String() string
}

type Int32 struct {
        int32
}

func (n *Int32) Inc() {
        (*n).int32++
}

func (n Int32) String() string {
        return fmt.Sprintf("%d", n.int32)
}

type EventCounter interface {
        Num
        IncTwice()
}

type Event struct {
        Num
}

func (e Event) IncTwice() {
        e.Inc()
        e.Inc()
}

func main() {
        e := Event{&Int32{42}}
        e.IncTwice()
        fmt.Println(e)
}

(Alse here)

Output
44


text:
Q: SQL CLR Function Table Input & Output I am new here, and this is my first question.
I've created a dll in VB in order to use it in SQL server 2008 R2 Development
the below example is functional if I remove the table input (and use xml), but I need to have a table input.
--VB--
[SqlFunction(DataAccess:=DataAccessKind.Read, FillRowMethodName:="FillRow", TableDefinition:="ID int, Text nvarchar(max)")]
Public Shared Function MyFunction(ByVal tbl As IEnumerable(Of InputRow)) As IEnumerable
...
End Function

Public Shared Sub FillRow(...)
...
End Sub

Public Class InputRow
    Public sID As SqlInt32
    Public sText As SqlString
End Class

--SQL--
Create ASSEMBLY [ASSEMBLY1] from '[PATH].dll'
WITH PERMISSION_SET = unsafe
CREATE ASSEMBLY [ASSEMBLY2] from '[PATH].XmlSerializers.dll'
WITH PERMISSION_SET = unsafe

CREATE TYPE TableInput AS TABLE
(ID int, MyText varchar(1024))

CREATE FUNCTION ufn
(@sInputTable TableInput READONLY)
RETURNS TABLE (
    anID int null,
    SomeText nvarchar(max) null)
        WITH EXECUTE AS CALLER
AS EXTERNAL NAME MyDotNETAssembly.[MyNamespace.MyClassname].MyFunction

Error:
Msg 6552, Level 16, State 3, Procedure ufn, Line 2
CREATE FUNCTION for "ufn" failed because T-SQL and CLR types for parameter "@sInputTable" do not match.
Can anyone help?
how do I "assign" the input parameter in SQL?

A: In your CLR function, you should specify that ID and Text allow nulls such as TableDefinition:="ID int null, Text nvarchar(max) null".
You should also make sure that the column names match up with your InputRow class definition. To make it easier, I'd just ensure that the names are the same throughout. That is, change ID and sID to anID, Text and sText to SomeText.


text:
Q: Add Button to XML Layout programatically This problem has been asked many times here, but none of the solutions work for me, because my XML layout is a bit different.
I have an XML with LinearLayout containing an ImageView and a TextView. The XML is populated using Java code. It is a file picker library from here, it lists the files and folders that exists in the android filesystem.
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

   <ImageView
        android:id="@+id/file_picker_image"
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_marginBottom="5dip"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="5dip"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop"
        android:src="@drawable/file" />

    <TextView
        android:id="@+id/file_picker_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:singleLine="true"
        android:text="@string/file_name"
        android:textSize="28sp" />

</LinearLayout>

Now, I want to add a button just below this list. When I try to add the button in the XML, it iterates though each row, and buttons are shown in every row.
When I do it using Java code, neighter the button, nor the textview is displayed, but the image view is displayed.
What I want is similar to the image in this post, but cannot achieve it till now. None of those solutions or any other that I read here works in my case.
I am trying to add the button using this code in the Activity whose source is in the link provided above. I tried to add the following code in FilePickerListAdapter's constructor.
            RelativeLayout relLayout = new RelativeLayout(context);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

            Button filterBtn = new Button(context);
            filterBtn.setText("Filter");

            relLayout.addView(filterBtn, params);

Please guide me what am I doing wrong, and how to make it possible.
Regards.

A: Mixing the xml way and programmatic way to create views is not a good idea. You might as well  create all views in xml first (including your button), only set your button to android:visibility="gone" to hide it. Set it to visible when you want.

A: This might not be something you asked for, but it's an alternative that you can try it out. I implemented layout_weight into your xml and included the button at the end of the screen. The outcome of this will be something similar with the link in your question.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight=".9" >

       <ImageView
           android:id="@+id/file_picker_image"
           android:layout_width="40dip"
           android:layout_height="40dip"
           android:layout_marginBottom="5dip"
           android:layout_marginLeft="5dip"
           android:layout_marginTop="5dip"
           android:contentDescription="@string/app_name"
           android:scaleType="centerCrop"
           android:src="@drawable/file" />

       <TextView
           android:id="@+id/file_picker_text"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginLeft="10dip"
           android:singleLine="true"
           android:text="@string/file_name"
           android:textSize="28sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight="0.1" >

        <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />  <!--Your Button-->

    </LinearLayout>

</LinearLayout>


text:
Q: How to update angular ng-class when a variable changes? I want my ng-class to update when the variable in my controller changes. For some reason, it is only triggered on the page load and whilst the variable change, the ng-class does not update to reflect this.
Here is the code that triggers the variable change:

Here is the code which I want to change depending on the variable:

  {{user.firstName}} {{user.lastName}}

Here is the corresponding code from the controller:
$rootScope.isLeftMenuOpen = false;
$rootScope.isRightMenuOpen = false;

$scope.switchMobileMenu = function(direction) {
       if (direction === 'left') {
           $scope.isLeftMenuOpen = !($scope.isLeftMenuOpen);
       } else {
           $scope.isRightMenuOpen = !($scope.isRightMenuOpen);
       }
};

It seems that ng-class is only set on the initial ng-click. I believe I need to wrap the above function in a $scope.apply() function so that the ng-class watches for changes and applies them as the ng-click toggles the variable. Am I on the right track? If so, how would I do this?

A: You don't need $scope.$apply. Working example: https://jsbin.com/fogasiniku/edit?html,js,output
Do you really have double dashes in the CSS class name?


text:
Q: Migrating ASP.NET SQL Membership to ASP.NET Identity with Database First I have an old ASP.NET application that uses SQL Membership and uses aspnet_ tables to manage the logins, passwords, and roles, etc.
I'm wanting to rewrite the application using MVC 5 but it uses ASP.NET Identity and I haven't found an easy way to migrate to it using the new authentication method.
I tried following http://www.asp.net/identity/overview/migrations/migrating-an-existing-website-from-sql-membership-to-aspnet-identity
but that doesn't seem to work despite getting all of the SQL scripts to execute fine.
When trying to create a brand new ASP.NET MVC 5 application, I'm at a loss on tying it into my current database. I tried just setting the DB Context connection string to my entity framework connection string but it didn't like that.
Does anyone have any experience migrating an old .NET application to MVC 5 and keeping the database of users?

A: I'd say go for data migration if your passwords are not hashed (one-way encryption) in the database. I mean if your using something like DES and AES to encrypt and passwords are recoverable then data migration works for you and you can get rid of the old membership provider.
Otherwise, go for token based authentication and create a WebAPI service on top of the old membership to issue tokens and the rest of the job would be db-agnostic.

A: About the password hashing issue mentioned in the previous answer.
We managed to solve this problem when moved one of our old web-apps from MVC 3 (with SQL Membership) to ASP.NET Core (with Identity).
Here is a blog post with step-by-step instructions


text:
Q: Need specific instruction set to solve the conflict between two kinds of class constructors (one of them with std::initializer_list) A class (dLinkedList) need to have different c-tors: [please don't suggest to use STL containers!]
explicit dLinkedList(const int value);
dLinkedList(const dLinkedList &rhs);
explicit dLinkedList(size_t numberOfNode, int initializationValue);
dLinkedList(const std::initializer_list<int> &arg);

However, the c-tor with initializer_list seems to be not working. For example, if we construct a class like this:
dLinkedList test1 {10, 108}; // intention is to create 10 elements of 108 value each

But my question is -- based on the arguments - this c-tor can well be considered as one with initializer_list<int>. How do I resolve this conflict?
The implementation of the last two constructors
and the structure of the class dLinkedList are as follow:
class dLinkedList
{
public:

    //constructors will go here
    explicit dLinkedList(const int value)
    {
        createFirstNode(value);
        nodeCount = new size_t;
        updateNodeCount();
    }

    dLinkedList(const dLinkedList &rhs)
    {
        Node *temp = rhs.head;

        createFirstNode(temp->data);
        temp = temp->next;
        while(temp)
        {
            push_back(temp->data);
            temp = temp->next;
        }

        nodeCount = new size_t;
        updateNodeCount();
    }

    explicit dLinkedList(size_t numberOfNode, int initializationValue)
    {
        createFirstNode(initializationValue);
        for(size_t i = 1; i < numberOfNode; ++i)
            push_back(initializationValue);

        nodeCount = new size_t;
        updateNodeCount();
    }

    /* constructor with std::initializer_list is not working!!
    dLinkedList(const std::initializer_list<int> &arg)
    {
        std::cout << "\n Here\t";
        if(arg.size() == 0) dLinkedList(1);
        else
        {
            for(auto it = arg.begin() + 1; it != arg.end(); ++it)
            {
                push_back(*it);
            }

            nodeCount = new size_t;
            updateNodeCount();
        }
    }*/

    //class destructor will go here
    ~dLinkedList()
    {
        clear();
        delete nodeCount;
        nodeCount = nullptr;
    }

    //member functions will go here
    void push_back(int);                    // will attach a new node at the end of the list
    void push_front(int);                   // will insert a new node at the beginning of the list
    bool insertNode(int, int, bool, bool);  // will insert a new node after the existing node (true = first occurrence from the head with value int OTHERWISE if false, then from the tail.)
    bool deleteNode(int, bool);             // will delete the existing node (true = first occurrence from the head with value int OTHERWISE if false, then from the tail.)
    void pop_back();                         // will delete the last node in the list
    void pop_front();                       // will delete the first node in the list
    size_t size();                          // will return the number of nodes/elements - experimental feature
    void printList(bool);                   // will print the values of the data - (true for ordered list, false for reverse ordered list)
    void swap(dLinkedList &rhs);             // will swap this linked-list with rhs

    //operator overloading go here
    dLinkedList& operator = (const dLinkedList &rhs);
    dLinkedList& operator + (const dLinkedList &rhs);
    dLinkedList& operator += (const dLinkedList &rhs);
    dLinkedList& operator >> (const size_t numberOfNodes);
    dLinkedList& operator << (const dLinkedList &rhs);

private:
    //defining the double linked-list structure
    struct Node
    {
        int data; //this is a generic place holder - will be replaced later with some actual data-structures
        Node *next;
        Node *previous;

        explicit Node(int x) : data(x), next(nullptr), previous(nullptr) {}
    };

    //member functions go here
    void createFirstNode(int val);  //will create the first node when the list is empty
    void clear();  // will be called when class destructor is called
    void updateNodeCount(); // keeps the nodeCount variable up-to-date
    bool empty(); // returns true if the list is empty

    //some experimental utility functions for internal use
    void ectomizeAndClip(Node*);
    Node *detectData(int, bool);
    void insertBefore(Node*, int);
    void insertAfter(Node*, int);

    //member variables go here
    Node *head {nullptr};
    Node *tail {nullptr};
    size_t *nodeCount {nullptr}; //experimental feature

};

A: You do not need to do anything to "resolve the conflict". The language does it for you; initialization in the form
dLinkedList test1 {10, 108};

will always call an initializer_list constructor if possible, falling back to a non-initializer_list constructor only if there are no viable initializer_list constructor candidates.
The problem is that the resolution of the potential conflict did not produce the outcome that you wanted. You want it to be resolved in favour of the two-element constructor.
It is possible to simulate what you want by having the initializer_list constructor delegate to another function only if it has two elements:
explicit dLinkedList(size_t numberOfNode, int initializationValue) {
    initialize(numberOfNode, initializationValue);
}
dLinkedList(const std::initializer_list<int> &arg) {
    if (arg.size() == 2) {
        initialize(arg[0], arg[1]);
        return;
    }
    // otherwise: initialize the list using the values in `arg`
}
private:
void initialize(size_t numberOfNode, int initializationValue) {
    // create `numberOfNode` nodes with value `initializationValue`
}

However, I would strongly recommend that you not do this, because it will be terribly confusing for the user if the meanings of the following three declarations are not similar:
dLinkedList test1 {1};
dLinkedList test2 {2, 3};
dLinkedList test3 {4, 5, 6};

In fact, a constructor that takes the number of nodes as the first argument, and the value with which to initialize those nodes as the second argument, is a bad idea in general. It will lead to bugs when users forget which argument is which.
A better way is to create a struct that has the desired number of nodes and desired initial value as members:
struct dLinkedListInit {
    int numberOfNodes;
    int initialValue;
};
explicit dLinkedList(dLinkedListInit i) {
    // ...
}

With C++20 designated initializers, this constructor could be used as follows:
dLinkedList l({.numberOfNodes = 10, .initialValue = 108});

Also, strike the constructor explicit dLinkedList(const int value); since the initializer list constructor can provide the same functionality. It is good to make users write out the braces explicitly to make it obvious that the value inside the braces is meant to be interpreted as an element value.


text:
Q: How can I login to Cisco WLC GUI using Ansible playbook with Username and Password and get an Output? I am trying to write an Ansible-Playbook to Login to Cisco WLC using Web GUI and get an Output from it. I am using Ansible uri module to do that, while running the code it get the Main page but can see if it is able to login or not. Please help.
- name: Login to WLC and Return webpage
  hosts: WLC
  connection: local
  gather_facts: flase

  tasks:

    - name: Login to Cisco WLC using web GUI
      uri:
        url: https://10.23.201.2
        method: GET
        force_basic_auth: yes
        url_username: username
        url_password: password
        validate_certs: False
        return_content: yes
        register: login
    - debug: var=login.stdout

A: You can use the aireos_command module. For example, if you wanted to get the output for the show wlan summary command, you should create something like this:
- name: show wlan summary
  aireos_command:
    provider:
      host: '{{inventory_hostname}}'
      username: '{{username}}'
      password: '{{password}}'
      timeout: 30
    commands:
      - show wlan summary
  register: output

Then, if you wanted to parse the output and convert it into another data type, you can use the parse_cli filter. Here is an example of how you could parse the output:
- set_fact:
  data: '{{ output["stdout"][0] | parse_cli("./specs/wlan_summary.yml") }}'

And inside the ./specs/wlan_summary.yml:
---
vars:
  wlan:
    wlc_id: '{{ item.wlc_id }}'
    state: '{{item.state}}'
    interface: '{{ item.interface }}'
    profile: '{{ item.profile }}'
    ssid: '{{ item.ssid }}'

keys:
  items:
    value: "{{ wlan }}"
    items: "^(?P<wlc_id>\\d)\\s+(?P<profile>.*?)\\s/\\s(?P<ssid>.*?)\\s{2,}(?P<state>\\w+)\\s+(?P<interface>\\w+)"

I hope it helps.


text:
Q: How to check all checkboxes using javascript in onClick button? I am trying to make a button to check all checkboxes in a single line of a button onclick. Let's assume some checkboxes...

<input name="chk1" type="checkbox" class="post_dest_check" value="1" />Opt1
<input name="chk2" type="checkbox" class="post_dest_check" value="2" />Opt2
<input name="chk3" type="checkbox" class="post_dest_check" value="3" />Opt3

<button type="button" class="action" onClick="document.getElementsByClassName('post_dest_check').map((elm)=>{ elm.checked = true;});">Todos</button>

When clicked, will give me error

SyntaxError: Unexpected token ')'".

I also have tried with forEach.
Why? What's wrong? Is there a way to do this without heaving to write a script in the root to call from button?
Edit: I think I miss some explanation about why I wish to do like this, a script inside the onClick property.
I have many forms that are loaded into the page as needed. By making a script in the page instead of in the form, I will have to create a "standard" to my forms, so the script can find the elements in the form every time is loaded. If I change one form, maybe I will have to change all of them and the script. Not a catastrophe, I just thought maybe a script inside the form can avoid this complexity - a built in automation.
Of course, if possible and advisable.

A: There are a few things wrong here:

*

*Do not use inline event attributes like onclick. Instead of using this 25+ year old technique that pre-dates standards and causes scalability and this binding issues, use the standard .addEventListener() that is separated from your HTML (which makes debugging easier by the way).

*Do not use getElementsByClassName() as this returns a live node list that can cause performance issues, especially in looping situations.

*.map() returns a new array, which in your use case is not needed and therefore a waste of resources. Instead, .forEach() is the better approach.

*Don't bother with self-terminating XHTML syntax. It buys you nothing and can add confusion as to where it can/can't be used.
In the code below, "event delegation" is used so that you can have one event handler handle any set of checkboxes that are within their own form.

// Set up an event handler at a common ancestor of all the elements you wish to handle
document.querySelector("section").addEventListener("click", function(event){
  // Check to see if the event was triggered by an element you care to handle
  if(event.target.classList.contains("action")){
    // Get your reference to all the checkboxes in that form
    // (.closest searches for the nearest matching ancestor) and
    // loop over the checkboxes with the .forEach() method that works on node lists
    event.target.closest("form").querySelectorAll("input.post_dest_check").forEach(function(box){
      box.checked = true;
    });
  }
});
<section>
<fieldset>
  <legend>Form 1</legend>
  <form>
    <input name="chk1" type="checkbox" class="post_dest_check" value="1">Opt1
    <input name="chk2" type="checkbox" class="post_dest_check" value="2">Opt2
    <input name="chk3" type="checkbox" class="post_dest_check" value="3">Opt3
    <button type="button" class="action">Todos</button>
 </form>
</fieldset>

<fieldset>
  <legend>Form 2</legend>
  <form>
    <input name="chk1" type="checkbox" class="post_dest_check" value="1">Opt1
    <input name="chk2" type="checkbox" class="post_dest_check" value="2">Opt2
    <input name="chk3" type="checkbox" class="post_dest_check" value="3">Opt3
    <input name="chk3" type="checkbox" class="post_dest_check" value="3">Opt4
    <button type="button" class="action">Todos</button>
 </form>
</fieldset>

<fieldset>
  <legend>Form 3</legend>
  <form>
    <input name="chk1" type="checkbox" class="post_dest_check" value="1">Opt1
    <input name="chk2" type="checkbox" class="post_dest_check" value="2">Opt2
    <button type="button" class="action">Todos</button>
 </form>
</fieldset>
</section>

A: How to check all checkboxes using javascript in onClick button?
for(el of document.getElementsByTagName('input')){if(el.type==="checkbox")el.checked=true;}

However, if you only want checkboxes with the class 'post_dest_check' you could be a little more specific.
for(el of document.getElementsByClassName('post_dest_check')){if(el.constructor.name==="HTMLInputElement"&&el.type==="checkbox")el.checked=true;}

I've only left out optional spaces as you've indicated you were going to use this in an inline onClick event handler.


text:
Q: Java EE Parameter Constraint Configuration strange behaviour Im trying to add a parameter constraint configuration (a bean validation) on the create and edit method of the standrd AbstractFacade (as generated by NetBeans).
So I tried:
@Override
public void create(@WkTeilnahmePlanedResult  WkTeilnahme entity) {
   super.create(entity);
}

This returned the message

A method overriding another method must not alter the parameter
  constraint configuration
  when deploying it to Glassfish 4

So next try was
  @Override
  public void create(WkTeilnahme entity) {
    checkedCreate(entity);
  }

  private void checkedCreate(@WkTeilnahmePlanedResult WkTeilnahme entity) {
    super.create(entity);
  }

which deploys without any problems ... but the validator is never called.
Can you tell me why?
BTW:
  @Override
  public void create(WkTeilnahme entity) {
    throw new UnsupportedOperationException(
            "Create not supported! Use checkedCreate() instead!");
  }

  public void checkedCreate(@WkTeilnahmePlanedResult WkTeilnahme entity) {
    super.create(entity);
  }

This works but isn't really very cool!

A: Regarding your first attempt, it does not work, because Bean Validation constraints must follow the Liskov Substitution Principle. See also the relevant Bean Validation specification section - http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-methodlevelconstraints-inheritance
From the specification:

Very informally speaking, the Liskov substitution principle says that
  where a given type T is used, it should be possible to replace T with
  a sub-type S of T ("Behavioral subtyping"). If S overrides/implements
  a method from T and S would strengthen the method's preconditions
  (e.g. by adding parameter constraints) this principle would be
  violated as client code working correctly against T might fail when
  working against S. Also if S overrides/implements a method from T and
  S weakens the method's postconditions this principle would be
  violated. However S may strengthen the method's postconditions (by
  adding return value constraints), as client code working against T
  still will work against S.

I think your second example should actually work, however, I am not familiar with the NetBeans AbstractFacade. My guess is that the call to checkedCreate(entity); is not going via a proxies instance and hence is not intercepted. Maybe you could post the full code for the involved classes? What type of class contains these methods? A session bean?

A: You should do these:
inteface Test {
   void create(@WkTeilnahmePlanedResult  WkTeilnahme entity);
}

@Validated
class TestImpl implement Test {
    @Override
    public void create(WkTeilnahme entity) {
       super.create(entity);
    }
}

A: I faced the same problem.
My code was like this:
public interface SomeService{
    List<Object> getObjects(Integer id);
}

public class SomeServiceImpl implements SomeService{
    @Override
    public List<Object> getObjects(@NotNull Integer id) { ... }
}

I added the same annotation to the service and the problem has been soled:
public interface SomeService{
    List<Object> getObjects(@NotNull Integer id);
}

A: Thanks Hardy.
Shure I can post them:
package at.wima.member.facade;

import java.util.List;
import javax.persistence.EntityManager;

public abstract class AbstractFacade<T> {
  private Class<T> entityClass;

  public AbstractFacade(Class<T> entityClass) {
    this.entityClass = entityClass;
  }

  protected abstract EntityManager getEntityManager();

  public void create(T entity) {
    getEntityManager().persist(entity);
  }

  public T edit(T entity) {
    return getEntityManager().merge(entity);
  }

  public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
  }

  public T find(Object id) {
    return getEntityManager().find(entityClass, id);
  }

  public List<T> findAll() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    return getEntityManager().createQuery(cq).getResultList();
  }

  public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(range[1] - range[0]);
    q.setFirstResult(range[0]);
    return q.getResultList();
  }

  public int count() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(getEntityManager().getCriteriaBuilder().count(rt));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
  }

}

and the subclass
package at.wima.member.facade;

import at.wima.member.entity.*;
import at.wima.member.validations.*;
import java.util.*;
import javax.ejb.Stateless;
import javax.persistence.*;

@Stateless
public class WkTeilnahmeFacade extends AbstractFacade<WkTeilnahme> {

  @PersistenceContext(unitName = "memberPu")
  private EntityManager em;

  public WkTeilnahme findByKey(Mandant mandant, Wettkampf wettkampf,
                               Person person) {
    Query query = em.createNamedQuery("wkTeilnahmeFindByKey");
    query.setParameter("mandant", mandant);
    query.setParameter("wettkampf", wettkampf);
    query.setParameter("person", person);
    List rl = query.getResultList();

    if (rl.size() <= 0) {
      return null;
    }
    return (WkTeilnahme) (rl.get(0));
  }

  public List<WkTeilnahme> findAllSort(Mandant mandant) {
    Query query = em.createNamedQuery("wkTeilnahmeFindAllSort");
    query.setParameter("mandant", mandant);
    return query.getResultList();
  }

  public List<WkTeilnahme> findByWettkampf(Mandant mandant, Wettkampf wettkampf) {
    Query query = em.createNamedQuery("wkTeilnahmeFindByWettkampf");
    query.setParameter("mandant", mandant);
    query.setParameter("wettkampf", wettkampf);
    return query.getResultList();
  }

  @Override
  public void create(WkTeilnahme entity) {
    throw new UnsupportedOperationException(
            "Create not supported! Use checkedCreate() instead!");
  }

  public void checkedCreate(@WkTeilnahmePlanedResult WkTeilnahme entity) {
    super.create(entity);
  }

  @Override
  public WkTeilnahme edit(WkTeilnahme entity) {
    throw new UnsupportedOperationException(
            "Edit not supported! Use checkedEdit() instead!");
  }

  public WkTeilnahme checkedEdit(@WkTeilnahmePlanedResult WkTeilnahme entity) {
     return super.edit(entity);
  }

  @Override
  protected EntityManager getEntityManager() {
    return em;
  }

  public WkTeilnahmeFacade() {
    super(WkTeilnahme.class);
  }
}


text:
Q: Nativescript calendar plugin Can anyone tell me how to use the calendar plugin in nativescript? And I am using only XML not with typescript. I need the calendar control exactly like as in Bookmyshow.

A: There are several options for calendar plugin.
The most extended one is the telerik-ui for NativeScript
The calendar is highly customisable and offers a lof of functionality.
You can see more about it here - keep in mind that this is a paid functionality.
Another option is to search for community-made nativescript calendar related plugins. Like this one here! Not familiar with it - it looks easy to work with.
The third option is to use date-picker. IF you are looking for a calendar in Android then you can open your app/App_Resources/Android/values-21 folder and open the file styles.xml and modify the default mode of the date picker from spinner to calendar.
Example:
<item name="android:datePickerMode">calendar</item>

A: You might be interested in the "Telerik UI for NativeScript" plugin. There is a free and pro version which contains a really slick looking and functioning calendar UI component.
More details about the plugins and their contents can be found here. Additionally you can take a look at the sdk examples regarding the RadCalendar component for both vanila and Angular 2 NativeScript.

A: I'm using this npm package:
https://www.npmjs.com/package/nativescript-calendar
"nativescript-calendar": "^1.0.7",

A: I juss created a wrapper over android-lib which help in rendering calendar in nativescript. checkout the plugin
https://www.npmjs.com/package/nativescript-calendar-weekview


text:
Q: Random Forest can't overfit? I've read some literature that random forests can't overfit.  While this sounds great, it seems too good to be true.  Is it possible for rf's to overfit?

A: Hastie et al. address this question very briefly in Elements of Statistical Learning (page 596).

Another claim is that random forests "cannot overfit" the data. It is certainly true that increasing $\mathcal{B}$ [the number of trees in the ensemble] does not cause the random forest sequence to overfit... However, this limit can overfit the data; the average of fully grown trees can result in too rich a model, and incur unnecessary variance. Segal (2004) demonstrates small gains in performance by controlling the depths of the individual trees grown in random forests. Our experience is that using full-grown trees seldom costs much, and results in one less tuning parameter.

A: Random forest can overfit. I am sure of this. What is usually meant is that the model would not overfit if you use more trees.
Try for example to estimate the model $y = log(x) + \epsilon$ with a random forest. You will get an almost zero training error but a bad prediction error

A: I will try to give a more thorough answer building on Donbeo's answer and Itachi's comment.
Can Random Forests overfit?
In short, yes, they can.
Why is there a common misconception that Random Forests cannot overfit?
The reason is that, from the outside, the training of Random Forests looks similar to the ones of other iterative methods such as Gradient Boosted Machines, or Neural Networks.
Most of these other iterative methods, however, reduce the model's bias over the iterations, as they make the model more complex (GBM) or more suited to the training data (NN). It is therefore common knowledge that these methods suffer from overtraining, and will overfit the training data if trained for too long since bias reduction involves an increase in variance.
Random Forests, on the other hand, simply average trees over the iterations, reducing the model's variance instead, while leaving the bias unchanged. This means that they do not suffer from overtraining, and indeed adding more trees (therefore training longer) cannot be source of overfitting. This is where they get their non-overfitting reputation from!
Then how can they overfit?
Random Forests are usually built of high-variance, low-bias fully grown decision trees, and their strength comes from the variance reduction that comes from the averaging of these trees. However, if the predictions of the trees are too close to each other then the variance reduction effect is limited, and they might end up overfitting.
This can happen for example if the dataset is relatively simple, and therefore the fully grown trees perfectly learn its patterns and predict very similarly. Also having a high value for mtry, the number of features considered at every split, causes the trees to be more correlated, and therefore limits the variance reduction and might cause some overfitting  (it is important to know that a high value of mtry can still be very useful in many situations, as it makes the model more robust to noisy features)
Can I fix this overfitting?
Like always, more data helps.
Limiting the depth of the trees has also been shown to help in this situation, and reducing the number of selected features to make the trees as uncorrelated as possible.

For reference, I really suggest reading the relative chapter of Elements of
Statistical Learning, which I think gives a very detailed analysis, and dives deeper into the math behind it.


text:
Q: How to convert custom type definition file to npm type definition file I have a custom module definition file for a dependency written in CoffeeScript in my typescript project.
It looks like the following and works great:
src/@types/dependency-name.d.ts
declare module 'dependency-name' {
  import EventEmitter from 'eventemitter3';

  /**
  * omitted
  */

  interface ICable {
    new (channels: Record<string, ISubscription>): ICable;

    channels: Record<string, ISubscription>;

    channel: (name: string) => ISubscription | undefined;
    setChannel: (name: string, channel: ISubscription) => ISubscription;
  }
  export const Cable: ICable;
}

So I want to contribute to this project and submit a type definition file.
What I tried is:

*

*Forked the original CoffeeScript project,

*Copied the above definition to index.d.ts

*Add the following line to pacakge.json:

"typings": "index.d.ts",

*Installed forked repository in my typescript project for testing.

However, it does not recognize the added index.d.ts file. Shows type definition is missing error.
I've seen this post and guessed that the issue is this one:

be written as external modules

But I don't understand it. Can someone guide me to convert my custom typing (module augmentation, I guess?) to correct type definition file for package.json?

A: I would recommend looking directly at the TypeScript handbook page linked from the post you linked, as the post itself is rather old and the copy of the text there is a bit outdated. In particular, "types" is now preferred over "typings" in package.json, although both should still work.
However, you and the post are correct that the issue is one of ambient external modules ("ambient modules") vs. non-ambient ones ("external modules"). You should just need to remove the declare module block wrapping around your file, leaving its contents at the top level. That will transform your declarations from ambient to non-ambient and should make it work.


text:
Q: How to set the resolution of a macro exporting images of LibreOffice Writer pages? Previously I've asked how to export all pages of a LibreOffice Writer document to images. I've got this answer.
I've adapted the macro towards my needs and this is my current code:
Sub StoreEachPageToWebP()
    Dim oDoc As Variant, oViewCursor As Variant
    Dim iPageCount As Long, iPage As Long
    Dim sOriginalURL As String, sFileURL As String
    dim args1(1) as new com.sun.star.beans.PropertyValue
    args1(0).Name = "FilterName"
    args1(0).Value = "writer_webp_Export"
    args1(1).Name = "FilterData"
    args1(1).Value = Array(Array("Quality",0,75,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Lossless",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PixelWidth",0,1000,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PixelHeight",0,647,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("LogicalWidth",0,26455,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("LogicalHeight",0,17116,com.sun.star.beans.PropertyState.DIRECT_VALUE))

    oDoc = ThisComponent
    iPageCount = oDoc.getCurrentController().PageCount
    oViewCursor = oDoc.getCurrentController().getViewCursor()
    sOriginalURL = oDoc.getURL()
    oViewCursor.jumpToFirstPage()
    For iPage = 1 To iPageCount
        sFileURL = Replace(sOriginalURL, ".odt", "-" & Format(iPage, "000") & ".webp")
        oDoc.StoreToURL(sFileURL, args1)
        If Not oViewCursor.jumpToNextPage() Then End
    Next iPage
End Sub

Unfortunately FilterData options seem to be ignored. The exported WebP-Images always have the same resolution, which is the standard size of the page. When I export it manually it works. I've used the macro recorded to get the options for FilterData so I can be quite sure that they are correct. The recorded macro looks like this:
sub RecordedPageExportAsWebP
rem ----------------------------------------------------------------------
rem define variables
dim document   as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document   = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")

rem ----------------------------------------------------------------------
dim args1(3) as new com.sun.star.beans.PropertyValue
args1(0).Name = "URL"
args1(0).Value = "file:///home/user/Documents/namecards-all.webp"
args1(1).Name = "FilterName"
args1(1).Value = "writer_webp_Export"
args1(2).Name = "FilterData"
args1(2).Value = Array(Array("Quality",0,75,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("Lossless",0,true,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PixelWidth",0,1000,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("PixelHeight",0,647,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("LogicalWidth",0,26455,com.sun.star.beans.PropertyState.DIRECT_VALUE),Array("LogicalHeight",0,17116,com.sun.star.beans.PropertyState.DIRECT_VALUE))
args1(3).Name = "SelectionOnly"
args1(3).Value = false

dispatcher.executeDispatch(document, ".uno:ExportTo", "", 0, args1())

end sub

What am I missing here?
I'm using the following version of LibreOffice:
Version: 7.4.0.3 / LibreOffice Community
Build ID: 40(Build:3)
CPU threads: 8; OS: Linux 5.19; UI render: default; VCL: gtk3
Locale: en-US (en_US.UTF-8); UI: en-US
7.4.0-3
Calc: threaded

A: As I said, a few extra lines of code will be required to set the resolution:
Sub StoreEachPageToPNG()
Dim oDoc As Variant, oViewCursor As Variant
Dim iPageCount As Long, iPage As Long
Dim sOriginalURL As String, sFileURL As String
Dim pngFilterData(1) As New com.sun.star.beans.PropertyValue
    pngFilterData(0).Name = "PixelWidth"
    pngFilterData(0).Value = 1634 ' or as much as you need
    pngFilterData(1).Name = "PixelHeight"
    pngFilterData(1).Value = 2114 ' take care to maintain proportions
Dim Args(1) As New com.sun.star.beans.PropertyValue
    Args(0).Name = "FilterName"
    Args(0).Value = "writer_png_Export"
    Args(1).Name = "FilterData"
    Args(1).Value = pngFilterData

    oDoc = ThisComponent
    iPageCount = oDoc.getCurrentController().PageCount
    oViewCursor = oDoc.getCurrentController().getViewCursor()
    sOriginalURL = oDoc.getURL()
    oViewCursor.jumpToFirstPage()
    For iPage = 1 To iPageCount
        sFileURL = Replace(sOriginalURL, ".odt", " - " & Format(iPage, "000") & ".png")
        oDoc.StoreToURL(sFileURL, Args)
        If Not oViewCursor.jumpToNextPage() Then End
    Next iPage
End Sub

Be careful when increasing the values for PixelWidth and PixelHeight, don't be greedy - the size of the output file grows rapidly!
Of course, this code is still far from perfect - for example, this macro does not check if the current document has a name (if the file is saved), if there is permission to write files to the target folder, if files with the target name already exist and are not locked, etc.


text:
Q: Toolstrip Container missing from Winforms Designer? I'm porting a huge winforms application from .NET Framework 4.8 to .NET 5.
It seems the Toolstrip Container is missing from the Designer. Everything behaves normally in run time, but the designer breaks if the form has a Toolstrip Container in it. Everything gets filled with red crosses, and sometimes VS crashes.
The component toolbar doesn't show Toolstrip Container anymore, but it isn't part of any list of discontinued components and it's still there when I run the program. I searched the web for answers but found nothing.
Has anyone had this experience or knows of any fix for the problem?


text:
Q: Message Enricher Usage I have a mule flow with some javabean payload, what i'd like to do is enrich some varaiables using some xml (xpath) returned from an https outbound url.
What i"m trying is something like: (Assume the whole certificate/tls issue is not the problem):
<enricher>
    <https:outbound-endpoint name="clientEndpoint" address="https://someaddress"
         connector-ref="httpConnector" exchange-pattern="request-response"/>
        <enrich target="#[variable:paymentValidated]" source="#[xpath:INCIDENTS/INCIDENT/@state]" />
</enricher>
<logger message="#[variable:paymentValidated]" level="ERROR" />

However, i cant seem to be able to work with the xml returned from the https endpoint, i keep getting XPATH violations. after checking my xpath with a validator i am certain that i am giving a correct xpath.
I also tried using a bytearraytostring response tranformer - but the problem was not solved.
Anyone have any idea how to fix this and make it work??
The xml i"m attempting to parse:
<?xml version="1.0" encoding="UTF-8" ?>
<INCIDENTS process_ms="56">
  <INCIDENT assignee="Unassigned" closedtime="" createdtime="Fri Jan 20 15:13:10 EST 2012" creator="System" disposition="Not Set" disposition_id="-1" domain="SES" guid="5749976847410062927" id="147" incident_type="security" modifiedtime="Sat Jan 21 15:13:15 EST 2012" open_duration="2 days 18 hours 53 mins 56 secs" priority="3" referencenum="0000000147" severity="4" state="New" state_id="0" status="Open" status_id="1" team="Unassigned" tracking="No" type="SomeType" userpriority="">
    <DESCRIPTION>
    <![CDATA[ Some message" ]]>
    </DESCRIPTION>
  </INCIDENT>
</INCIDENTS>

A: Since you're not showing the exact error, I'll try to guess.
I think the issue comes from the fact you select the state attribute from a list of incidents instead of just one. Try with:
/INCIDENTS/INCIDENT[1]/@state

A: You can also use the feature of Mule Xpath3 which is from Mule 3.6
Something like follow :-
#[xpath3('/INCIDENTS/INCIDENT[1]/@state')]

Please find the linke for Xpath3 here :- https://developer.mulesoft.com/docs/display/current/XPath


text:
Q: How to display mobile view for mobile devices in Yii2? I have main and mobile sites: site.com and m.site.com.
How to display different views/themes in Yii2 for mobile and desktop devices?
May be I should using themes, but how display different views?
P.S. I don't want use responsive design. Thank you!


text:
Q: Iptables remote port forwarding and dynamic remote ip I want to forward a port from my remote vps to my domestic server and I am quite a newbie with iptables.
The problem is that I am using a dynamic dns service to reach my home server from the internet so I don't have a fixed ip and iptables doesn't like urls.
The rules I am willing to use are these:
-t nat -A PREROUTING -p tcp -i eth0 -d xxx.xxx.xxx.xxx --dport 8888 -j DNAT --to myhome.tld:80
-A FORWARD -p tcp -i eth0 -d myhome.tld --dport 80 -j ACCEPT

Of course I recevie a Error BAD IP ADDRESS because of myhome.tld.
What can I do?

A: This will not work as iptables needs fixed ip addresses.
I'd suggest either running a VPN between the machines or having a watchdog that will reapply the rules when your home address changes.

A: Try using Shorewall to build your firewall.  It will expand DNS for you with caveats.  (DNS must be reachable during startup.)  There are notes in the documentation.  You will need a trigger to reload the firewall when your IP address changes.  The DHCP clients have hooks where you can do this.