text:
Q: Special case of Bertrand Paradox or just a mistake? I've been working on a question and it seems I have  obtained a paradoxical answer. Odds are I've just committed a mistake somewhere, however, I will elucidate the question and my solution just in case anyone is interested.

I want to know what is the average distance between two points on a circle of radius 1 where we consider only the boundary points.

My attempt is as follows:
Consider a segment of the diameter x which is uniformly distributed between 0 and 2. Then you can calculate the distance between the points (2,0) and the point determined by x just by elementary geometry as this picture shows:

Here in the picture, the green segment is the geometric mean and the orange one is the distance whose distribution we want to know.
Just by calculating the expected value, we obtain:
$E\left(\sqrt{(4-2X)}\right) = \int_{0}^{2} \sqrt{(4-2x)}\cdot\frac{1}{2} dx = 1.333.... = \frac{4}{3}$
Where $\sqrt{(4-2x)}$ is the transformation of the random variable and $\frac{1}{2}$ is the pdf of a uniform distribution $[0,2]$.
Also, if we derive the pdf of the transformation we obtain the same result:
$y = \sqrt{(4-2x)} , x = 2- \frac{y^2}{2}, \mid\frac{d}{dy}x\mid = y$
$g(y)=f(x)\cdot\mid\frac{d}{dy}x\mid = \frac{1}{2}\cdot y$
$E(Y)= \int_{0}^{2}y\cdot\frac{1}{2}\cdot y dy = 1.333.... = \frac{4}{3} $
I have seen a different approach somewhere else where the distribution of the angle is considered as a uniform distribution between 0 and $\pi$ and the final result was:
$1.27... = \frac{4}{\pi}$
That's pretty much the problem I found. Maybe I just did it wrong in some step but it all makes sense to me. I know this is not exactly what we refer as Bertrand paradox but it just suggests something like that because both problems handle with segments in circumference and maybe my result is wrong because it does not hold for rotations of the circle or something like that (I read a little bit about the Bertrand's Paradox).

That's pretty much it. Also sorry for my bad English and maybe I'm also wrong in something pretty elemental since I've just started learning about probability theory. It's also my first post so I will try to improve my exposition and LateX use in the following ones.

A: This is a very nice question, well-written and researched before posting.  You have clearly put a lot of careful into your question and it is very much appreciated on this site (and I thought your English reads perfectly naturally).  Thanks so much for taking the time to ask a serious and well-considered question.  I hope this answer comes close to meeting the high standard of quality set by your question.
I don't see any calculation errors on your part, and I'll wager you checked those thoroughly.  The flaw is something much more subtle and is related to the initial framing of the problem.
You have correctly solved the problem of "what is the average distance between the rightmost point of a circle and another point projected upwards from a randomly chosen point on the diameter".   But this doesn't quite capture the same probability distribution as "rightmost point and another randomly chosen point on the circle" (which is sufficient to capture the dynamics of "two random points on the circle").
There is a hidden non-uniformity in the projection process, and that's because the circle has varying slope so the projection hits the circle differently at different positions.
Here's an experiment that should help convince you that uniform distribution on the diameter does not yield uniform distribution on the circle boundary.  Fundamentally, a uniform distribution should treat all arcs of the same length equally: a random point has a $1/4$ chance of falling on a quarter-circular arc, regardless of which quarter circle that is.
Now compare two specific quarter-circles and their projections onto the diameter: 1) the quarter-circle adjacent to $(2,0)$, i.e. 12 o'clock to 3 o'clock, and 2) the quarter-circle centered around the top-most point $(1,1)$, i.e. 10:30 to 1:30.
These both project onto the diameter with no self-overlap (avoiding double counting).  But the first one projects down to the interval  $[0,1]$ which has length $1$, and the second one projects down to $[-\sqrt{2}/2,\sqrt{2}/2]$, which has length $\sqrt2$.
This should indicate to you that the two distributions are not equivalent (though they may intuitively seem so).  Consequently, the random process of choosing uniformly from the diameter and projecting onto the circle results in disproportionately favoring the top and bottom sectors of the circle over the left and right.

A: Thanks, Erick Wong for your feedback. After your answer, I calculated the distribution of the arc length subject to the uniform distribution of the point on the diameter. In fact: if we want to express the arc length $l$ as a function of $x$, $l = f(x)$ we obtain:
$l = \arccos(1-x), x = 1-\cos{l}, |\frac{d}{dl}(x)| = \sin{l}$
$l_{pdf} = x_{pdf} \cdot |\frac{d}{dl}x| = \frac{1}{2}\cdot \sin{l}$.
So the arc length does not distribute uniformly, we have "lost it", we might say. That's what was wrong.
For instance, if the arc length obeys a uniform distribution [0, $\pi$], then we can calculate the segment $s$ as a function of the arc length:
We know $l = f(x)$ and want to know $s = h(l)$. If we calculate $s = g(x)$ we're done:
From the image on the question I post, $s = g(x)=\sqrt{2x}$ (or the opposite segment $\sqrt{4-2x}$ ) then $h = g \circ f^{-1}$, $s = \sqrt{2(1-cosl)}$
$E(s) = \int_0^\pi{\sqrt{2(1-cosl)}\frac{1}{\pi}dl}=1.273... = \frac{4}{\pi}$
Also the pdf:
$s = h(l) = \sqrt{2(1-cosl)} ,  l=h^{-1}(s)= 2\cdot \arcsin(\frac{s}{2}), |\frac{d}{ds}h^{-1}|=\frac{2}{\sqrt{4-s^2}}$
$s_{pdf} = \frac{1}{\pi} \frac{2}{\sqrt{4-s^2}}$
$E(s) = \int_0^2{s\cdot \frac{1}{\pi} \frac{2}{\sqrt{4-s^2}}ds} = 1.273... = \frac{4}{\pi}$
So we're done. Also, the pdf of the segment suggests something related to the Cauchy distribution. Not exactly but certainly it has to do something with it. If we read the description of Cauchy distribution in Wolfram MathWorld:
"The Cauchy distribution, also called the Lorentzian distribution or Lorentz distribution, is a continuous distribution describing resonance behavior. It also describes the distribution of horizontal distances at which a line segment tilted at a random angle cuts the x-axis."
And that's it. A really fascinating problem that introduces some subtle ideas of probability theory. If anyone knows something else please give me feedback. I really think there's a nice connection with Cauchy distribution.


text:
Q: ie shows border when image is clicked I'm using jQuery to change between clases when an image is clicked.
In chrome & FF everything is fine but in ie9 (probably also earlier) when i click one
of the image some ugly gray border appears.
This is the html code:

This is the style:
.PastWin_Unmarked{border:0px;display: block;background-image:url('images/tomgui3_08.png');background-repeat:no-repeat;width:206px;height:43px;text-decoration:none;}

And here is an image with the ugly border that appears:

A: You can remove it with...
a:focus {
   outline: none;
}

However, keep in mind some people need this as a visual cue when navigating via the keyboard.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap Button Grid-Size I'm trying to make a button that spans 12 columns.
I know how to create a div that is 12 columns as such

But that only makes the div 12 columns long. If I was to replace the div with a input:button how would I get that to work?

A: Add the class btn-block and place it inside the 12-column
. (Note: this is Bootstrap 2.3.2)

    <button class="btn btn-large btn-block btn-primary" type="button">Block level button</button>

A: Why not use <button></button>? (bootstrap3)

<button class='btn btn-lg btn-warning col-lg-12' >button</button>


text:
Q: OpenGL GLFW + GLAD Program cannot draw triangle I'm trying to draw a triangle with GLFW and Glad.
But it doesn't display anything on screen.
I'm able to open window and make the screen to any Color but cannot draw triangle.
It show like this
enter image description here
I'm doing this program in Ubuntu22
(required lib are imported glad, glfw, math, iostream)

const char* vertexShaderSource = "#version 330 core\n"
"latout (location =0) in vec3 aPos;\n"
"void main()\n"
"{\n"
"   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
"   FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";

int main(){
    glfwInit();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLfloat vertices[] =
    {
        -0.5, -0.5f * float(sqrt(3)) / 3, 0.0f,
        0.5f, -0.5f * float(sqrt(3)) / 3, 0.0f,
        0.0f, 0.5f * float(sqrt(3)) * 2 / 3, 0.0f
    };

    GLFWwindow* window = glfwCreateWindow(600, 600, "TriangleOpenGL", NULL, NULL);
    if(window == NULL)
    {
        std::cout<<"Failed to create GLFW window"<< std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    gladLoadGL();

    glViewport(0, 0, 600, 600);

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);

    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    GLuint VAO, VBO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    glClearColor(0.07f, 0.13f, 0.17f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glfwSwapBuffers(window);

    while(!glfwWindowShouldClose(window))
    {
        glClearColor(0.07f, 0.13f, 0.17f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glUseProgram(shaderProgram);
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteProgram(shaderProgram);

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

A: You have syntax error in your vertex shader:
"latout (location =0) in vec3 aPos;\n"

It should be layout (location = 0).
You can easily find it yourself if you add something like that after glCompileShader.
  GLint logLength;
  glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &logLength);
  if (logLength > 0)
  {
    GLchar *log = new GLchar[logLength];
    glGetShaderInfoLog(vertexShader, logLength, &logLength, log);
    std::cout << log << std::endl;
    delete[] log;
  }


text:
Q: Isomorphism between Galois Groups Let $q$ prime and $n$ natural number coprime to $q$. Futhermore let $\zeta_n$ be the primitive $n$-th root.
I want to know how to prove using Hensel's Lemma that for Galois groups
$$\text{Gal}(\mathbb{Q}_q[\zeta_n]/\mathbb{Q}_q) \cong \text{Gal}(\mathbb{F}_q[\zeta_n]/\mathbb{F}_q)$$ holds?
My first idea was to consider the cyclotomic polynomial $\Phi_n$ in $\mathbb{F}_q[X]$. Does it split there?

A: Maybe you're familiar with only the weak version of Hensel. Here's the version you want:
Let $(\mathfrak o,\mathfrak m)$ be a complete (noetherian) local ring with residue field $\mathfrak o/\mathfrak m=k$. Let $f(X)\in\mathfrak o[X]$, with $\bar f=\gamma\eta\in k[X]$, and $\gcd(\gamma,\eta)=1$. Then there are $g,h\in\mathfrak o[X]$ with $\deg(g)=\deg(\gamma)$, $\bar g=\gamma$, $\bar h=\eta$, and $gh=f$.
It's particularly easy to prove when $\mathfrak o$ is a discrete valuation ring, your situation, but in any case, you prove it by using the standard strategy of improving a factorization modulo $\mathfrak m^r$ to a factorization modulo $\mathfrak m^{r+1}$, using the hypothesis that $\gamma$ and $\eta$ are relatively prime at a crucial point. And you have to pay attention to the degree of the approximations to $g$ at every stage, for otherwise you'll find yourself defining a power-series factorization. And one other thing: you can get around the degree aspect of the statement and proof by demanding at the outset that $\,f$, $\gamma$, and $\eta$ be monic, and finding monic $g$ and $h$; but one of the most useful applications requires allowing $\,f$ to have highest coefficient in $\mathfrak m$.


text:
Q: I'm getting some unknown requests in my "app engine" aplicattion and want to know what they are it's just a simple express js web app in standard environment, i put my custom domain and is working ok,
but a couple of days ago I started receiving these requests and I want to know what they are.

A: Those requests are typically Let's Encrypt requests to verify that you control the domain during the SSL certificate validation process.
The response is 404 Not Found which means the pages do not exist.
Those requests are harmless provided that you do not receive a massive number of requests.


text:
Q: VisualStudio 2017 - always show exceptions I have a Visual Studio App (Windows.Forms) that build a release .exe-App. If I run this exe an exception occurs, I only can see it in the windows log, nothing more happens.
But I would like to see the JIT Exception Window. Can I activate this somehow in VS?
Im asking for a general "If any exception at runtime - show the JIT Debugger"-switch. Is something like this available?

A: Did it now like here shown.
http://www.csharp-examples.net/catching-unhandled-exceptions/
Instead of logging made an MessageBox with the Exception Message und Application.Exit(). Works exactly as i like it to have.


text:
Q: WiX installation into nested folder I want to install my application by default according to schema:

Program Files/Company Name/Product Name

I write in WiX script:
<Directory Id="TARGETDIR" Name="SourceDir">
  <Directory Id="ProgramFilesFolder">
    <Directory Id="ApplicationRoot" Name="Company Name">
      <Directory Id="APPLICATIONFOLDER" Name="Product Name">
      </Directory>
    </Directory>
  </Directory>
</Directory>

Then all components are targeted to APPLICATIONFOLDER. However, setup installs files into

Program Files/Company Name/

What is wrong?


text:
Q: Matrix Calculation that Matches Numbers Contained within the Row and Column Names I have a matrix that contains economic information on industries for several countries. I want to do a series of calculations that depend on the positioning of the element in the matrix and the corresponding column / row names.
The row / column names has a three letter country code followed by an industry number. The row and column names are identical.
The calculation would be as follows:

*

*For each element in a row, there will be a matched country and industry

*Keeping the industry combination the same, multiply the industry of purely the same country with the same one in the other country inside of the match.

I will give a simple example, although my data is much bigger than this example.
Say I have matrix a
set.seed(10)

a <- matrix(sample(36) , nrow = 6)
colnames(a) <- rownames(a) <- paste( rep(c("aaa" , "bbb" , "ccc") , each = 2), rep(c(1:2) , times = 3))

Giving:
      aaa 1 aaa 2 bbb 1 bbb 2 ccc 1 ccc 2
aaa 1     9    19    26     6     5    21
aaa 2    10    24     2    30    36    27
bbb 1    12    15    13    11    20    16
bbb 2     8    28    33    18    34    17
ccc 1    22    35    14    23    29     4
ccc 2     7    31    25    32     1     3

In this case there are three countries "aaa", "bbb" and "ccc" and only two industries, 1 and 2. I want to calculate the value of industries produced in their own countries and multiply with each other.
For example, in a[1, 4] this would match "aaa 1" with "bbb 2". I would want to multiply industry combination 1 - 2 for each country i.e. "aaa 1" - "aaa 2" with "bbb 1" - "bbb 2" (19 * 11 = 209). The values along the blocks of diagonals would be squared (two times the same country).
The final matrix would look like:
      aaa 1 aaa 2 bbb 1 bbb 2 ccc 1 ccc 2
aaa 1    81   361   117   209   261    76
aaa 2   100   576   330   432    10    72
bbb 1   117   209   169   121   377    44
bbb 2   330   432  1089   324    33    54
ccc 1   261    76   377    44   841    16
ccc 2    10    72    33    54     1     9

Which I calculated manually using this inefficient following code:
b <- kronecker(diag(1, 3), matrix(1, 2, 2))

b <- (a * b)^2
c <- b

c[1,3] <- 9 * 13
c[1,4] <- 19 * 11
c[1,5] <- 9 * 29
c[1,6] <- 19 * 4

c[2,3] <- 10 * 33
c[2,4] <- 24 * 18
c[2,5] <- 10 * 1
c[2,6] <- 24 * 3

.
.
.

c[6,1] <- 1 * 10
c[6,2] <- 3 * 24
c[6,3] <- 1 * 33
c[6,4] <- 3 * 18

Is there a flexible code to calculate this irrespective of the number of countries and industries within the data? I appreciate any help.
Edit: The matrices I am working with are large (with dimensions of over 2000 * 2000). I would need a code that can handle this kind of data without freezing R. Unfortunately, outer can solve the problem posed here for lower smaller matrices, but gets stuck when working with larger ones.

A: Assume that each country has equal number of industries, and dimnames(a) are sorted well like A1, A2...Am, B1, B2, ...Bm. This approach takes advantage of vectorized computation and avoids indexing the matrix with its dimnames, and hence improves the efficiency and saves memory considerably.

*

*m: number of industries

m <- 2
n <- nrow(a)
block <- matrix(a[kronecker(diag(n/m), matrix(1, m, m)) == 1], m)
block[rep(1:m, len = n), ] * c(block[, c(t(matrix(1:n, m)))])

#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]   81  361  117  209  261   76
# [2,]  100  576  330  432   10   72
# [3,]  117  209  169  121  377   44
# [4,]  330  432 1089  324   33   54
# [5,]  261   76  377   44  841   16
# [6,]   10   72   33   54    1    9

A: Something like this should perform well enough if your actual matrix a is n-by-n with n less than 10000. You can optimize further, especially if you know that dimnames(a) are sorted (see, e.g., @DarrenTsai's answer), but it's not clearly necessary.
n <- nrow(a)
nms <- rownames(a)

u <- unlist(strsplit(nms, " "))
country <- u[c(TRUE, FALSE)]
industry <- u[c(FALSE, TRUE)]

i1 <- seq_len(n)
j2 <- rep(i1, each = n)
j1 <- match(paste(country, industry[j2]), nms)
i2 <- match(paste(country[j2], industry), nms)

matrix(a[cbind(i1, j1)] * a[cbind(i2, j2)], n, n)

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   81  361  117  209  261   76
[2,]  100  576  330  432   10   72
[3,]  117  209  169  121  377   44
[4,]  330  432 1089  324   33   54
[5,]  261   76  377   44  841   16
[6,]   10   72   33   54    1    9

Of course, if dimnames(a) aren't sorted but you want to reap the benefits of sortedness, then you can permute the rows and columns of a, operate on the resulting block matrix, and inverse permute the rows and columns of the answer.
n <- nrow(a)
nms <- rownames(a)

## Number of industries, countries:
ni <- sum(startsWith(nms, substr(nms[1L], 1L, 3L)))
nc <- n %/% ni

p <- order(nms)
a.pp <- a[p, p] # permute

## Essentially @DarrenTsai's answer {uglier but highly optimized}:
k <- sequence(rep.int(ni, n), rep(seq.int(1L, n, ni), each = ni) + seq.int(0L, n * n - 1L, n))
b <- matrix(a.pp[k], ni, n)
r.pp <- b[rep.int(seq_len(ni), nc), ] * as.vector(b[, sequence(rep.int(nc, ni), seq_len(ni), ni)])

q <- p
q[q] <- seq_along(q)
r <- r.pp[q, q] # inverse permute

Actually, there is some neat matrix algebra here. Block [i,j] of r.pp is the elementwise product of blocks [i,i] and [j,j] of a.pp. Hence r.pp can be seen as a sort of block cross product of b, since b is the horizontal concatenation of the diagonal blocks of a.pp.

A: Another way sub-setting the original matrix to the needed sub-matrixes and multiplying them (GKi1).
x <- do.call(rbind, strsplit(rownames(a), " "))
x <- apply(outer(unique(x[,1]), unique(x[,2]), paste), 1,
           \(i) a[i, i], simplify = FALSE)
x <- do.call(rbind, lapply(x, \(y) do.call(cbind, lapply(x, `*`, y))))
rownames(x) <- colnames(x)
x
#      aaa 1 aaa 2 bbb 1 bbb 2 ccc 1 ccc 2
#aaa 1    81   361   117   209   261    76
#aaa 2   100   576   330   432    10    72
#bbb 1   117   209   169   121   377    44
#bbb 2   330   432  1089   324    33    54
#ccc 1   261    76   377    44   841    16
#ccc 2    10    72    33    54     1     9

x[rownames(a), colnames(a)] #In case the order of the original matrix is needed

A variant, extracting the relevant information of the original matrix in a different way - similar to the comment from @Mikael Jagan (Thanks!) could look like (GKi1B).
n <- nrow(a)
x <- do.call(rbind, strsplit(rownames(a), " ", TRUE))
x1 <- unique(x[,1])
x2 <- unique(x[,2])
n1 <- length(x1)
n2 <- length(x2)
A <- a[rep(match(t(outer(unique(x[,1]), unique(x[,2]), paste)), rownames(a)), each=n2) +
       sequence(rep.int(n2, n), sequence(rep.int(n2, n1), seq.int(0L, by=n*n2, length.out=n1), n-1L))]
do.call(rbind, lapply(seq.int(0, by=n2*n2, length.out=n1),
                      \(i) matrix(A * A[seq_len(n2*n2)+i], n2)) )
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   81  361  117  209  261   76
#[2,]  100  576  330  432   10   72
#[3,]  117  209  169  121  377   44
#[4,]  330  432 1089  324   33   54
#[5,]  261   76  377   44  841   16
#[6,]   10   72   33   54    1    9

Another way using outer but might also work with a larger matrix could be (GKi2).
n <- rownames(a)
i <- do.call(rbind, strsplit(n, " "))
j <- outer(i[,1], i[,2], paste)
array(a[cbind(n, c(j))] * a[cbind(c(t(j)), n[col(a)])], dim(a))
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   81  361  117  209  261   76
#[2,]  100  576  330  432   10   72
#[3,]  117  209  169  121  377   44
#[4,]  330  432 1089  324   33   54
#[5,]  261   76  377   44  841   16
#[6,]   10   72   33   54    1    9

Benchmark
set.seed(10)
a <- matrix(sample(1:100, 2002*2002, TRUE) , nrow = 2002)
colnames(a) <- rownames(a) <- paste( rep(strrep(letters, 3) , each = 77), 1:77)

bench::mark(check=FALSE,
ThomasIsCoding = {p <- expand.grid(rep(list(row.names(a)), 2))
p1 <- as.matrix(transform(p, Var2 = paste(sub("\\d+", "", Var1), sub("\\D+", "", Var2), sep = "")))
p2 <- as.matrix(transform(p, Var1 = paste(sub("\\d+", "", Var2), sub("\\D+", "", Var1), sep = "")))
`dim<-`(a[p1] * a[p2], dim(a))},
"Mikael Jagan" = {n <- nrow(a)
nms <- rownames(a)
u <- unlist(strsplit(nms, " "))
country <- u[c(TRUE, FALSE)]
industry <- u[c(FALSE, TRUE)]
i1 <- seq_len(n)
j2 <- rep(i1, each = n)
j1 <- match(paste(country, industry[j2]), nms)
i2 <- match(paste(country[j2], industry), nms)
matrix(a[cbind(i1, j1)] * a[cbind(i2, j2)], n, n)},
GKi2 = {n <- rownames(a)
i <- do.call(rbind, strsplit(n, " "))
j <- outer(i[,1], i[,2], paste)
array(a[cbind(n, c(j))] * a[cbind(c(t(j)), n[col(a)])], dim(a))},
"Mikael & Darren" = {n <- nrow(a)
nms <- rownames(a)
ni <- sum(startsWith(nms, substr(nms[1L], 1L, 3L)))
nc <- n %/% ni
p <- order(nms)
a.pp <- a[p, p] # permute
b <- matrix(a.pp[as.logical(kronecker(diag(nc), matrix(1, ni, ni)))], ni, n)
r.pp <- b[rep.int(seq_len(ni), nc), ] * as.vector(b[, sequence(rep.int(nc, ni), seq_len(ni), ni)])
q <- p
q[q] <- seq_along(q)
r.pp[q, q]},
GKi1 = {x <- do.call(rbind, strsplit(rownames(a), " "))
x <- apply(outer(sort(unique(x[,1])), sort(unique(x[,2])), paste), 1,
           \(i) a[i, i], simplify = FALSE)
x <- do.call(rbind, lapply(x, \(y) do.call(cbind, lapply(x, `*`, y))))
rownames(x) <- colnames(x)
x},
"Mikael & DarrenB" = {n <- nrow(a)
nms <- rownames(a)
ni <- sum(startsWith(nms, substr(nms[1L], 1L, 3L)))
nc <- n %/% ni
p <- order(nms)
a.pp <- a[p, p] # permute
b <- {k <- sequence(rep.int(ni, n), rep(seq.int(1L, n, ni), each = ni) + seq(0L, n * n - 1L, n)); matrix(a.pp[k], ni, n)}
r.pp <- b[rep.int(seq_len(ni), nc), ] * as.vector(b[, sequence(rep.int(nc, ni), seq_len(ni), ni)])
q <- p
q[q] <- seq_along(q)
r.pp[q, q]},
GKi1B = {n <- nrow(a)
x <- do.call(rbind, strsplit(rownames(a), " ", TRUE))
x1 <- unique(x[,1])
x2 <- unique(x[,2])
n1 <- length(x1)
n2 <- length(x2)
A <- a[rep(match(t(outer(unique(x[,1]), unique(x[,2]), paste)), rownames(a)), each=n2) +
       sequence(rep.int(n2, n), sequence(rep.int(n2, n1), seq.int(0L, by=n*n2, length.out=n1), n-1L))]
do.call(rbind, lapply(seq.int(0, by=n2*n2, length.out=n1),
                      \(i) matrix(A * A[seq_len(n2*n2)+i], n2))) }
)

Result
  expression            min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc
  <bch:expr>       <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>
1 ThomasIsCoding      1.24s    1.24s     0.810   872.1MB     4.05     1     5
2 Mikael Jagan     743.23ms 743.23ms     1.35    367.1MB     1.35     1     1
3 GKi2             812.95ms 812.95ms     1.23    734.1MB     4.92     1     4
4 Mikael & Darren   62.56ms  64.66ms    15.5     140.7MB     9.69     8     5
5 GKi1              28.72ms  29.57ms    33.3      48.8MB     7.83    17     4
6 Mikael & DarrenB  28.21ms  32.37ms    30.9      48.9MB     5.79    16     3
7 GKi1B              26.7ms   28.3ms    35.0      49.8MB     9.71    18     5

In this case Mikael & DarrenB, GKi1 and GKiB are the fastest and uses lowest amount of memory.

A: You can try the code below
> p <- expand.grid(rep(list(row.names(a)), 2))

> p1 <- as.matrix(transform(p, Var2 = paste(sub("\\d+", "", Var1), sub("\\D+", "", Var2), sep = "")))

> p2 <- as.matrix(transform(p, Var1 = paste(sub("\\d+", "", Var2), sub("\\D+", "", Var1), sep = "")))

> `dim<-`(a[p1] * a[p2], dim(a))
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   81  361  117  209  261   76
[2,]  100  576  330  432   10   72
[3,]  117  209  169  121  377   44
[4,]  330  432 1089  324   33   54
[5,]  261   76  377   44  841   16
[6,]   10   72   33   54    1    9


text:
Q: With continue chain, how to achieve absolute node positioning? My problem is that I want to draw several horizontal "layers" of nodes (implemented as chains), with connections between them.  When I try to position a node absolutely, it is additionally offset in the chain's direction:
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{chains}
\begin{document}
\begin{tikzpicture}[
  node distance=1,
  block/.style={
    on chain,
    inner sep=0pt,outer sep=0pt,
    draw,minimum height=10,minimum width=2}
]

\path[start chain=layer1]
  node[block] {}
  node[block,join] {}
  node[block,join] {}
;

\path[start chain=layer2]
  node[block,join=with layer1-3,below=of layer1-end] {}
  node[block,join] {}
  node[block,join] {}
;

%\path[start chain=layer1right] % WORKS
\path[continue chain=layer1]    % DOES NOT WORK, BUT WHY?
  node[block,join=with layer2-end,anchor=center] at (layer2-end |- layer1-end) {}
  node[block,join] {}
  node[block,join] {}
;

\end{tikzpicture}
\end{document}

I also tried variants like
node[block,join=with layer2-end placed {at=(layer2-end |- layer1-end)},anchor=center] {}

and I don't understand why I get the additional offset (I did find a workaround, see below).  According to the pgfmanual, I think this should've worked:

Independently of which form is used, the ⟨text⟩ inside ⟨direction⟩ that follows going or placed (separated by a compulsory space) can have two different effects:
(a) If it contains an equal sign, then this ⟨text⟩ is used as the placement rule, that is, it is simply executed.
(b) If it does not contain an equal sign, then ⟨text⟩=of \tikzchainprevious is used as the placement rule.
Note that in the first case, inside the ⟨text⟩ you have access to \tikzchainprevious and \tikzchaincount for doing your positioning calculations.

My workaround (see commented out code) is to start a new chain (which has the additional advantage that I could remove the anchor=center).  I cannot use above=of ..., because in my real code, the blocks have different heights, and the nodes on layer1 will not be aligned anymore.

A: If I understand question correctly, than you looking for something like this:

Code:
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{chains,positioning}

    \begin{document}
\begin{tikzpicture}[
  node distance=1,
  block/.style={
    on chain,
    inner sep=0pt,outer sep=0pt,
    draw,minimum height=10,minimum width=2}
                    ]
\path[start chain=layer1]
  node[block] {}
  node[block,join] {}
  node[block,join] {};
\path[start chain=layer2]
  node[block,join=with layer1-end,below=of layer1-end] {}
  node[block,join] {}
  node[block,join] {};
\path[continue chain=layer1]
  node[block,join=with layer2-end,above=of layer2-end] {}% <--
  node[block,join] {}
  node[block,join] {};
\end{tikzpicture}
    \end{document}

As you see, in continuation I use the same syntax as you for draw chain layer2. Options continue chain=... means that the chain will continue, where you indicate, in this case above of end node in chain2.
Main benefits to use of chains is relative positioning of nodes: next node in chain is always placed relatively to node before it.
Addendum:
From comments can be concluded, that you looking for nodes on the grid:

New MWE:
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{chains,positioning}

\begin{document}
\begin{tikzpicture}[
    on grid,
  node distance=2cm and 0.5 cm,
  block/.style={
    on chain,
    inner sep=0pt,outer sep=0pt,
    draw,minimum height=#1,minimum width=2}
                    ]
\path[start chain=layer1]
  node[block=1cm] {}
  node[block=2cm,join] {}
  node[block=1cm,join] {};
\path[start chain=layer2]
  node[block=1cm,join=with layer1-end,below=of layer1-end] {}
  node[block=1cm,join] {}
  node[block=1cm,join] {};
\path[continue chain=layer1]
  node[block=2cm,join=with layer2-end,above=of layer2-end] {}% <--
  node[block=1cm,join] {}
  node[block=1cm,join] {};
\end{tikzpicture}
\end{document}

A: I would:

*

*set up layer2 as a branch;

*add the precisely positioned node outside the chain;

*use \chainin to add that node into the chain before continuing with the remaining nodes.

For example:
\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{chains,scopes}
\begin{document}
\begin{tikzpicture}
  [
    node distance=1,
    basic block/.style={%
      inner sep=0pt,
      outer sep=0pt,
      draw,
      minimum height=10,
      minimum width=2,
    },
    block/.style={%
      basic block,
      on chain,
    },
    start chain=layer1,
  ]
  \path
  node [block] {}
  node [block,join,minimum height=20] {}
  node [block,join,minimum height=5] {}
  ;
  {[start branch=layer2 going below]
    \node [block,join,minimum height=20] {};
  }
  {[continue branch=layer2 going right]
    \path
    node [block,join] {}
    node [block,join,minimum height=30] {}
    ;
  }
  \node (a) [basic block] at (layer1/layer2-end |- layer1-3) {};
  [continue chain=layer1]
  \chainin (a) [join=with layer1/layer2-end];
  \path
  node [block,join,minimum height=20] {}
  node [block,join] {}
  ;
\end{tikzpicture}
\end{document}

Note that the chains implementation is a little ... eccentric ... at times. As I understand it, it is considered deprecated and, hence, very unlikely to get significant improvements.
[I think this is a shame because the idea has a pleasing simplicity and is more friendly to beginners than the functionality provided by the graphs syntax, which replaces it. The graphs syntax is, however, more flexible, powerful and concise.]


text:
Q: // Formatting java source comments -------------------------------- I use, and have seen used, a separator-comment in Java and C code along the lines of:
// fields used in configuration ---------------------------
int a = 0;
etc

// fields used for authentication process -----------------
String principalID = "";
etc

It helps with readability (IMO anyway) and refactoring.  I used-to use jalopy to extend the ---- to the end of the line, but it seems to have fallen by the wayside in recent years, and I can't find how to configure eclipse to do it.
Does anyone have a process or plugin they use (I'm using java so eclipse config would be ideal, but I'll use another tool if necessary), before I write a sed script to do it? (no sense re-inventing the wheel!).

A: I think this should do the trick :
Go to Eclipse's preferences --> Java --> Code Style --> Code Templates
Then, you should be able to configure the comments appearance as you wish


text:
Q: Min Max (Date Time) And Count Data Using SQL Server 2014
Example Table:
|   ID  |   Date_Time               |   ID_Plan |
|   1   |   2018-12-19 21:21:00.000 |   A1      |
|   2   |   2018-12-19 21:22:00.000 |   A1      |
|   3   |   2018-12-19 21:23:00.000 |   NULL    |
|   4   |   2018-12-19 21:24:00.000 |   NULL    |
|   5   |   2018-12-19 21:25:00.000 |   A2      |
|   6   |   2018-12-19 21:26:00.000 |   A2      |
|   7   |   2018-12-19 21:27:00.000 |   A2      |
|   8   |   2018-12-19 21:28:00.000 |   A3      |
|   9   |   2018-12-19 21:29:00.000 |   A3      |
|   10  |   2018-12-19 21:30:00.000 |   NULL    |
|   11  |   2018-12-19 21:31:00.000 |   NULL    |
|   12  |   2018-12-19 21:32:00.000 |   NULL    |
|   13  |   2018-12-19 21:33:00.000 |   A4      |
|   14  |   2018-12-19 21:34:00.000 |   A4      |
|   15  |   2018-12-19 21:35:00.000 |   A4      |
|   16  |   2018-12-20 21:36:00.000 |   NULL    |

IF OBJECT_ID('tempdb..#tb_CountFinal') IS NOT NULL
DROP TABLE #tb_CountFinal

CREATE TABLE #tb_CountFinal
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    Date_Time DATETIME,
    ID_Plan NVARCHAR(100)
)

INSERT INTO #tb_CountFinal
SELECT '12/19/2018 21:21','A1'union all
SELECT '12/19/2018 21:22','A1'union all
SELECT '12/19/2018 21:23',NULL union all
SELECT '12/19/2018 21:24',NULL union all
SELECT '12/19/2018 21:25','A2'union all
SELECT '12/19/2018 21:26','A2'union all
SELECT '12/19/2018 21:27','A2'union all
SELECT '12/19/2018 21:28','A3'union all
SELECT '12/19/2018 21:29','A3'union all
SELECT '12/19/2018 21:30',NULL union all
SELECT '12/19/2018 21:31',NULL union all
SELECT '12/19/2018 21:32',NULL union all
SELECT '12/19/2018 21:33','A4'union all
SELECT '12/19/2018 21:34','A4'union all
SELECT '12/19/2018 21:35','A4'union all
SELECT '12/20/2018 21:36',NULL

I'm interested in a query which would output rows similar to the following:
|   Start_Date          |       End_Date        |   Plan_ID     |   Count_PlantID   |
|   12/19/2018 21:21    |   12/19/2018 21:22    |   A1          |   2               |
|   12/19/2018 21:23    |   12/19/2018 21:24    |   NULL        |   2               |
|   12/19/2018 21:25    |   12/19/2018 21:27    |   A2          |   3               |
|   12/19/2018 21:28    |   12/19/2018 21:29    |   A3          |   2               |
|   12/19/2018 21:30    |   12/19/2018 21:32    |   NULL        |   3               |
|   12/19/2018 21:33    |   12/19/2018 21:35    |   A4          |   3               |
|   12/20/2018 21:36    |   12/20/2018 21:36    |   NULL        |   1               |

A: For each NULL entries I made a key by looking at the previous starting [ID] column, then performed the Group By on that new column. Try it.
select  min(Date_Time) as Start_Date, max(Date_Time) as End_Date
        , min(ID_Plan) as Plan_ID, count(1) as Count_PlanID
from    (
        select  s.*
                , case when ID_Plan is null
                    then
                        cast(
                                (
                                select  max([ID])
                                from    #tb_CountFinal as x
                                where x.ID < s.ID and ID_Plan is not null
                                ) as varchar(100)
                            )
                    else
                        ID_Plan
                    end as ID_Plan_Adv_Start
        from    #tb_CountFinal  as s
        ) as dt
group by dt.ID_Plan_Adv_Start
order by Start_Date


text:
Q: Incompatible Class Change Error: jaxrs-0.7 vs mail-1.0.1 I have a dependency resolution issue with another plugin, which is causing the following error:
Caused by: java.lang.IncompatibleClassChangeError
at grails.plugin.mail.MailMessageContentRenderer$RenderEnvironment.init(MailMessageContentRenderer.groovy:125)
at grails.plugin.mail.MailMessageContentRenderer$RenderEnvironment.with(MailMessageContentRenderer.groovy:158)
at grails.plugin.mail.MailMessageContentRenderer.render(MailMessageContentRenderer.groovy:47)
at grails.plugin.mail.MailMessageBuilder.doRender(MailMessageBuilder.groovy:235)
at grails.plugin.mail.MailMessageBuilder.html(MailMessageBuilder.groovy:253)

The way to recreate the error:
Install jaxrs 0.7 plugin and its dependencies in build config: spock 0.7 and org.springframework:spring-test:3.1.2.RELEASE
When I do run-app, since everything is loaded directly from resources, there is no error. However, doing a run-war, as dependencies are resolved I get the the above error.
The mail plugin depends on org.springframework:spring-test:3.1.0.RELEASE which gets kicked out. So, probably that is the reason.
Any suggestions on how to deal with this issue? I don't necessarily want to recompile the plugin separately as it becomes hard to maintain. I already tried a lot of combination in buildconfig for exclusion, but doesn't seem to work.
Thanks.


text:
Q: Removing string from within string I am trying to remove part of a string withing a string. for example if a string is "atgtga" i want the output to be "atg".
i tried using the .replace("tga","") method but my TA was saying that it only masks that part of the string instead of removing it.
i tried a new approach but i am still stuck on the if statement.
x="atgtgaacttaa"
c=0
q=3

while(q<=len(x)):
    x=x[c:q]

    if(x=="tga" or x=="taa" or x=="tag"):

       c=c+3
       q=q+3

print(x)

I tried making a new function but my output is ignoring "atg" for some reason and deleting it.
 def get_orf(dna_seq):
   x=0

   while(x<=len(dna_seq)):
     if("taa" in dna_seq or "tag" in dna_seq or "tga" in dna_seq ):
       dna_seq=dna_seq.replace("taa","")
       dna_seq=dna_seq.replace("tag","")
       dna_seq=dna_seq.replace("tga","")
       return dna_seq
     else:
      return dna_seq
     x=x+1

A: You can use replace, sometimes things do what they say on the tin:
>>> x = "atgtga"
>>> y = x.replace("tga", "")
>>> print(y)
atg

A: Your TA is incorrect.  replace returns a new string with the indicated change.  The original string is, indeed, still intact, but the new string is a separate entity, not part of the original, and not dependent on the original any more.


text:
Q: Мгновенная обработка ввода текста в JTextField Нужно, чтобы при вводе символа в JTextField мгновенно выполнялся код, замеряющий время ввода слова, важна каждая миллисекунда. Сейчас пытаюсь на главный JFrame повесить KeyListener, но думаю - это плохой способ, не синхронизированные потоки, все дела. Как можно узнать, что в поле ввели текст, как можно быстрее?

A: Нашёл решение, возможно не самое элегантное, но в моём случае сработало и полностью отвечает требованиям.
Создаём свой KeyListener содержащий интерфейс KeyListener:
private static class KListener implements KeyListener
{
    private String str = "";

    public void keyTyped(KeyEvent e) {}

    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE)
            {if (!str.equals("")) str = str.substring(0, str.length() - 1);}
        else if (code != KeyEvent.VK_SHIFT && code != KeyEvent.VK_ALT &&
                 code != KeyEvent.VK_CAPS_LOCK && code != KeyEvent.VK_CONTROL &&
                 code != KeyEvent.VK_ENTER && code != KeyEvent.VK_TAB &&
                 code != KeyEvent.VK_WINDOWS && code != KeyEvent.VK_CONTEXT_MENU)
                     str += e.getKeyChar();
    }

    public void keyReleased(KeyEvent e) {}
}

Если нажимаем Backspace, то стираем последний символ, иначе добавляем символ введённый с клавиатуры в текст, если, конечно, это не функциональная клавиша (все функциональные клавиши проверять не стал, ибо не было нужды, да и так получилось немаленькое нагромождение в коде).
Осталось на наш JTextField повесить KeyListener:
textField.addKeyListener(new KListener(this));

Всё, теперь в переменной str будет храниться текст, который содержится и в JTextField и его можно обработать с минимальной задержкой.

A: если хочешь обрабатывать текст при вставке, стоит поиграться с этим:
((AbstractDocument)textComponent.getDocument()).setDocumentFilter(new DocumentFilter(){
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
super.insertString(fb, offset, modifyString(string), attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
super.replace(fb, offset, length, modifyString(text), attrs);
}
});


text:
Q: Having Maven2 copy resources to the build directory, but NOT bundle them in the JAR I've started a new Maven project in NetBeans, accepting all the defaults.  The POM, with all the JAR dependencies stripped out, is cut-n-pasted at the bottom of this question.
The application reads in various properties files (e.g. logging and config).  It also reads in external resources such as fonts, images, and sounds.  I do NOT want all these resources to be bundled up into the JAR file.  Instead, I plan to deploy them in subdirectories beneath the directory where the JAR is deployed.
A simplified view of the project's directory structure looks like this:
-src
   |---main
           |---java
                   |---com.mypackage, etc
           |---resources
                        |---conf
                        |---fonts
                        |---images
                        |---sounds
+target

What I would like to have after a clean build would look like this:
+src
-target
       |---myproject-1.0.0.jar (compiled contents of "src/main/java" ONLY)
       |---conf
       |---fonts
       |---images
       |---sounds

However, when I do a "clean-and-build" or an "exec" through NetBeans (or the command-line for that matter)... what I'm actually getting looks like this:
+src
-target
       |---classes
                  |---("src/main/java" and "src/main/resources" slammed together)
       |---myproject-1.0.0.jar (the "classes" subdirectory JAR'ed up)

Can someone point me in the right direction for getting that first result rather than the second?  I apologize if this is a silly question (I'm a Maven rookie), or if I overlooked a previously-asked duplicate.  However, from the searching I've done on Stack Overflow... it looks like all the duplicate questions try to go the other way! (i.e. get resources into a JAR rather than keep them out)
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>steveperkins</groupId>
    <artifactId>myproject</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0</version>
    <name>My Project</name>
    <url>http://maven.apache.org</url>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.4</source>
                    <target>1.4</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
    ...

A: Personally, I would not use the default location of resources but an "extra" location and configure the resources plugin to copy them where you want from there:
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
          <execution>
            <id>copy-resources</id>
            <!-- here the phase you need -->
            <phase>validate</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <outputDirectory>${basedir}/target</outputDirectory>
              <resources>
                <resource>
                  <directory>src/non-packaged-resources</directory>
                  <filtering>true</filtering>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    ...
  </build>
  ...
</project>

If you insist with using the default location (src/main/resources), I think you'll have to configure some exclusions (see below) to avoid resources getting copied by default and then use the same approach as above.
Another option would be to use the AntRun maven plugin and Ant to move files but this is not really the maven way so I won't detail it.
Resources

*

*Copy Resources

*Including and excluding files and directories

A: Although the proposed solutions would work they basically work around the maven conventions.  A better alternative would be to filter out the resources so they are not included in the jar but still available as resources while working in the IDE.  In the pom it should look like this:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                    <configuration>
                        <excludes>
                            <exclude>/conf/**</exclude>
                            <exclude>/fonts/**</exclude>
                            <exclude>/images/**</exclude>
                            <exclude>/sounds/**</exclude>
                        </excludes>
                    </configuration>
                </execution>
            </executions>
        </plugin>
   </plugins>
</build>

This would effectively exclude them from the jar without any workarounds.
Here is the doc page for the jar plugin.
Though the above will answer your question may I suggest some additional possibility that could help you in your endeavour.  As a second step, to still make these resources available you could package your project using the assembly plugin.  this would allow you to create a zip file and place all the files, resources and jar, in an appropriate location so that when the zip is unpacked everything just falls into place.
If this project is part of a larger work you can still use the assembly plugin for each where you would have this situation and in the main project you could extract and reassemble them in a larger zip including all the necessary artifacts.
Lastly I suggest you leave the directory structure under target as-is.  If you customize it it would be preferable to do it through the Maven variables so that the changes percolate to the other plugins.  If you manually remove and rename stuff once Maven has gone through you may run into problems later.  Normally the Maven jar plugin should be able to just get it right if you configure it the way you want so you have no needs to worry about what comes under target.  Personally I use Eclipse and the pusign is pretty good at getting the IDE and Maven config in sync.  For NetBeans I would suspect this would also be the case.  If not the best approach would be to configure your project in NetBeans to use target/classes as a target folder for built artifacts and target/test-classes for stuff built from src/test/java.

A: You can sonfigure a special execution of resources:copy-resources goal.

A: Eugene is on the right track but there's a better way to make this work.
It should look something like this:
<build>
  <outputDirectory>target/${artifactId}-${version}</outputDirectory>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>2.3.1</version>
      <configuration>
        <classesDirectory>${project.build.outputDirectory}</classesDirectory>
        <outputDirector>target</outputDirectory>
      </configuration>
    </plugin>
  </plugins>
  <resources>
    <resource>
      <directory>src/main/resources/conf</directory>
      <targetPath>../conf</targetPath>
    </resource>
    <resource>
      <directory>src/main/resources/ANOTHER_PATH</directory>
      <targetPath>../ANOTHER_PATH</targetPath>
    </resource>
  </resources>
</build>

You won't be able to get rid of the 'classes' directory, but you'll be able to give it a different name that shouldn't interfere with NetBeans.
You can find more about the <outputDirectory> element here.
You can find more about the jar plugin here.
You can find more about the <resource> element here.
As a side note, you may want to consider running Maven under a 1.6 JDK and fork the maven-compiler-plugin to use your 1.4 JDK for compiling.  You can find out more about this here.  That should give you a boost to your compile time.  You can also tell surefire when running test cases to use the 1.4 JDK for execution as well.


text:
Q: WPF DataGrid Need Vertical Scrollbar in Grid Row My customer developing a property editor of sorts that contains multiple property sections that are presented as WPF Expanders with Datagrids contained within. We have everything laid out in a WPF Grid, currently with auto sized rows.
The problem we're trying to solve is proportional sizing of each property section when the screen height changes. When expanders are opened they should take up a proportional amount of space with vertical scrollbars kicking automatically when needed. When they are closed they should collapse and give the remaining space to the remaining sections.
In real life we have 4 expanders with content. The first one is a fixed height, the remaining three are Lists and DataGrids that need to size proportionally with the last one getting the largest portion of the remaining space. Keep in mind, users might resize the screen, or users might be running in different screen resolutions, so we need it to react accordingly.
We've tried messing with the DataGrid RowDefinition Height (fixed, proportional and auto) and MaxHeight, and also the MaxHeight of each datagrid, but I can't seem to find a combination that causes the whole area to be consumed when needed. We're researching a code based solution, but we're curious what others may suggest.
Here's a simple code sample that will give you the layout we're after. We just need it to work as described above.
Here's The Code (this would be a view model in real world)
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        datagrid1.DataContext = GetCustomerVM();
        datagrid2.DataContext = GetCustomerVM();
        datagrid3.DataContext = GetCustomerVM();
    }

    private List<Customer> GetCustomerVM()
    {
        var CustomerList = new List<Customer>();
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });
        CustomerList.Add(new Customer() { FirstName = "A" });

        return CustomerList;
    }
}

public class Customer
{
    public string FirstName { get; set; }
}

The XAML
<Window x:Class="StackOverflow_SidePanelGridScrolling.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflow_SidePanelGridScrolling"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow" Height="500" Width="300">

    <Window.Resources>

        <DataTemplate x:Key="ExpanderHeaderTemplate">
            <DockPanel Height="30">
                <TextBlock Margin="4,0,0,0"
                               VerticalAlignment="Center"
                               DockPanel.Dock="Left"
                               FontSize="16"
                               Text="{Binding}" />

            </DockPanel>
        </DataTemplate>

    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Expander x:Name="expander1" Grid.Row="0" Header="Area 1">

            <DataGrid Name="datagrid1"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander2" Grid.Row="1" Header="Area 2">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

        <Expander x:Name="expander3" Grid.Row="3" Header="Area 3">

            <DataGrid Name="datagrid2"
                      ItemsSource="{Binding}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="First Name"
                                        Binding="{Binding FirstName}"
                                        Width="100*" />
                </DataGrid.Columns>
            </DataGrid>

        </Expander>

    </Grid>
</Window>

A: As far as I'm able to understand your requirements, I think this does about what you want:

*

*Every expander, when not expanded, takes up whatever minimal space it requires.

*The top row, when expanded, is sized to its content.

*Rows two, three, and four divide up the remainder of the space. When expanded, they stretch. Two gets one share of the available space, Three gets two shares, Four gets three shares. If Two and Three are open, Two gets one of four shares and Three gets the other three.

Those shares are handed out by the * Height values in the setters in the triggers. Here's the trigger for Row Four:
<DataTrigger
    Binding="{Binding Children[3].IsExpanded, RelativeSource={RelativeSource AncestorType=Grid}}"
    Value="True"
    >
    <Setter Property="Height" Value="3*" />
</DataTrigger>

The nice thing about doing this in XAML is that it will never spring any ugly surprises on you.
So here's the XAML:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition>
            <RowDefinition.Style>

                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>

                </Style>
            </RowDefinition.Style>
        </RowDefinition>
        <RowDefinition>
            <RowDefinition.Style>

                </Style>
            </RowDefinition.Style>
        </RowDefinition>
    </Grid.RowDefinitions>
    <Expander
        Grid.Row="0"
        VerticalAlignment="Stretch"
        Header="One" Background="LightGreen">
        <StackPanel>
            Content One
            Content One
            Content One
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="1"
        VerticalAlignment="Stretch"
        Header="Two" Background="LightSkyBlue">
        <StackPanel>
            Content Two
            Content Two
            Content Two
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="2"
        VerticalAlignment="Stretch"
        Header="Three" Background="LightGoldenrodYellow">
        <StackPanel>
            Content Three
            Content Three
            Content Three
        </StackPanel>
    </Expander>
    <Expander
        Grid.Row="3"
        VerticalAlignment="Stretch"
        Header="Four" Background="Khaki">
        <StackPanel>
            Content Four
            Content Four
            Content Four
        </StackPanel>
    </Expander>
</Grid>

These don't show scrollbars because I didn't take the time to create content that will scroll.


text:
Q: linking two C Programs I'm combining two C programs using a header file.
first program
#include<explore.h>

int main()
{
    int a =10;
    explore();
}

explore program
#include<stdio.h>

int explore()
{
    // I want to use the value of a. Can I use it? How can sue it?
}

I want to use the value of a in explore() in explore program file.
Can I use it? How can use it, is possible?

A: Ok, first off. With the code as it stands now, you won't be able to use the int a anywhere, except in the main function, since it's a local variable to that function.
Either pass it as an argument, or declare it as a global (and an extern for that matter). Either way, I'd opt to pass it as an argument, if a will be changed by the function explore, you can do 1 of 2 things:
int explore( int val)
{
    //do stuff
    return new_val;
}
//call:
a = explore(a);//assigns return int to a

Or, if the returned int signals a status of some kind, pass a pointer to a. This may, if you're new to pointers, seem like a sure way to over-complicate things, but it's very common, and very useful (added note on why this is useful to the bottom):
int explore(int *val)
{
    *val += 123;//add 123 to val's value
    //this is NOT the same as val += 123, because that's shifting the pointer!
    return 0;
}
//call:
int return_val = explore(&a);//pass &[address-of]a

Now, linking two source files is easy, but you say you're using a header file, all well and good, but you don't seem to be including it anywhere, nor are you showing what it looks like. I suspect you're having trouble compiling your code... if so, show us what you've tried (how you're compiling the code), and what errors you're getting.
If you need a basic example of how to manually link 2 source files: Here's a previous answer of mine that shows, step by step, how to link 2 files
Why pointers?:
Many reasons, really. Here's just a few:

*

*limit memory usage: If you're passing big structs by value all over the place (ie, copying the same data over and over), your code will be slow, and your stack might end up cluttered with the same value. (recursion induced stack overflow)

*C can allocate heap memory, which can only be accessed through pointers, you can't turn a pointer variable into a non-pointer.

*Return values are often ways to notify you of an error that may have occurred.

The last point is crucial. If you're passing a to explore for some complex computation, changing the value of a along the way. If, half way down the function, something goes pear-shaped, how do you notify the caller that the value of a is no longer reliable? Simple:
int complex_function( int *val)
{
    _Bool negative = *val > 0 ? false : true;
    //do all sorts of magic stuff
    //val wasn't negative, but is now, possible maxed int?
    if (negative == false && *val < 0) return -1;//notify using -1
    return 0;//usually, 0 means everything went well ok
}
//call like so:
if ((complex_function(&a)) != 0) exit( EXIT_FAILURE);//it's all gone wrong
//else, continue

Now that's where pointers are very useful. It doesn't require you to mess about with all too many temp variables, creating copies of values all over the place, and compare those to get to the same conclusion.

A: Call explore with a as parameter.
Nevertheless, you don't really seem to have two "programs". You have two source files in one program. So another way to use a in both parts could be to define a in main.c and declare it as "extern" in explore.h. Keep in mind, though, that a is somewhat "global" to your program then.

A: just pass the value (or pointer) of a to your explore function
pass by value (a copy of a)
#include<stdio.h>
int explore(int value)
{

}

pass by reference (the pointer pointing at a)
#include<stdio.h>
int explore(int *value)
{

}

A: Change to int explore(int some_var) and then you are free to use some_var inside this function. In main you need to call as explore(a).

A: First of all, they are not two programs. It's a single program. You are writing a function. If you want to pass the value of a to that function, you need to pass it as a parameter:
#include<explore.h>
int main()
{
  int a =10;
  explore(a);
}

#include<stdio.h>
int explore(int a)
{
  // you can now use a here
}


text:
Q: Export Package [Eclipse] I am just wondering how do I export a .deb package for Ubuntu Software Centre in Eclipse? I have created an application that runs Python and Webkit now I wish to submit to the Software centre. How do I export a .deb file?

A: I'm not aware of any Debian package integration for Eclipse.
I suggest you read the packaging guide.
If you have a working setup.py then packaging Python is fairly simple.


text:
Q: previous data losted when click on add button in GirdView in Asp.Net i am working on Asp.Net with C#-4.0 .
I want to get Input from end user in a GridView. Like

in DropDownList or in TextBox i enters some value and clicks on Add then new record will add but previous data was lost.

the Problem is when i change value of controls, it not saves in DataTable to which it is binded. How can i save this value to DataTable. What code i have missed here  ?
designer code :
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SaleOrder.aspx.cs" Inherits="Transactions_SaleOrder" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FormHeader" Runat="Server">

Sale Order

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="FormBody" Runat="Server">

                <asp:Label ID="lblDate" runat="server" Text="Date : "></asp:Label>
<asp:TextBox ID="txtSODate" runat="server"></asp:TextBox>
                <asp:CalendarExtender ID="txtSODate_CalendarExtender" runat="server"
                    Enabled="True" TargetControlID="txtSODate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
                </asp:CalendarExtender>
                <asp:MaskedEditExtender ID="txtSODate_MaskedEditExtender" runat="server"
                Enabled="True" Mask="99/99/9999" MaskType="Date" TargetControlID="txtSODate">
                </asp:MaskedEditExtender>
                <asp:ImageButton ID="ImageButton1" runat="server"
                    ImageUrl="~/images/Calendar_scheduleHS.png" />

                Shift :
                <asp:DropDownList ID="DropDownList1" runat="server" Width="300px">
                    <asp:ListItem Value="Morning">MORNING</asp:ListItem>
                    <asp:ListItem Value="EVENING"></asp:ListItem>
                    <asp:ListItem Value="OTHERS"></asp:ListItem>
                </asp:DropDownList>

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    CellPadding="4" ForeColor="#333333" GridLines="None"
                    onrowcommand="GridView1_RowCommand">
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                    <Columns>
                        <asp:TemplateField HeaderText="Product">
                            <ItemTemplate>
                                <asp:DropDownList ID="ddlProduct" runat="server" Width="300"
                                DataSource='<%# dtProductMaster %>'
                                DataTextField="PDescr"
                                DataValueField="PID"
                                >
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Qty">
                            <ItemTemplate>
                                <asp:TextBox ID="txtQuan" runat="server" MaxLength="5" style="text-align:right" Text='<%# BIND("QUAN") %>'></asp:TextBox>
                                <asp:MaskedEditExtender ID="txtQuan_MaskedEditExtender" runat="server" Enabled="True"
                                    Mask="99999" TargetControlID="txtQuan">
                                </asp:MaskedEditExtender>
                            </ItemTemplate>
                            <ItemStyle HorizontalAlign="Right" />
                        </asp:TemplateField>
                        <asp:ButtonField CommandName="ADD" Text="Add" />
                        <asp:ButtonField CommandName="DELETE" Text="Delete" />
                    </Columns>
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>

                <asp:Button ID="btnSave" runat="server" Text="Save" Width="58px" />

</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="FormFooter" Runat="Server">
</asp:Content>

C# Code behind it :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Transactions_SaleOrder : System.Web.UI.Page
{
    internal DataTable dtProductMaster_;
    internal DataTable dtProductMaster
    {
        get
        {
            if (dtProductMaster_ == null)
            {
                clsData d = new clsData();
                d.Select("select PID, PEDESCR2 + ' ' + PEDESCR3 as PDescr From TBLPROD_MAST");
                dtProductMaster_ = d.DataTable;
            }
            return dtProductMaster_;
        }
    }
    DataTable dtProductDet
    {
        get
        {
            if (ViewState["dtProductDet"] != null)
            {
                return (DataTable)ViewState["dtProductDet"];
            }
            else
            {
                return null;
            }
        }
        set
        {
            ViewState["dtProductDet"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
            //--
            dtProductDet = new DataTable("dtProductDet");
            dtProductDet.Columns.Add("PID", typeof(int));
            dtProductDet.Columns.Add("PName", typeof(string));
            dtProductDet.Columns.Add("Quan", typeof(decimal));
            dtProductDet.Rows.Add(0,"",0);
            //--
        }
        GridView1.DataSource = dtProductDet;
        GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName.ToUpper())
        {
            case "ADD":
                dtProductDet.Rows.Add(0, "", 0);
                break;
            case "DELETE":
                dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
                break;
        }
    }
}

how can i achieve my aim.

A: The answer has already been given in previous comments. To spell it out...
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
        //--
        dtProductDet = new DataTable("dtProductDet");
        dtProductDet.Columns.Add("PID", typeof(int));
        dtProductDet.Columns.Add("PName", typeof(string));
        dtProductDet.Columns.Add("Quan", typeof(decimal));
        dtProductDet.Rows.Add(0,"",0);
        //--
        GridView1.DataSource = dtProductDet;
        GridView1.DataBind();
    }
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    switch (e.CommandName.ToUpper())
    {
        case "ADD":
            dtProductDet.Rows.Add(0, "", 0);
            break;
        case "DELETE":
            dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
            break;
    }
    GridView1.DataBind();
}

A: I have got the solution.
The problem is, when i am editing value in DropDownList or in TextBox, its value is not saving back to DataTable which is bind with GridView and TextBox and DropDownList.
There is no automatic way to do this, so we have to write manual code to save values back to DataTable.
When i asked the question add button was in GridViewColumn and it was command Column, now i have added a button in GridView Footer.
So when i click on "Add new row" button, page is posted back, at first page load event fires and then Button_Click event fires. I have add code on Page.Load event, if page is posted back then pick data from GridView and Save it to DataTable.
Nextly Button_click event fires, so a new row adds in DataTable and DataTable will assign in DataSource of GridView and DataBind method executes and re-generates GridView.
I have a DropDownList which is also bind to a different DataTable other than GridView, so that after DataBind() i have to select manually value in DropDownList as per saved in DataTable of GridView.
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
        //--
        dtProductDet = new DataTable("dtProductDet");
        dtProductDet.Columns.Add("PID", typeof(int));
        dtProductDet.Columns.Add("PName", typeof(string));
        dtProductDet.Columns.Add("Quan", typeof(decimal));
        dtProductDet.Rows.Add(0,"",0);
        //--
        SetGridViewSource();
    }
    else
    {
        DataTable dtPD = dtProductDet;
        DropDownList ddlProd = null;
        if (GridView1.Rows.Count > 0)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
                dtPD.Rows[i]["PID"] = Convert.ToInt32(ddlProd.SelectedItem.Value);
                dtPD.Rows[i]["PName"] = ddlProd.SelectedItem.Text;
                dtPD.Rows[i]["QUAN"] = ((TextBox)GridView1.Rows[i].Cells[gvci_Quan].FindControl("txtQuan")).Text;
            }
        }
        dtProductDet = dtPD;
    }
}

protected void btnAdd_Click(object sender, EventArgs e)
{
    dtProductDet.Rows.Add(0, "", 0);

    DataTable dtPDet = dtProductDet;
    GridView1.DataSource = dtPDet;
    GridView1.DataBind();

    DropDownList ddlProd = null;
    DataRow drFind = null;
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
        drFind = dtProductMaster.Rows.Find(dtPDet.Rows[i]["PID"]);
        if(drFind != null)
        {
            ddlProd.SelectedIndex = dtProductMaster.Rows.IndexOf(drFind);
        }
    }

}


text: Q: Android:send sms through internet without using native services I am making an app in which i am have to send sms to another device using internet but i donot want to use phone native means i donot want to pay for sms i.e. i want to use internet to send messages .Is their any other way than sending xml to server and if used xml then how to maintain session. Can anyone help me .Any help will be appreciated.


text:
Q: JavaFX - CSS styling listview I have a ListView and want the following:

*

*Odd rows with white background color;

*ListView: when mouse over an item, highlight with a blue shade;

*ListView: when an item is selected, paint it with a gradient;

*ListView: when focus is lost from ListView, selected item should be painted with gradient;

*ListView: all items will start with text-fill black. But on mouse over and/or selected it will change to white.

That's my code. It's working fine, except for the even rows: on mouse over, it highlight in white. So, the text's white and can't be showed. What's wrong with it?
.list-cell:filled:selected:focused, .list-cell:filled:selected {
    -fx-background-color: linear-gradient(#328BDB 0%, #207BCF 25%, #1973C9 75%, #0A65BF 100%);
    -fx-text-fill: white;
}

.list-cell:odd {
    -fx-cell-hover-color: #0093ff;
    -fx-background-color: white;
}

.list-cell:filled:hover {
    -fx-cell-hover-color: #0093ff;
    -fx-text-fill: white;
}

Thanks in advance.

A: EDIT:
Slightly changing your css:
.list-cell:filled:selected:focused, .list-cell:filled:selected {
    -fx-background-color: linear-gradient(#328BDB 0%, #207BCF 25%, #1973C9 75%, #0A65BF 100%);
    -fx-text-fill: white;
}

.list-cell:even { /* <=== changed to even */
    -fx-background-color: white;
}

.list-cell:filled:hover {
    -fx-background-color: #0093ff;
    -fx-text-fill: white;
}

This css produces the following presentation:

Does this give what you expect?
I changed odd to even. The first cell is even, because its index value is 0 (zero). Also -fx-cell-hover-color is not valid. I changed it to -fx-background-color where needed or removed it.

Original text: (note that this has different interpretation of odd/even)
My take would be this:
(I included your requirements in a numbered list for reference in the css. I also made the gradient more obvious and added a green background for even cells.)
/*
1. Odd rows with white background color;
2. ListView: when mouse over an item, highlight with a blue shade;
3. ListView: when an item is selected, paint it with a gradient;
4. ListView: when focus is lost from ListView, selected item should be painted with gradient;
5. ListView: all items will start with text-fill black. But on mouse over and/or selected it will change to white.
*/

.list-cell:filled:selected:focused, .list-cell:filled:selected {
    /* 3:, 4: */
    -fx-background-color: linear-gradient(#333 0%, #777 25%, #aaa 75%, #eee 100%);
    -fx-text-fill: white; /* 5 */
}
.list-cell { -fx-text-fill: black; /* 5 */ }
.list-cell:odd { -fx-background-color: white; /* 1 */ }
.list-cell:even { -fx-background-color: #8f8; /* for information */ }
.list-cell:filled:hover {
    -fx-background-color: #00f; /* 2 */
    -fx-text-fill: white; /* 5 */
}

This leads to this rendering:


text:
Q: Adding elements to cyclic Single Linked Lists I am trying to add an element to the end of a cyclic Single Linked List for my homework
assignment. But for some reason I am having a lot of problems.
I have a _tail pointer, and _dummy. The add method in JUnit test says that when checking the add method it returns null instead of 1. (1 being what was added to list)
Here is my code
 private static class Node<T>{
    Node<T> next;
    T data;
    public Node(T data, Node<T> next){
        this.next = next;
        this.data = data;
    }
}

private Node<T> _tail;
private int _count;
private int _version;
private Node<T> _dummy;

 public CyclicLinkedList(){
    _dummy = new Node<T>(null, null);
    _dummy.next = _dummy;
    _tail = _dummy;
    _count = 0;
    assert _wellFormed();
}

and here is my add method
@Override
public boolean add(T x){
    assert _wellFormed();

    Node<T> n = new Node<T>(x, _tail.next);
    _tail.next = n;
    _tail = n;

    ++_version;
    ++_count;

    assert _wellFormed();
    return true;
}

The assertWellformed states that the linked list is wrongly cyclic. The _wellFormed() method has already been implemented by the class instructor so that is not the problem. Need some pointers! Thanks. Here is the test to see if the test is wrongly cyclic.
 // check for cycles:
    Node<T> fast = _tail.next;
    for (Node<T> p = _tail; fast != null && fast.next != null && fast != _tail       && fast.next != _tail; p = p.next) {
        if (p == fast) return _report("list is wrongly cyclic");
        fast = fast.next.next;
    }

A: _tail.next = n;
    _tail = n;

You should add one more line at the start of that code in add method:-
n.next = _tail.next;

So, your code becomes: -
n.next = _tail.next;
_tail.next = n;
_tail = n;

You need to make your new node point to the first node, to make it cyclic.
And since, _tail.next I assume must be pointing to the first element, before adding a new node to the List, so assign _tail.next to n.next before adding it to the list to make n also now point to the first node.
So, at the first line, both your nodes: - n node and _tail node, point to the first node. Now, detach your _tail node from first node, and make it point to the n node. And at last, make your n node as _tail node.


text:
Q: Terraform Serverless Applications with AWS Lambda and API Gateway unknown token? I'm learning terraform, and one of the well written tutorials on hashicorp has given me some problems towards the end.
I have a file defining my lambda, and its relationship to an API Gateway.  The connections to the API Gateway haven't been tested, since I can't seem to get the API Gateway to deploy.
lambda.tf

provider "aws" {
    region = "us-east-1"
    shared_credentials_file = "/home/camelType/.aws/credentials"
    profile = "default"
}

resource "aws_lambda_function" "example" {
    function_name = "ServerlessExample"

   # The bucket name as created earlier with "aws s3api create-bucket"
    s3_bucket = "camelType-serverless-example"
    s3_key    = "v1.0.0/example.zip"

   # "main" is the filename within the zip file (main.js) and "handler"
   # is the name of the property under which the handler function was
   # exported in that file.
    handler = "main.handler"
    runtime = "nodejs12.x"

    role = "${aws_iam_role.lambda_exec_role.arn}"
}

resource "aws_iam_role" "lambda_exec_role" {
    name = "lambda_exec_role"
    assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "sts:AssumeRole",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
            "Effect": "Allow",
            "Sid": ""
        }
    ]
}
EOF
}

//Haven't tested below here

resource "aws_api_gateway_resource" "proxy" {
   rest_api_id = aws_api_gateway_rest_api.example.id
   parent_id   = aws_api_gateway_rest_api.example.root_resource_id
   path_part   = "{proxy+}"
}

resource "aws_api_gateway_method" "proxy" {
   rest_api_id   = aws_api_gateway_rest_api.example.id
   resource_id   = aws_api_gateway_resource.proxy.id
   http_method   = "ANY"
   authorization = "NONE"
}

I've deployed the lambda alone, and it worked as expected.
However, when I went to the next step, and added the api gateway, I get a parsing error for the aws_api_gateway_rest_api.example.id.  I assumed that the example.id was a reference to the aws_api_gateway_rest_api resource above, so the example.id name is correct, but that's the line it's having trouble parsing.
api_gateway.tf
resource "aws_api_gateway_rest_api" "example" {
    name        = "ServerlessExample"
    description = "Terraform Serverless Application Example"
}

resource "aws_api_gateway_integration" "lambda" {
    //issue here
    rest_api_id = aws_api_gateway_rest_api.example.id
    resource_id = aws_api_gateway_method.proxy.resource_id
    http_method = aws_api_gateway_method.proxy.http_method

    integration_http_method = "POST"
    type                    = "AWS_PROXY"
    uri                     = aws_lambda_function.example.invoke_arn
}

resource "aws_api_gateway_method" "proxy_root" {
    rest_api_id   = aws_api_gateway_rest_api.example.id
    resource_id   = aws_api_gateway_rest_api.example.root_resource_id
    http_method   = "ANY"
    authorization = "NONE"
}

resource "aws_api_gateway_integration" "lambda_root" {
    rest_api_id = aws_api_gateway_rest_api.example.id
    resource_id = aws_api_gateway_method.proxy_root.resource_id
    http_method = aws_api_gateway_method.proxy_root.http_method

    integration_http_method = "POST"
    type                    = "AWS_PROXY"
    uri                     = aws_lambda_function.example.invoke_arn
}

resource "aws_api_gateway_deployment" "example" {
    depends_on = [
    aws_api_gateway_integration.lambda,
    aws_api_gateway_integration.lambda_root,
   ]

    rest_api_id = aws_api_gateway_rest_api.example.id
    stage_name  = "test"
}

I've gone through a few of their tutorials, and this is the first one I've had issues with.  I'm sure it's my error, but I've gone over it several times, and can't seem to figure out what I'm doing wrong.
The copy paste of the error message is Error: Error parsing /home/camelType/api_gateway.tf: At 7:18: Unknown token: 7:18 IDENT aws_api_gateway_rest_api.example.id

A: Based on the comments.
The issue was caused by using old version of terraform (v0.11.11), while using syntax from newer version in the config files.
Similar issues have been reported:

*

*Unknown token: 2:23 IDENT max

*Unknown token IDENT aws_region
The solution was to upgrade terraform.


text:
Q: Using extrn prinf:near in MASM Hello have a MASM assembly question. In the code below:
What is- extrn printf:near
It is refering to prinf function being called externally but what does the :near signify?

    ; include C libraries
includelib      msvcrtd
includelib      oldnames
includelib      legacy_stdio_definitions.lib    ;for scanf, printf, ...

.data
    prompt  db "Enter a number: ", 0
    fmt     db "%i", 0
    input   sdword ?
    output  byte 'z' ; initialize to 'z' as default

.code
    extrn   printf:near
    extrn   scanf:near

public  main
main    proc

    push    offset prompt
    call    printf
    add     sp,4

    ; get input with scanf
    push    offset input
    push    offset fmt
    call    scanf
    add     sp, 8

    cmp     input, 0
    je      LOUTPUT
    jg      LPOS
    jng     LNEG

LPOS:
    mov output, 'p'
    jmp LOUTPUT

LNEG:
    mov output, 'n'
    jmp LOUTPUT

LOUTPUT:
    push offset output
    call printf
    add  sp, 4

    ret
main    endp

end


text:
Q: TimeLineCollectionViewController.allProd.count всегда равен нулю. Из-за асинхронности, видимо. Как решить проблему с опозданием получения данных? static func creatUserTimeLineProducts(completion: @escaping ([Product]) -> ()) {
        Firestore.firestore()
        //        получаем список Магазинов
            .collection("stores")
            .getDocuments { stores, error in
                print("Магазинов: \(stores!.count)")
                //                проходим по всем Магазинам
                for store in stores!.documents {
                    let storeRef = store.reference
                    //                    заходим в Продукты
                    storeRef.collection("products")
                        .getDocuments { products, error in
                            print("Продуктов: \(products!.count)")
                            //                            получаем все Продукты
                            let prods = products?.documents.compactMap({ Product(productDict: $0.data() )})
                            for prod in prods! {
                                FBDataBase.allProdArray.append(prod)
                            }
                            completion(FBDataBase.allProdArray)

                        }
                }
            }
    }

    func loadind() {
    FBDataBase.creatUserTimeLineProducts { all in
        TimeLineCollectionViewController.allProd = all
    }
    TimeLineCollectionViewController.allProd = FBDataBase.allProdArray
    print("Количество Айтемс Покупатели loading: \(TimeLineCollectionViewController.allProd.count)")

}

override func loadView() {
    super.loadView()
        switch AuthAccaunt.authProfile {
        case .store:
            FBDataBase.creatDB { prodArray in
                TimeLineCollectionViewController.prodArray = prodArray
            }

        case .user:
            loadind()


text:
Q: Middleware, how to redirect after check Laravel 5 I need after check if user is logged as editor, to redirect to profile page...
Here is my code:
<?php namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

use Closure;

class AdminMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            if (Auth::user()->roles->toArray()[0]['role'] == 'editor'){
                return redirect('/profile');
            }
                return $next($request);
            }
            else {
                return $next($request);
            }
        }
    }

Problem with this code is when user is editor I get infinite loop....
Here is my routs:
Route::group(['middleware' => 'auth'], function(){

    Route::get('home', ['middleware' => 'admin', function()
        {
        return view('home');
        }]);
    Route::get('profile', array(
       'as' => 'profile',
       'uses' => 'UserController@getProfile'
    ));

});

Anyone know what is problem?

A: Where did you register your middleware in App\Http\Kernel?
Is it in protected $middleware = [] or protected $routeMiddleware = [] ?
If registered in $middleware it will run on each very request thereby causing infinite loop, if so use only $routeMiddleware

A: I found this to be a less code and less decisions for redirecting users based on roles, Put this in your AuthController.php
protected function authenticated( $user)
{

    if($user->user_group == '0') {
        return redirect('/dashboard');
    }

    return redirect('my-account');
}

https://laracasts.com/discuss/channels/laravel/how-best-to-redirect-admins-from-users-after-login-authentication

A: Go to Kernel.php. It's in app\http.
Try to find  protected $routeMiddleware
in that array you need to add this
'admin' => \App\Http\Middleware\AdminMiddleware::class

After that it should work fine.
Hope this helps anyone who faces the same problem.


text:
Q: Why time cost is 0 seconds after call std::async? See the following code.
#include <future>
#include <iostream>
#include <ctime>

int main()
{
    std::future<int> future = std::async(std::launch::deferred, [](){
            std::this_thread::sleep_for(std::chrono::seconds(5));
            return 100;
        });
    std::cout << "waiting...\n";

    clock_t start = clock();
    std::future_status status = future.wait_for(std::chrono::seconds(20));
    std::cout << "result is " << future.get() << std::endl;
    clock_t end = clock();
    std::cout<<"Time Cost : "<< (double)(end-start)/CLOCKS_PER_SEC <<" seconds."<< std::endl;
}

It's very confusing about the execution result. Yep, the main thread will wait for only 5 seconds around and then print "100". But why "Time Cost" shows 0? The test environment is Cygwin with g++ 4.9.3.
Then I tested it in VS2013. The result is 25 seocnds. Strange!

A: It doesn't show 0 on my machine but a very small value : 0;000156s. But as it measures processor time and your main thread does not consume any cpu (wait is not an active loop), the result is almost 0.

A: clock() returns processor time spent. It doesn't have any guarantee of advancement whatsoever. If your CPU sleeps, the value returned by it will not be advanced. To measure intervals properly, use clocks from std::chrono, for example, std::chrono::steady_clock.


text:
Q: Google Sitemaps Puzzle I'm trying to submit a sitemap for a web site to Google Webtools but I'm getting a very strange error related to the domain name. First of all, I submitted the sitemap as an RSS document which I believe is valid (Check here).
I have two issues. A minor one is that the response carries the header "Content-Type: application/rss+xml; charset=utf-8" but Webtool displays a "Type: ?" message.

Second, and most important, is that Web Tool returns an error with the message "
General HTTP error: Domain name not found". However, I am able to resolve the domain name (http://vlab.mooo.info) and the name has been registered months ago, so there shouldn't be a DNS problem.
$ resolveip vlab.mooo.info
IP address of vlab.mooo.info is X.Y.Z.W

I can't really reach a conclusion: Is there some DNS issue I can't identify? Is there some problem with the syntax of my RSS document? Or something else?
Update 1: I did something even simpler! I uploaded a simplistic sitemap.xml file on http://vlab.mooo.info/sitemap.xml. The result is exactly the same. Webtool claims that the domain name cannot be found :S
Update 2: Here is yet another error I get from the web crawler:

A: Upload a robots.txt with the following:
User-agent: *
Disallow:

And let the google webmaster tools open it, lets see if it can access that file.
Does your google-analytics account work without any issues?
Normally when adding a new domain to google webmaster tools it cant take up to 48 hours to fully work.
Oh and your feed isn't totally valid.
Remember the w3c services, also for feeds :) http://validator.w3.org/feed/
http://validator.w3.org/feed/check.cgi?url=http%3A%2F%2Fvlab.mooo.info%2Frss%2Ffeed%2F


text:
Q: How to add in a read object to an ArrayList and print out user requested info For class, we have to read in a CSV file that has states, their abbreviations, and population and add the objects to an array list. then we have to print out the list in a tabular format. From there we have to ask the user what abbreviation they are looking for and print the abbreviation, state, and population out.
I have already tried adding the objects to an array list how my professor showed me and it broke the whole program. From what I have it set up as now is the closest thing that i've gotten to from the assignment description. We have never used array lists before so you'll have to forgive me if im missing something obvious. I have tried adding for loops in different places to see if it would work and it has not so far. Im lost on how to find specific items in the data and pull them out also.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

class Reader {
    public static void main(String[] args) {
        String abbreviation = "";
        String nameOfState = "";
        int population = 0;

        Scanner inFile = null;

        // open file
        try {
            inFile = new Scanner(new File("States.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error: File not found");
        }

        // read file
        System.out.printf("%-12s %5s %5s\n", "Abbreviation", "State Name",
                "Pop");
        System.out.printf("%-12s %5s %5s\n", "------------", "----------",
                "---");
        while (inFile.hasNext()) {
            String record = inFile.nextLine();        // read up to new line
            String[] tokens = record.split(",[ ]*");

            abbreviation = tokens[0];
            nameOfState = tokens[1];
            population = Integer.parseInt(tokens[2]);

            System.out.printf("%-12s %5s %12d\n", abbreviation, nameOfState,
                    population);

        }
        Scanner in = new Scanner(System.in);
        System.out.println("Which state would you like to find?");
        String question = in.nextLine();
        for (int i = 0; i < abbreviation.length(); i++) {

            if (question.equalsIgnoreCase(abbreviation)) {

            } else {
                System.out.println("Incorrect formating");
            }

        }
        inFile.close();

    }
}

--
public class States {
    private String abbreviation;
    private String nameOfState;
    private int population;

    public States(String abbreviation, String nameOfState, int population) {
        super();
        this.abbreviation = abbreviation;
        this.nameOfState = nameOfState;
        this.population = population;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public String getNameOfState() {
        return nameOfState;
    }

    public int getPopulation() {
        return population;
    }
}

A: First let's cal the class State and not States it has no sense
Then you need to

*

*declare a new array list List<State> stateList = new ArrayList<>();

*for each line create a State instance, and add it to the list

List<State> stateList = new ArrayList<>();
while (inFile.hasNext()) {
    String record = inFile.nextLine();        // read up to new line
    String[] tokens = record.split(",[ ]*");

    String abbreviation = tokens[0];
    String nameOfState = tokens[1];
    int population = Integer.parseInt(tokens[2]);

    stateList.add(new State(abbreviation, nameOfState, population));
}

Then iterate over each State in the list, and if the abbrevation matches the user input : print it
Scanner in = new Scanner(System.in);
System.out.println("Which state would you like to find?");
String question = in.nextLine();
for (State state : stateList) {
    if (question.equalsIgnoreCase(state.getAbbreviation())) {
        System.out.println(state);
    }
}

And in State class
@Override
public String toString() {
    return String.format("%-12s %5s %12d", abbreviation, nameOfState, population);
}

Streamy version for fun
Using a constructor that takes the line directly
public State(String data) {
    String[] tokens = data.split(",\\s*");
    this.abbreviation = tokens[0];
    this.nameOfState = tokens[1];
    this.population = Integer.parseInt(tokens[2]);
}

You could
List<State> stateList = Files.lines(Path.of("States.txt"))
                             .map(State::new)
                             .collect(Collectors.toList());

stateList.stream()
        .filter(state -> state.getAbbreviation().equals(question))
        .forEach(System.out::println);


text:
Q: Is there a way to convert QnA Questions into LUIS Intent Utterances I followed this Microsoft Documentation to make my implementation of a Bot that uses LUIS to route users questions to QnAMaker: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-tutorial-dispatch?view=azure-bot-service-4.0&tabs=cs
Basically I noticed in the V3 Documentation(https://learn.microsoft.com/en-us/azure/cognitive-services/qnamaker/tutorials/integrate-qnamaker-luis) (As there is no mention of it in V4)
it says:

Add an intent for each QnA Maker knowledge base. The example
  utterances should correspond to questions in the QnA Maker knowledge
  bases.

My question is, other than manually copying all the questions from QnA Maker to each individual Intent (Assuming I have multiple KBs) is there an easier way to do this? Eg export the file from QnA Maker or something similar?

A: This is done using the Dispatch tool. Essentially what it does is downloads the questions from your QnA Maker KBs and creates a new LUIS app with "dispatch" in the name. Inside this new app a intent will be added for each of your QnA Maker KBs, the naming will be q_<kb_name_here>, the questions from the relevant KB will be added to this intent as utterances.
How to do this is outline under the Create the dispatch model section of the documentation that you linked.
You will need to have NodeJS which comes with npm installed to do the following from the command line in your CognitiveModels folder (rough guide):
// install botdispatch package
npm i -g botdispatch

// initialise a dispatch file
dispatch init -n <filename-to-create> --luisAuthoringKey "<your-luis-authoring-key>" --luisAuthoringRegion <your-region>

// add references to luis and qna apps
dispatch add -t luis -i "<app-id-for-weather-app>" -n "<name-of-weather-app>" -v <app-version-number> -k "<your-luis-authoring-key>" --intentName l_Weather
dispatch add -t luis -i "<app-id-for-home-automation-app>" -n "<name-of-home-automation-app>" -v <app-version-number> -k "<your-luis-authoring-key>" --intentName l_HomeAutomation
dispatch add -t qna -i "<knowledge-base-id>" -n "<knowledge-base-name>" -k "<azure-qna-service-key1>" --intentName q_sample-qna

// generate a dispatch model
dispatch create

Then in the LUIS portal you will have to find your new app and Publish it before you will be able to use it. then follow the steps under the Use the dispatch model to take advantage of LUIS for routing.


text:
Q: Problem on continuous periodic functions
Problem. Let $f:\Bbb R\to\Bbb R$ be a continuous periodic function. Show that for every $t>0$, there exists $x\in\Bbb R$ with $$f(x)=\frac{f(x+t)+f(x-t)}{2}.$$

My Attempt. First, if $f$ is constant, then we are done. Otherwise, we can rewrite the formula as
$$f(x+t)-f(x)=f(x)-f(x-t).$$
Denote $g(x):=f(x)-f(x-t)$. It then suffices to show that there exists $x\in\Bbb R$ such that $g(x)=g(x+t)$. In particular, I also know that $g$ is periodic with the same period as $f$. But I have no idea how to continue.
Here $t>0$ is an arbitrary constant, not necessarily the period or integer times the period, so the case looks a bit complicated.

A: Let $T$ be the period of $f$.
Let $h(x) = g(x+t)-g(x)$. Then $h$ is a continuous periodic function with period same as $g$ and $f$.
Now as $g$ is contuinuous and periodic with period $T$, we have $g(\mathbb{R})=g([0,T])$ so the range of $g$ is bounded and compact.
Let $a,b\in \mathbb{R}$ such that $g(a) = \text{sup}\, g(\mathbb{R})$ and $g(b) = \text{inf} \,g(\mathbb{R})$, then $h(a-t) = g(a)-g(a-t) \ge 0 $ and $h(b-t) = g(b)-g(b-t) \le 0 $ so by intermediate value theorem there exists a $c\in \mathbb{R}$ such that $h(c)=0$ implying the result.