text:
Q: How do I evaluate this type of integral that involve complex parameters? In particular, I am asking about integrals shaped like this:
$$\int_{-\infty}^\infty e^{-ax^2-bx}dx$$
where $a\in\mathbb C$ with ${\rm Re}(a)>0$, and $b\in\mathbb C$. This kind of integral appears often in quantum mechanics when computing the wave function using Fourier's transformation. However, it seem that physicists uses the formula
$$\int_{-\infty}^\infty e^{-ax^2-bx}dx=\frac{1}{\sqrt a}\int_{-\infty}^\infty e^{-y^2+b^2/4a}dy=\frac{e^{b^2/4a}\sqrt\pi}{\sqrt a}$$
which I believe only holds when $a,b$ are real and $a>0$ unless there is further explanation.
Is there any way to justify this formula in the case of $a,b\in\mathbb C$ with ${\rm Re}(a)>0$? Or is there a workaround?

Update: what I feel confused about
My textbook and an answer below say "make the substitution $y=x+b/2a$". And the integral would be justified by
$$I=\int_{-\infty}^{\infty} e^{-(ax^2+bx)} dx=\int_{-\infty}^{\infty} e^{-a(x^2+(b/a)x)} dx =\int_{-\infty}^{\infty} e^{-a([x+(b/(2a))]^2)} e^{b^2/(4a)} dx\\
=e^{b^2/(4a)} \int_{-\infty}^{\infty} e^{-ay^2} dy=\sqrt{\frac{\pi}{a}} e^{b^2/(4a)}$$
(1) After the substitution $y=x+b/2a$, $y$ will not be real if $b/2a$ is not. In this case, shouldn't the integral after the substitution be
$$e^{b^2/(4a)} \int_{-\infty+b/2a}^{\infty+b/2a} e^{-ay^2} dy\quad ?$$
How is this defined? Perhaps a Riemann-Stieltjes integral?
(2) Suppose it is a Riemann-Stieltjes integral, this would mean we are integrating
$e^{-ay^2}$, where $a$ and $y$ are both possibly complex, along the line ${\rm Im}(y)={\rm Im}(b/2a)$. How do I evaluate this?
(3) Suppose somehow we can indeed get rid of $b/2a$ and write
$$\int_{-\infty}^\infty e^{-ax^2-bx}dx=e^{b^2/(4a)} \int_{-\infty}^{\infty} e^{-ay^2} dy$$
What's to justify
$$\int_{-\infty}^{\infty} e^{-ay^2} dy=\sqrt{\pi/a}\quad?$$
when $a\notin\mathbb R$? I am assuming another substitution is made here: "$t=\sqrt{a}y$" to obtain
$$\int_{-\infty}^{\infty} e^{-ay^2} dy=\sqrt{a}\int_L e^{-t^2} dt$$
where $L$ is the line $\mathbb R\cdot\sqrt a$. The well-known $\int_{-\infty}^\infty e^{-t^2}dt=\sqrt{\pi}$ does not seem to be usable here.

A: It is rather insightful to question whether the substitution is valid because the limits change in a potentially unpleasant way when the substitution is made. Let me show two ways to justify the substitution. First off, we could use contour integrals. Let
$$-ax^2-bx=-a\left(x^2+\frac bax\right)=-a\left(x+\frac b{2a}\right)^2+\frac{b^2}{4a}=-a\left(x+f+ic\right)^2+\frac{b^2}{4a}$$
Where $f=\Re\frac b{2a}$ and $c=\Im \frac b{2a}$. Translation in the real direction doesn't change the limits but translation in the imaginary direction does:
$$\int_{-\infty}^{\infty}e^{-ax^2-bx}dx=e^{\frac{b^2}{4a}}\int_{-\infty}^{\infty}e^{-a(x+f+ic)^2}dx=e^{\frac{b^2}{4a}}\int_{-\infty}^{\infty}e^{-a(y+ic)^2}dy$$
Where we have made the substitution $x+f=y$. To justify the imaginary translation we set up a contour integral
$$\oint_Ca^{-az^2}dz=\int_{C_1}e^{-az^2}dz+\int_{C_2}e^{-az^2}dz+\int_{C_3}e^{-az^2}dz+\int_{C_4}e^{-az^2}dz$$
Where the contour $C$ is counterclockwise around a rectangle in the complex $z$-plane and the subcontours are shown in the following figure:

Now we can work out the integral over each subcontour. Along $C_1$, $z=t$ so
$$\int_{C_1}e^{-az^2}dz=\int_{-N}^Ne^{-at^2}dt$$
So
$$\lim_{t\rightarrow\infty}\int_{C_1}e^{-az^2}dz=\int_{-\infty}^{\infty}e^{-at^2}dt$$
Along $C_2$, $z=N+is$ so
$$\int_{C_2}e^{-az^2}dz=i\int_0^ce^{-a(N+is)^2}ds$$
$$\begin{align}-a(N+is)^2&=-(\Re a+i\Im a)(N^2+2iNs-s^2)\\
&=-(N^2-s^2)\Re a+2Ns\Im a+i\left(-(N^2-s^2)\Im a-2Ns\Re a\right)\end{align}$$
So
$$\left|e^{-a(N+is)^2}\right|=e^{-(N^2-s^2)\Re a+2Ns\Im a}$$
And
$$\begin{align}\left|\int_{C_2}e^{-az^2}dz\right|&\le\int_0^ce^{-(N^2-s^2)\Re a+2Ns\Im a}ds\\
&\le\int_0^ce^{-(N^2-c^2)\Re a+2Nc\left|\Im a\right|}ds=ce^{-(N^2-c^2)\Re a+2Nc\left|\Im a\right|}\end{align}$$
So that
$$\lim_{N\rightarrow\infty}\int_{C_2}e^{-az^2}dz=0$$
Along $C_3$, $z=t+ic$ so
$$\int_{C_3}e^{-az^2}dz=\int_N^{-N}e^{-a(t+ic)^2}dt=-\int_{-N}^Ne^{-a(t+ic)^2}dt$$
So
$$\lim_{N\rightarrow\infty}\int_{C_3}e^{-az^2}dz=-\int_{-\infty}^{\infty}e^{-a(t+ic)^2}dt$$
From the work surround the $C_2$ contour I hope it is clear that
$$\left|\int_{C_4}e^{-az^2}dz\right|\le ce^{-(N^2-c^2)\Re a+2Nc\left|\Im a\right|}$$
So
$$\lim_{N\rightarrow\infty}\int_{C_4}e^{-az^2}dz=0$$
Since the integrand is holomorphic along and within contour $C$ it follows that
$$\oint_Ce^{-az^2}dz=0=\int_{-\infty}^{\infty}e^{-at^2}dt+0-\int_{-\infty}^{\infty}e^{-a(t+ic)^2}dt+0$$
So that justifies the imaginary translation step:
$$\int_{-\infty}^{\infty}e^{-at^2}dt=\int_{-\infty}^{\infty}e^{-a(t+ic)^2}dt$$
Of course we only did it for $c=\Im\frac b{2a}>0$ you might have to repeat for $c<0$. So we are up to
$$\int_{-\infty}^{\infty}e^{-ax^3-bx}dx=e^{\frac{b^2}{4a}}\int_{-\infty}^{\infty}e^{-ax^2}dx=2e^{\frac{b^2}{4a}}\int_0^{\infty}e^{-ax^2}dx$$
Now we let $a=re^{i\theta}$ and set up another contour integral

We want to do
$$\oint_Ce^{-rz^2}dz=\int_{C_1}e^{-rz^2}dz+\int_{C_2}e^{-rz^2}dz+\int_{C_3}e^{-rz^2}dz$$
Along $C_1$, $z=t$ so
$$\int_{C_1}e^{-rz^2}dz=\int_0^Re^{-rt^2}dt$$
and
$$\lim_{R\rightarrow\infty}\int_{C_1}e^{-rz^2}dz=\int_0^{\infty}e^{-rt^2}dt=\frac1{\sqrt r}\int_0^{\infty}e^{-u^2}du=\frac12\sqrt{\frac{\pi}r}$$
Along $C_2$, $z=Re^{i\phi}$ so
$$\int_{C_2}e^{-rz^2}dz=\int_0^{\frac{\theta}2}e^{-rR^2e^{2i\phi}}iRe^{i\phi}d\phi$$
Then
$$-rR^2e^{2i\phi}=-rR^2\cos2\phi-irR^2\sin2\phi$$
So
$$\left|e^{-rR^2e^{2i\phi}}\right|=e^{-rR^2\cos2\phi}\le e^{-rR^2\cos2\theta}$$
Thus
$$\int_{C_2}e^{-rz^2}\le\int_0^{\frac{\theta}2}Re^{-rR^2\cos3\theta}d\phi=\frac{\theta}2Re^{-rR^2\cos3\theta}$$
And
$$\lim_{R\rightarrow\infty}\int_{C_2}e^{-rz^2}dz=0$$
Along $C_3$, $z=te^{i\theta/2}$ so
$$\int_{C_3}e^{-rz^2}dz=e^{\frac{i\theta}2}\int_R^0e^{-re^{i\theta}t^2}dt=-e^{\frac{i\theta}2}\int_0^Re^{-at^2}dt$$
So
$$\lim_{R\rightarrow\infty}\int_{C_3}e^{-rz^2}dz=-e^{\frac{i\theta}2}\int_0^{\infty}e^{-at^2}dt$$
Again the integrand is holomorphic along and within contour $C$ so
$$\oint_Ce^{-rz^2}dz=0=\frac1{\sqrt r}\int_0^{\infty}e^{-t^2}dt+0-e^{\frac{i\theta}2}\int_0^{\infty}e^{-at^2}dt$$
So now we have
$$\int_{-\infty}^{\infty}e^{-ax^2-bx}dx=\frac{2e^{\frac{b^2}{4a}}}{\sqrt re^{\frac{i\theta}2}}\int_0^{\infty}e^{-t^2}dt=\frac{e^{\frac{b^2}{4a}}}{\sqrt a}\int_{-\infty}^{\infty}e^{-t^2}dt$$
Another way to justify is to start with
$$I(c)=\int_{-\infty}^{\infty}e^{-a(y+ic)^2}dy$$
Then
$$\frac{dI}{dc}=\int_{-\infty}^{\infty}-2ia(y+ic)e^{-a(y+ic)^2}dy=\left.ie^{-a(y+ic)^2}\right|_{-\infty}^{\infty}=0$$
So
$$I(c)=\int_{-\infty}^{\infty}e^{-a(y+ic)^2}dy=\text{constant}=I(0)=\int_{-\infty}^{\infty}e^{-ay^2}dy$$
That gets us to
$$\int_{-\infty}^{\infty}e^{-ax^3-bx}dx=2e^{\frac{b^2}{4a}}\int_0^{\infty}e^{-ax^2}dx$$
Now we can let
$$J(\theta)=\int_0^{\infty}e^{-re^{i\theta}x^2}dx$$
Then
$$\frac{dJ}{d\theta}=\int_0^{\infty}-rie^{i\theta}x^2e^{-re^{i\theta}x^2}dx=\left.\frac i2xe^{-re^{i\theta}x^2}\right|_0^{\infty}-\frac i2\int_0^{\infty}e^{-re^{i\theta}x^2}dx=-\frac i2J(\theta)$$
The general solution to this differential equation is
$$J(\theta)=Ce^{-\frac i2\theta}$$
And we can apply the initial condition
$$J(0)=C=\int_0^{\infty}e^{-rx^2}dx=\frac1{\sqrt r}\int_0^{\infty}e^{-t^2}dt$$
If we now let $a=re^{i\theta}$ then
$$\int_{-\infty}^{\infty}e^{-ax^2-bx}dx=2e^{\frac{b^2}{4a}}J(\theta)=\frac{2e^{\frac{b^2}{4a}}}{\sqrt re^{\frac i2\theta}}\int_0^{\infty}e^{-t^2}dt=\frac{e^{\frac{b^2}{4a}}}{\sqrt a}\int_{-\infty}^{\infty}e^{-t^2}dt$$
So we could justify the imaginary translation step and the rotation step either via contour integrals or by differentiating with respect to a parameter.

A: $$I=\int_{-\infty}^{\infty} e^{-(ax^2+bx)} dx=\int_{-\infty}^{\infty} e^{-a(x^2+(b/a)x)} dx =\int_{-\infty}^{\infty} e^{-a([x+(b/(2a))]^2)} e^{b^2/(4a)} dx $$
Let $x+b/(2a)=t$, then
$$I=e^{b^2/(4a)} \int_{-\infty}^{\infty} e^{-at^2} dt=\sqrt{\frac{\pi}{a}} e^{b^2/(4a)}, ~\Re(a) >0.$$


text:
Q: Adding linked list together and printing the result My problem is asking to have two linked lists where each node has one value and add them together into a different linked list. But, in order to get the digits of the list, I will have to do the modulo and division operator to shift my decimal and get the digits. I am using the power function as an increment of my index through the list and able to add them together. However, in the end is not printing my output. Everything looks fine, but the new linked list is not showing up. This is what I have:
#include <iostream>
#include <math.h>
using namespace std;

class elem {
public:

    int data;
    elem * next;
    elem * prev;
    elem()
    {
        next = prev = NULL;
    }
};
elem *head = NULL;

int num(elem * head) { //Putting the head in the last element
    int mem = 0;
    int powr = 0;
    for (elem * p = head; p != NULL; p = p->next) {
        mem += p->data * pow(10, powr);
        powr++; //Increments the list +1
    }

    return mem; //Returns the sum
    /*
        ex. first element is 6, then it will be 6 x 10^0 = 6
            second element is 1, then it will become 1 x 10^1 = 10
            third element is 7, then it will become 7 x 10^2 = 700
            total mem = 700 + 10 + 6 = 716
            linked list form (7 -> 1 -> 6)
    */
}

int digit(int value) {
    int mem = 0;
    while (value > 0) {
        value /= 10;
        mem++;
    }
    return value;
}

elem * listSum(elem * listOne, elem * listTwo) {
    int temp1 = num(listOne); //List #1
    int temp2 = num(listTwo); //List #2
    int sum = temp1 + temp2; //New sum
    int digits = digit(sum); //New element with the sum of both

    elem * list = NULL;
    elem * last = NULL;
    for (int ii = 0; ii<digits; ii++) {
        elem * p = new elem;
        p->next = NULL;
        if (list == NULL) {
            list = p;
        }
        else {
            last->next = p;
        }
        p->data = sum % 10; //Gets the digit
        sum /= 10; //Reduces the decimal
        last = p; //Adds the new value into the last (from 7->1->6 it is going to become 617)
    }
    return list;
}

void main() {
    //Make first list
    // 7 -> 1 -> 6 -> NULL
    elem * a1 = new elem;
    a1->data = 7;
    elem * b1 = new elem;
    b1->data = 1;
    elem * c1 = new elem;
    c1->data = 6;

    a1->next = b1;
    b1->next = c1;
    c1->next = NULL;
    elem * firstHead = a1;

    //Make second list
    // 5 -> 9 -> 2 -> NULL
    elem * a2 = new elem;
    a2->data = 5;
    elem * b2 = new elem;
    b2->data = 9;
    elem * c2 = new elem;
    c2->data = 2;

    a2->next = b2;
    b2->next = c2;
    c2->next = NULL;
    elem * secondHead = a2;

    elem * newHead = listSum(firstHead, secondHead);
    /*
        ( 7 -> 1 -> 6) + (5 -> 9 -> 2) would be 617 + 295 = 3rd new node
    */
    for (elem * p = newHead; p != NULL; p = p->next) {
        cout << p->data;

        //Output should be: 2 -> 1 -> 9. Which is 912
    }

}

As a test case, I made a print function to see if is printing the list for the sum, but it says that is empty. My other values looks fine when it prints. Any thoughts?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to fail an Azure DevOps pipeline build on WhiteSource report results? I have a step in my Azure DevOps build pipeline to generate a WhiteSource Bolt report
  - task: WhiteSource Bolt@20
displayName: "WhiteSource Bolt"

Does anyone know if there is a way to fail the build based on the report find vulnerabilities at a certain severity level?


text:
Q: Merge Two Arrays so that the Values Alternate I'm looking for a jQuery method to merge two arrays so that their values alternate:
var array1 = [1,2,3,4,5];
var array2 = ['a', 'b', 'c', 'd', 'e'];

The result I want is:
var arrayCombined = [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e'];

Please note that I know it is trivial to do this in JS, however I am after a jQuery method that will do this.

A: Just another solution using Array.prototype.flat() and Array.prototype.map().

var array1 = [1, 2, 3, 4, 5];
var array2 = ['a', 'b', 'c', 'd', 'e'];

var result = array1.map(
  (element, index) => [element, array2[index]]
).flat();

console.log(result);

A: For those who arrive here by search engine and want a Lodash option:
_.compact(_.flatten(_.zip(array1, array2)))

A: You can use the map method:

var array1 = [1, 2, 3, 4, 5];
var array2 = ['a', 'b', 'c', 'd', 'e'];

var arrayCombined = $.map(array1, function(v, i) {
  return [v, array2[i]];
});

console.log(arrayCombined);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Demo: http://jsfiddle.net/Guffa/hmUy6/

A: Try something like this:
function merge(array1, array2) {
  if (array1.length == array2.length) {
    var c = [];
    for (var i = 0; i < array1.length; i++) {
      c.push([array1[i], array2[i]]);
    }
    return c;
  }
  return null;
}

A: If you must use jQuery, you can take advantage of their broken $.map implementation.
var result = $.map(array1, function(v, i) {
                                return [v, array2[i]];
                           });

jQuery's $.map flattens the returned array, giving you the result you want.
DEMO: http://jsfiddle.net/8rn2w/

Pure JS solution:
var result = array1.reduce(function(arr, v, i) {
                              return arr.concat(v, array2[i]);
                           }, []);

DEMO: http://jsfiddle.net/8rn2w/1/

A: I came here curious to see if there was a new Array.prototype.<whatever>() that was helpful for this - and flatMap is that... kinda - but I'm going to leave with the simplest, most obvious solution...
(and a few tears that in 10 years no one else used a for loop to build a single array)
Plain, old JavaScript
If you were merging bits of something like stereo channels, or template strings, etc, this is all you need:
// Supports the two most common cases:
//   - interleaving left and right audio channels
//   - interleaving template string and values
// (right is assumed to be the same length as left, or one shorter)
function interleave(left, right) {

  var both = [];
  var i;

  for (i = 0; i < left.length; i += 1) {
    both.push(left[i]);

    // because a template string will have one fewer value
    // than it will have string parts
    if (i < right.length) {
      both.push(right[i]);
    }
  }

  return both;
}

// a template string will always have one extra item
var abc = ['a', 'b', 'c', 'd' ];
var one = [1, 2, 3 ];

var both = interleave(abc, one);
console.log(both);
// ['a', 1, 'b', 2, 'c', 3, 'd']

flatMap
As mentioned in a comment, this is probably suitable:
function cleverInterleave() {
  return abc.flatMap(function (val, i) {
    if (one[i]) {
      return [val, one[i]];
    }
    return [val];
  });
}

var abc = ['a', 'b', 'c', 'd' ];
var one = [1, 2, 3 ];

cleverInterleave(abc, one);
// ['a', 1, 'b', 2, 'c', 3, 'd']

However, this seems a little too "clever" and not as intuitive. Also not as efficient... but readability counts far more than efficiency for most code, so... two strikes against.
mo' channels, mo' problems
You could also create a more generic form of this to handle arbitrary numbers of arrays, or zip up arrays of uneven lengths.
However, I'd recommend using a similar pattern, but tuned to the actual number of arrays that you need - such as 3 for RGB, or 4 for RGBA, etc.


text:
Q: GCC: why does compiling a .hpp file gives different results than a .cpp file? Here I have a very simple Point class:
namespace wtf{

  template<typename T> class Point{

    public:
      T x;
      T y;

      Point(T xx, T yy): x(xx), y(yy) {};
  };

}

As a templated class, it is my understanding that there cannot be separate header/implementation files as usual.
If I name the file that contains this class Point.cpp, and compile it to a shared library as shown below, the file size is 5.6K, which seems reasonable. If I rename the file to Point.hpp (Or .hxx or .h++), however, the file size grows to 1.9M! Clearly gcc is processing these two file types differently!
Before I stripped this down to a MWE, there were additional standard lib includes (sstream and iostream), which brought the file size up to 11M! That also might give a little more of a clue about what is going on, though...
I am curious about what is actually happening here, and whether there are other ways that gcc treats header files and code files differently. Mostly I have used gcc 5.2.0, though the same thing happened with older versions.
I do understand that it is probably not typical to try and compile a header file, but since I did try and found a funny result, I would like to know what's going on!
Thanks!
EDIT: Removed image.

A: You've tricked your compiler into naming the file libPoint.so, while in fact it's not a shared library.
TL;DR: You're making a precompiled header.
Which effectively means the compiler processes the entire header and saves it's own state to a file. Later, when you give it a .c/.cpp file which starts with #include "Point.hxx", it loads the state from the precompiled header, so it doesn't need to process it again. Thus, your code compiles faster. In a source file, only the first included header can benefit from this.
If you remove -o blah.so from your command, GCC will name it Point.hxx.gch, which is the intended name for a precompiled header. In fact, GCC won't even find your PCH if it's named differently.


text:
Q: Fetch input value of a CQ5 Form Text Component We want to fetch input value of a CQ5 Textbox Component used multiple times on a single page. We have added components as shown below:-
<cq:include path="lastname" resourcetype="demoproject/components/lastname">
<cq:include path="firstname" resourcetype="demoproject/components/firstname">

Where in firstname and lastname are extended cq5 form text components.
How can we get values of respective fields? We thought of giving unique ID's to each component but since we are using default CQ5 component we are not able to set different ID to each component included in our .jsp page.

A: Nithalia,
If you will include a component by cq:include then you will be stuck with only one instance of it and will never be able to use it dynamically.
You will have to drag multiple instances of this text component into the Parsys and then will have to configure each of that instance individually. A component when dragged into Parsys is independent of other component because a different node is created each time you drag it. While if you will include it only a single node will be created and hence editing can be made but only once.
If you want to do some research, drag the text component multiple times on Geomartixx site and configure them individually and see the nodes that will be created under the /content path.


text:
Q: Aspectj @Around annotation, prevents the code called by the method itself to initialize Spring Autowireds I am using an AspectJ interceptor using the @Around annotation to measure specific execution times during Spring Unit tests.
When intercepted by Aspectj Aspect @Around annotation,
the code called by the method itself use non initialized Autowired.
The class member annotated with @Value("${some.configured.property}") of at least one autowired Component is not initialized and this lead to a Null Pointer Exception.
The unit test itself works perfectly when not intercepted.
How would you configure Aspectj
to let Spring initialize its Components properly
before interception ?


text:
Q: Collapse DIV only on Mobile View - Bootstrap 3 I have a sidebar search parameters. I want to make collapse function on this DIV only on Mobile device. Using Bootstrap 3 - Latest version.
Here is the HTML Markup.

Location

Lahore (254)

                    <form role="form">

                            <input type="checkbox" id="ModelTown">
                            Model Town

                            <input type="checkbox" id="DHA">
                            DHA

                            <input type="checkbox" id="CG">
                            Cavalry Ground

                            <input type="checkbox" id="Gulberg">
                            Gulberg

                            <input type="checkbox" id="Samnabad">
                            Samnabad

                            <input type="checkbox" id="AIT">
                            Allama Iqbal Town

                            <input type="checkbox" id="GardenTown">
                            Garden Town

                            <input type="checkbox" id="Township">
                            Township

                            <input type="checkbox" id="FaisalTown">
                            Faisal Town

                        20 more locations
                    </form>

Availability

                    M
                    T
                    W
                    Th
                    F
                    S
                    SU

The SearchParameters DIV I use to give styling to the code.
Note : I want to collapse "SearchParameters" div only on mobile and opened it with a button.. There should be only 1 div.  I can hide this div and show another div which is visible on mobile devices but that's not a good approach. I want to collapse this div and show it on button click only on mobile devices.

A: You could do it this way:
<button class="visible-xs" data-toggle="collapse" data-target="#SearchParameters">Toggle it</button>

...

CSS:
#SearchParameters.in,
#SearchParameters.collapsing {
    display: block!important;
}

A: Since the "in" class is what defines the collapsible element as open, removing it on mobile causes it to start out collapsed.
E.g.
<button data-toggle="collapse" data-target="#collapsible">Show/Hide</button>

    Content Here.

A: CSS-only method. Also works on Bootstrap 4.

@media (min-width: 768px) {
  .collapse.dont-collapse-sm {
    display: block;
    height: auto !important;
    visibility: visible;
  }
}

  <button class="btn btn-primary hidden visible-xs" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Collapse Button
  </button>

      Collapse Panel

source

A: Why not using the window.matchMedia?
For simplicity I've created an example based on Andrew Dinmore. It doesn't need the extra empty div to check whether something is visible or not.
<button class="btn btn-default btn-block visible-xs hidden-sm hidden-md hidden-lg" data-toggle="collapse" data-target="#Foo">Toggle</button>

enjoy! ;-)

A: Similiar to Rudy's solution, I found the following worked well for my needs, for Bootstrap 4.6 & Razor (Blazor WASM) :
@media (min-width: 641px) {
  .collapse.collapse-show-xs {
      display: block !important;
  }
}

Usage:

            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                 Home
            </NavLink>

When I upgraded the version of bootstrap for Blazorize, I noticed my sidebar was not showing anymore.  Now it's doing what I want, which is that it never hides when at least meeting xs screen size, and can be hidden when below.


text:
Q: What is the downside of merging several microservices in a single monolith? I can see the time employed in maintaining lots of microservices with functionality not independent from each other. Clients, queues, routers...a lot of stuff that maybe is not totally needed for attending the needs of conceptually simple projects. What is the downside of merging several microservices in a single monolith? If the project itself is the only consumer of most of its microservices, I think that partitioning a large app is just wasting time for the sake of following a supposedly good practise in an scenario in which does not fit.

A: Microservices provide for set of guide lines that help you build applications which can scale easily, which are more available and which allows your team to bring around changes really fast.
Having said that, it does not really closes the gate on monoliths or any other guidelines that you want to follow while building stuff.
There will be cases when building a monolith will indeed be a better option.
Say you are starting with some thing new, and you domain knowledge is not good. It will become really hard to break your application into services. In depth understanding of the domain is required to break services into effective smaller independent chunks.
Second could be you are doing a POC or MVP (with plans to test waters) then perhaps you can build everything as one.
With microservices, like I said you get scale, availability, maintainability and speed to make changes. There will be projects where these are not really a concern, and if they are not you can keep away from it.
Lastly, with microservices, you need to have a solid dev ops. you need to have CI/CD pipelines, you need to have monitoring, centralised logging etc, because trust me you will need it to debug stuff. It is indeed big investment and you should think what you are getting into and why you are getting into.
You should not be using it just because every one else is.


text:
Q: How do I programmatically change the value of I am trying to change the value of a range slider using the mousewheel anywhere on a page, but I don't know how to programmatically change the value of the input.
Here is my code:
HTML:
<input id="slider" type="range" min="0" max="100" step="1" value="50">

Javascript:
$(window).mousewheel(function(event, delta){
    $('#slider').val($('#slider').val()*1 + delta);
});

// Another thing I tried, but didn't work:
/*
$('#slider').attr('value', oldval + 1);
*/

Any pointers are appreciated.

A: It is being interpreted as a string. Use this
$(window).mousewheel(function(event, delta){
    $('#slider').val($('#slider').val()*1 + delta);
//    var oldval = $('#slider').attr('value');
//    if(delta > 0)
//        document.getElementById('slider').value++;
//    else
//        document.getElementById('slider').value--;
});

// Another thing I tried, but didn't work:
/*
$('#slider').attr('value', oldval + 1);
*/


text:
Q: ASP.NET Core Web API (2.1.4) project results in HTTP 502.5 Error with error code 0x80070005 I have tried to run my project on a server provided by someone else for some time now and after going through a lot of troubleshooting documents I'm at a spot where I don't know what to try next.
For debugging purposes I have created a plain, empty project (with just the default "values controller") and deployed that and it too produces the error.
The following information is available to me:

*

*HTTP Server Error: 502.5

*Logfile is produced but is empty

*System Log shows the follówing:

Application 'MACHINE/WEBROOT/APPHOST/WEBSITE-NAME/API' with
  physical root '' created process with commandline
  'E:\HostingSpaces\customer-folder\website-name\wwwroot\api\tu-test-api.exe
  'but failed to get its status, ErrorCode = '0x80070005'.

I have tried different deployment types and all produce the same error. e.g. framework dependent, which produces a DLL. Then the error just stated that 'dotnet tu-test-api.dll' produces the error. But the codes and behavior is the same.
The server is a Windows 2008 R2 Server with IIS Express.
It has Microsoft .NET Core 2.1.4 WIndows Server Hosting installed.
The following three things are installed:

*

*Microsoft .NET Core Runtime 2.1.4 (x64)

*Microsoft .NET Core 2.1.4 - Windows Server Hosting

*Microsoft .NET Core Runtime 2.1.4 (x86)

According to the Admin
1. PATH variable is set correct
2. Microsoft Visual C++ 2015 Redistributable (x64) is installed
3. After (2.) Bundle was repaired/reinstalled and server was rebooted
I'm a bit irritated because physical root is an empty string in the system logs. But I'm not sure what that means.
Any help on what to try next would be greatly appreciated.


text:
Q: Webpack-CLI error: Invalid configuration object I've searched around the internet for answers to this problem and I can't find the one that answers the specific issue I'm having. I've created a webpack.config.js and when I try running it with webpack-cli, I get the following error message
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.module.rules[0] has an unknown property 'query'. These properties are valid:
   object { compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, sideEffects?, test?, type?, use? }
   -> A rule description with conditions and effects for modules.

Here is my webpack.config.js file
// Load the needed node modules
var path = require("path");
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

// Webpack project settings
module.exports = {
    context: __dirname,
    entry: {
        lobby: './templates/components/lobby/index',
    },
    output: {
        path: path.resolve('./static/bundles/'),
        filename: "[name]-[hash].js"
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin(), // don't reload if there is an error
        new BundleTracker({path: __dirname, filename: './webpack-stats.json'})
    ],
    module: {
        rules: [
            {
                test: /\.jsx$/,
                exclude: /(node_modules)/,
                loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
                query: {
                    presets: ['es2015', 'react']
                }
            },
        ]
    },

    resolve: {
        modules: ['node_modules'],
        extensions: ['.jsx', '.js']
    }
}

I'm not very skilled with Webpack, but I have followed some tutorials on it and I think it looks like how a webpack file should be setup so I don't know why I'm getting this error.


text:
Q: Preposition phrase-of college
While I was home for the summer after my first semester of college, I decided to work in a store to earn some extra cash.

Is the preposition phrase "Of college" a noun complement of semester?


text:
Q: Python: Look for Files that will constantly change name So, I'll explain briefly my idea, then, what I've tried and errors that I've got so far.
I want to make a Python script that will:
Search for files in a directory, example: /home/mystuff/logs
If he found it, he will execute a command like print('Errors found'), and then stop.
If not, he will keep it executing on and on.
But other logs will be there, so, my intention is to make Python read logs in /home/mystuff/logs filtering by the current date/time only.. since I want it to be executed every 2 minutes.
Here is my code:
import time
import os
from time import sleep

infile = r"/home/mystuff/logs`date +%Y-%m-%d`*"

keep_phrases = ["Error",
              "Lost Connection"]

while True:
    with open(infile) as f:
        f = f.readlines()
        if phrase in f:
            cmd = ['#print something']
            erro = 1
        else:
            sleep(1)

I've searched for few regex cases for current date, but nothing related to files that will keep changing names according by the date/time.. do you have any ideas?

A: You can't use shell features like command substitutions in file names. To the OS, and to Python, a file name is just a string. But you can easily create a string which contains the current date and time.
from datetime import datetime

infile = r"/home/mystuff/logs%s" % datetime.now().strftime('%Y-%m-%d')

(The raw string doesn't do anything useful, because the string doesn't contain any backslashes. But it's harmless, so I left it in.)
You also can't open a wildcard; but you can expand it to a list of actual file names with glob.glob(), and loop over the result.
from glob import glob

for file in glob(infile + '*'):
    with open(file, 'r') as f:
        # ...

If you are using a while True: loop you need to calculate today's date inside the loop; otherwise you will be perpetually checking for files from the time when the script was started.
In summary, your changed script could look something like this. I have changed the infile variable name here because it isn't actually a file or a file name, and fixed a few other errors in your code.
# Unused imports
# import time
# import os
from datetime import datetime
from glob import glob
from time import sleep

keep_phrases = ["Error",
              "Lost Connection"]

while True:
    pattern = "/home/mystuff/logs%s*" % datetime.now().strftime('%Y-%m-%d')
    for file in glob(pattern):
        with open(file) as f:
            for line in f:
                if any(phrase in line for phrase in keep_phrases):
                    cmd = ['#print something']
                    erro = 1
                    break
    sleep(120)


text:
Q: Reading and inserting part of a csv file using php - not wanting repeating data Very novice student programmer here  :-) I want to read part of a CSV file and insert into phpMyadmin using sql insert statement.  I am a bit stuck... there is a column UN sub-region name and I only want each region to populate my database table once with its relevant regional score.
I have tried array_unique to print each region once however I also want to be able to get the corresponding score and be able insert both into a table in phpMyAdmin.
Here is my output: .
Any help is greatly appreciated :-)

<?php

include("../connection/conn.php");
$file = "Global_Index_Data.csv";
$regionName =[];
$regionScore =[];

if (file_exists($file)) {
    $filepath = fopen($file, "r");

    while (($line = fgetcsv($filepath)) != FALSE) {
        $region = $line[5];
        $score = $line[7];

        $regionName[] = $region;
        $regionScore[] = $score;
   }

    $resultName = array_unique($regionName);
     echo sizeof($resultName)."<br>";
      print_r($resultName);
      print_r($regionScore);

      //$regionNameScore = [$result, $line[7]];

      //print_r($regionNameScore);

}

?>

A: Consider using a single associative array to pair and sum up a region's score across all rows provided by your CSV file:
<?php
//...
$regionScoreByName = [];
while (($line = fgetcsv($filepath)) !== false) {
    $regionName = $line[5];
    $regionScore = $line[7];
    $currentRegionScore = $regionScoreByName[$regionName] ?? 0;
    $regionScoreByName[$regionName] = $currentRegionScore + $regionScore;
}

foreach($regionScoreByName as $regionName => $regionScore) {
    // Insert region score by region name into your database
}

Edit: mind the CSV column headers when processing the region scores this way.
Edit 2: I seem to have misunderstand your desired result. Instead of summing up the region scores (as single insert statements), you seem to want to group the individual regional score records by their region name (and insert them individually).
So instead of using an associative array to sum up a region's score, we can use it to group all region scores by their respective region name:
<?php
//...
$regionScoresByName = [];
while (($line = fgetcsv($filepath)) !== false) {
    $regionName = $line[5];
    $regionScore = $line[7];
    if (false === isset($regionScoresByName[$regionName])) {
        $regionScoresByName[$regionName] = [];
    }
    $regionScoresByName[$regionName][] = $regionScore;
}

foreach($regionScoresByName as $regionName => $regionScores) {
    foreach($regionScores as $regionScore) {
        // Insert region score by region name into your database
    }
}

A: @Jeroen van der Laan here is what I did. I wanted to print_r to check.

<?php

include("../connection/conn.php");
$file = "Global_Index_Data.csv";
$regionName = [];
$regionScore = [];
$regionScoreByName = [];

if (file_exists($file)) {
    $filepath = fopen($file, "r");

    $regionScoreByName = [];
    while (($line = fgetcsv($filepath)) !== false) {
        $regionName = $line[5];
        $regionScore = $line[7];
        $currentRegionScore = $regionScoreByName[$regionName] ?? 0;
        $regionScoreByName[$regionName] = $currentRegionScore+$regionScore;
    }

    print_r($regionScoreByName);
    foreach($regionScoreByName as $regionName => $regionScore) {

    }

}

?>


text:
Q: Kentico localization in ascx transformation IF statment I felt it was easier to start a new thread here. In a previous thread (initial post) I was looking at dynamically adding a the open and close table tags in a repeater. As i'm working through the build in French, i'm struggling with using resource strings. Here's the code snippet:

<%# IsFirst() ? "

Date	Subject	From

" : "" %>

I want to replace the string 'Subject' with a resource key. I've tried a macro approach, and concatenation of the c#, but i'm stuck.

A: The resource string macro is {$ the.resource.string.code $}, so you add a localization string in the "Localize" module in Kentico, and use the macro above to place it.
If this is in an ASCX transformation, you may need to either use the CMS:LocalizedString control, or use a Literal control and then use the CMS.Helpers.ResHelper.GetString("stringKey");
https://docs.kentico.com/display/K9/Working+with+resource+strings

A: I rewrote the if statement to this. So far so good.

<%
 if (IsFirst()){
 %>

Date
<%# CMS.Helpers.ResHelper.GetString("kff.CEODirect-FormLabel--Subject") %>
From

<%
 }

%>

A: <%# Localize("kff.CEODirect-FormLabel--Subject") %>
I believe that will work, assuming that is your resource string key.


text:
Q: Spherical Conducting Shells, Potential When we have a spherical conducting shell and charge on outer surface of the shell then the potential inside remains constant i.e, kQ/R (R=radius). But say the inner surface of the shell is charged rather than outer then too does the potential remain constant?
Will the electric field still be 0 inside or will charges move towards outer surface , what would be the result ?
A situation similar to the one in the image below:-

A: If the grey and blue parts of your diagram are the conductors and the magnitudes of the two sets of charges are the same then you have drawn a correct diagram with an electric field present only in the region between the two sets of charges.
The field in that region being the same as if there was a $-Q$ charge at the centre of the arrangement.
In all other regions, including outside the outer sphere, the electric field will be zero and there will be no charge resident on the outside of the outer sphere.
Application of Gauss's law will show that is so.

A: The potential will remain constant and the the electric field at any point between the shells will be zero.

A: If you are talking of a conducting sphere, this situation cannot happen physically. Charge is supposed to stay on the outer surface of the conducting shell. However if you make the shell infinitely thin (which is again not possible physically,) then the potential inside (for radii less than the radius of the shell) would be still a constant.


text:
Q: How to use custom UICollectionReusableView as section header of collection view? I've been driven insane for hours as I can't get around with the issue.
I have a collection view which can have different section with different no. of items in each. For each section I need to use a section header of different type. So for this, I'm going to use UICollectionReusableView. But I can't seem to succeed in using a custom subclass of UICollectionReusableView by means of UINib registration.

A crash happens when I downcast the reusable view to my subclass. Like:

let friendHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                    withReuseIdentifier: "FriendHeaderView",
                                    for: indexPath) as! FriendHeaderView

Below is the code snippet:
class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    private let viewModel = ProfileViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
        // more code
        collectionView.register(UINib(nibName: "FriendHeaderView", bundle: nil),
                                forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                                withReuseIdentifier: "FriendHeaderView")
    }
}

Now here is the data source implementation:
extension ViewController: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        // valid implementation
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // valid implementation
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // valid implementation

    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        switch kind {
        case UICollectionView.elementKindSectionHeader:
            let friendHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "FriendHeaderView", for: indexPath) as! FriendHeaderView

            // *** Crash happens here *** //

            return friendHeader
        default:
            assert(false, "Invalid element type")
        }

    }

}

And I don't know why the collectionView(_:layout:referenceSizeForHeaderInSection:) needs to be also implemented. So here it is:
extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let size = CGSize(width: collectionView.bounds.width, height: 100)
        return size
    }

}

Okay, now come to the point: The above mentioned crash doesn't happen
  at all if I don't downcast with as! operator. Well, if I use section
  header from the storyboard instead of UINib registration, there is
  no crash.

If I'm going to need multiple type header, then I can't also use storyboard approach or without down-casting approach as I need to feed data to those headers.

What can I do to have multiple type headers with view built from interface builder?

I've made a demo project with what I've said above. If anyone is interested please check out that.

A: Once you assign proper class and identifier in your Xib file, then it will work without crashes.

A: Well, after some more investigation and the input from @good4pc in the accepted answer (actually I found out that by myself before looking at the answer) it seems that the issue is actually happening for some unwanted issue with Xcode.
When we create any view (preferably, UITableViewCell or UICollectionViewCell) with .xib, the class identity is provided automatically for that .xib in the identity inspector. But this was not the case for UICollectionReusableView. See the attached screenshot below for easy understanding.
This is a UICollectionViewCell subclassed with .xib:

This is a UICollectionReusableView subclassed with .xib:

So the key is to provide the class identity of the .xib file which
  is done from the attributes inspector.


text:
Q: Sort object by value So here's the object:

As you can see, the last amount(2000) is lower than 10000 but it's still at the end. I'm trying to display the elements sorted by amount. I know that I have to convert the object to array and use sort on it, but don't have an idea how can I do this properly.
EDIT: I've tried something like this without any success:
var packs_array = [];

jQuery.each(json.purchase_packs, function(i, pack) {
    packs_array.push(pack);
});

packs_array.sort();

A: To do this, you need to convert your object into an array first...
var arr = $.map(json.purchase_packs, function(v) { return v; });

... then sort this array with a custom sorter function:
arr.sort(function(a, b) {
  return a.amount - b.amount;
});

Demo. Note that sorting is in-place operation (i.e., arr.sort alters an existing object).

A: var packs = {
    0: { amount: 2000 },
    3: { amount: 1000 },
    5: { amount: 50 }
};

var sortedPacks = Object.keys(packs)
    .map(function (id)  {
        packs[id].id = parseInt(id, 10);
        return packs[id];
    })
    .sort(function (a, b) {
        return a.amount - b.amount;
    });

console.log(sortedPacks); // => [{"amount":50,"id":5},{"amount":1000,"id":3},{"amount":2000,"id":0}]

A: JavaScript sort() function works with list elements as strings by default. You should specify sort function to sort other value types:
var l = [1, 5, 12, 127, 12, 3, 9];
l.sort(function(a,b){return a-b});
=> [ 1, 3, 5, 9, 12, 12, 127 ]

Source


text:
Q: SQL query how to group separately same results wihin incremental keys RANK I have A and B columns. I need to group Column A with following way: 2&3, 5&6, 8&9&10 together based on values in B column. Column A is always increment 1 thru 10. I have issues finding a way in SQL to group 5&6 and 8&9&10 separately since they have same B values (1.4). I want to group incremental A values together (5,6,8,9,10 is not incremental due to missing 7). Appreciate any help. Thanks.
A   B
1   1.0
2   1.1
3   1.1
4   1.3
5   1.4
6   1.4
7   1.45
8   1.4
9   1.4
10  1.4

A: This is a gaps-and-islands type question, because you do not want to just group by B, you only want to group by consecutive B relative to A.
rextester: http://rextester.com/UEE36579
select
    minA = min(a)
  , maxA = max(a)
  , B
  , rnk = dense_rank() over (order by min(a))
from (select a, b
  , rn_a = row_number() over (order by a)
  , rn_b = row_number() over (partition by b order by a)
from t) as cte
group by B, rn_b - rn_a
order by minA, b

returns:
+------+------+------+-----+
| minA | maxA |  B   | rnk |
+------+------+------+-----+
|    1 |    1 | 1.00 |   1 |
|    2 |    3 | 1.10 |   2 |
|    4 |    4 | 1.30 |   3 |
|    5 |    6 | 1.40 |   4 |
|    7 |    7 | 1.45 |   5 |
|    8 |   10 | 1.40 |   6 |
+------+------+------+-----+

A: Dump into a temp table with an indicator of the groupings...

INSERT INTO #TempTable(ColA, ColB, GroupCol)
SELECT A,
       B,
       CASE
           WHEN A = 1 THEN 1
           WHEN A = 2 OR A = 3 THEN 2
           WHEN A = 4 THEN 4
           WHEN A = 5 or A = 6 THEN 5
           WHEN A = 7 THEN 6
           WHEN A = 8 OR A= 9 or A = 10 THEN 7
           ELSE NULL
       END AS GroupCol
FROM OrginalTable

  ColA
  ColB
  GroupCol

  1
  1.0
  1

  2
  1.1
  2

  3
  1.1
  2

  4
  1.3
  4

  5
  1.4
  5

  6
  1.4
  5

  7
  1.45
  6

  8
  1.4
  7

  9
  1.4
  7

  10
  1.4
  7

The you can use a "group by" using the groupCol


text:
Q: After webpack build (via gulp) - Toggle JS script stops binding to all toggles After I run webpack and transpile + combine all (6) of my js files, the custom toggle function I made stops working on all the toggles.
Toggles that are html <button> elements work fine, but the toggles that are  anchor tags stop working.
If I stop referencing the bundle.js in my html and reference the separate js files again, things work as they did (and as expected).
Webpack seems to run fine, without any errors. there are no console errors present in the browser.
This is a vanilla JS project, no react or vue or other front-end frameworks are used.
There are some bootstrap classes still in the html, but bootstrap has been removed and those classes are just remnants for now.
The elements involved:
Button element that still works as a toggle
<button class="navbar-toggler hidden-md-min" type="button" data-toggle="collapse" data-target="#navbar" id="mobileNavToggle" aria-haspopup="true" aria-expanded="false">

</button>

Anchor element that stops working for some reason
Toggle anchor

The JS involved
// init dropdowns is called on main.js after everthing loads
export const initDropdowns = () => document.querySelectorAll('[data-toggle~=dropdown]').forEach(setupDropdown);

const setupDropdown = (dropdownToggle) => {
  dropdownToggle.setAttribute('aria-haspopup', 'true');
  dropdownToggle.setAttribute('aria-expanded', 'false');

  let dropdownMenu = dropdownToggle.parentNode.querySelector('.dropdown-menu');

  dropdownMenu.setAttribute('aria-hidden', 'true');

  dropdownToggle.onclick = (evt) => {
    console.log("click happened!");
    evt.preventDefault();
    toggleDropdown(dropdownToggle, dropdownMenu);
  };

  // Toggle needs to close menu when a menu-item is clicked or when something outside the menu is clicked**
  dropdownAutoClose(dropdownToggle);
};

The console log included in the onclick block fires for the buttons, but nothing on the anchors, which make it seem like it isn't binding (or something).
and my webpack config just in case
const path  = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './source/js/main.js',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  resolve: {extensions: ['.js']},
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './public/js'),
  },
  devtool: 'source-map'
};

The only difference I can think of is that one element is a button (which works after webpack build) and the other is an anchor (which doesn't work  after webpack build for some reason).
I've removed the babel transpilation from the webpack config just to make sure it isn't that, the issue persists.
When using the plain js files not bundled by webpack, things work fine.
Does anyone have any idea why this would happen?
I've googled and tried for hours to figure out what the issue is.
Please help
Thanks in advance

A: Okay, so after much googling and research and wondering why no one else has experienced this kind of thing, I found a solution that worked for me.
I changed this
  dropdownToggle.onclick = (evt) => {
    evt.preventDefault();
    toggleDropdown(dropdownToggle, dropdownMenu);
  };

to this
dropdownToggle.addEventListener('click', (evt) => {
  evt.preventDefault();
  toggleDropdown(dropdownToggle, dropdownMenu);
});

Not sure why the former didn't work after being webpacked, but this solved my issue. It must be something to do with the eventlistener and how it got applied.
Still happy to hear an explanation if anyone has one.


text:
Q: TFSBuild call in Powershell throwing error I get the following error in powershell ISE:

tfsbuild : The term 'tfsbuild' is not recognized as the name of a cmdlet

I have tried the full path of tfsbuild, but then I still get an error.
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\tfsbuild start /collection:"http://xxxx:8080/tfs/DefaultCollection"  /builddefinition:"yyyy/zzzz"

A: If TfsBuild.exe is not in your PATH then you need to:

*

*Enclose full path in quotes

*Prefix call with &

*Include extension .exe

& "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\TfsBuild.exe" start...
Alternatively you can change your working directory to the folder containing the .exe and simply 'dot source' the executable.
cd "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE"
.\TfsBuild.exe start...


text:
Q: How to pass both formData and Json in POST request I am trying to pass both formData and an apiKey in the body of a POST request, but it seems like its not working in my code below. What is the right syntax of doing that?
static login = (formData) => {
    return fetch('/api/login', {
      method: 'POST',
      body: { formData,
              JSON.stringify({
                 apiKey: 'xxxxxxxx'
              }) },
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'same-origin'
    }).then(r => r.json())
  }

A: I'm pretty sure that's just request-promise, but here
var login = (formData) => {
    return fetch('/api/login', {
        method: 'POST',
        body: { formData:formData,
            json:JSON.stringify({
                apiKey: 'xxxxxxxx'
            })
        },
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
    }).then(r => r.json())
}

The body object needs to have keys assigned to the values
On the server, you can access them as body.formData and body.json


text:
Q: Global values modified by child process are not accessible to the parent process in main loop In the main(), I call a function create_child() which forks a child process and then executes a command which runs in the background. I use getpid() to get the pid of the child in a global variable, which is accessed by the parent in the main loop. However, i dont see the child pid value in the main loop.
following is the pseudocode-
pid_t pids[2];

create_child(cmd,counter) {

 i=fork();
 if(i<0) exit(1);
 if(i==0) {
   pids[counter]=getpid();
   ret=system(cmd);
   //when system returns exit 0;
  }
 }

 main() {
   counter=0;
   create_child(cmd,counter);
   if (pids[counter]==xxx) {

     -----
    }
 }

A:
I use getpid() to get the pid of the child in a global variable, which is accessed by the parent in the main loop.

When you execute a fork, a copy of the parent's address space is made for the child. Therefore the child will have a copy of the parent's variables, however modifying any variables in the parent or child will not see the changes also being made to the other one.
From the manpages for fork:

On success, the PID of the child process is returned in the parent, and 0 is returned in the child.

If you want to record the PID of the child in the parent, then have the parent store the return value of fork. If the return of fork is not 0, then you're in the parent. From here, have the parent store the PID. ie:
pid_t ret = fork();

if (ret < 0) { /* failed */ }
else if (ret == 0) { /* child, do exec */ }
else { /* parent, store PID */ }

A: You'll need a pipe to get back the pid. when you fork, the child inherits a copy of the current variables of the process. If you want to store any changes made by the child, you'll have to pipe them to the parent:
pseudocode:
int fd[2];
int id;
pipe(fd);
id = fork();
if (id == 0)
{
    close (fd[0]);
    pid = getpid();
    write (fd[1], pid, nbytes)
    exit(0);
}
else
{
    close(fd[1]);
    read(fd[0], buffer, nbytes);
}

You're then free to use the buffer to modify your global variable.

A: 1)  Once the parent forks a new process, new process has a life and there by it has its own data. New process inherits the data from the parent, and Child's own copy is created while child tries to modify the data. This concent is called CopyOnRight.  That is why the changes being made by child is not seen by parent.  Even if you create a Heap Data element [Ie: Dynamic memory allocation ], the same concept is applicable. Let's take the following example.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int arg, char ** argv )
{
    pid_t pid;
    int *p = malloc (sizeof(int));
    printf ("\n Globally Assigned 99 to *p\n ");
    *p= 99;

    pid = fork ();
    if (pid > 0)
    {
            printf ("\n Parent Changed *p to 100 \n ");
            *p=100;
            wait (NULL);
            printf (" Prent Exiting..\n");

    } else {
            sleep(10); /* I want to give preference to my parent :) */
            printf ("..Child fetching the value  *p is %d \n", *p);
    }

}
2). As explained by @Mathieu, pipe is also can be used to communite between two processes.
Let's look at the folloing sample code which uses shared memory between parent and child.
Compare this with the program given in (1). See!!! I have not done any error checking as my intention is project the concept!!!.
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main ( int arg, char ** argv )
{
        int sId;
        int * ptr= NULL;
        pid_t pid;

        /* We create a shared memory object */
        sId = shm_open("MySharedData", O_RDWR|O_CREAT|O_TRUNC, 0666);

        /* We allocate memory to shared object */
        ftruncate (sId, 512);

        /* we attach the allocated object to our process */
        ptr = (int *) mmap (NULL, 512, PROT_READ|PROT_WRITE, MAP_SHARED, sId, 0);
        printf ("\n Globally Assigned 99 to *p\n ");
        *ptr=99;
        pid = fork ();
        if (pid > 0)
        {
                printf ("\n Parent Changed *p to 100 \n ");
                *ptr=100;
                wait (NULL);
                printf (" Wow Child canged to %d \n", *ptr);
                printf (" Prent Exiting..\n");

        } else {
                sleep(10); /* I want to give preference to my parent :) */
                printf ("..Child fetching the value  *p is %d \n", *ptr);
                *ptr=1234;
        }
}

In program (2), you can see the changes in the parent that's been modified by the child and vice versa, as the shared memory is shared memory is common to both parent/child, rather than having both seperate memory location.
Hope this helps!!!.


text:
Q: Visual Studio C Program: How to print symbols for card suits? I'm trying to make a card game and I want to use the actual card suit symbols to print cards as so:
5♣ J♦ 10♠ Q♥
Problem is I literally have zero idea how to code these symbols to print successfully in a program.

A: You'll need to use the unicode characters for those symbols along with a font that supports them. This page lists the unicode character code for various suits. They are:

Spade = U+2660, Heart = U+2665, Diamond = U+2666, Heart = U+2663

This will give you black suits. There's also characters for white suits.
You'll also need to make sure you are using wchar_t to represent the characters, not char as it won't be wide enough. Also, make sure you use functions like wprintf to do your output.

A: With Windows console font set to "Lucida Console" the following works:
#include <stdio.h>

int main (void)
{
    int i;
    for(i=3; i<=6; i++)
         printf("%c", i);
    printf("\n");
    return 0;
}

Program output:
♥♦♣♠

Similarly with "Consolas" font.


text:
Q: How loading mechanism work? I've a number of files (pictures + fonts) that my c++ program (a game using Allegro library) need to load when it starts. It take me few seconds(about 2 seconds) to load before my program actually get into a running state. Files are being loaded like this:
gamePic[0] = al_load_bitmap("Data/pic01.jpg");
gamePic[1] = al_load_bitmap("Data/pic02.jpg");
gamePic[2] = al_load_bitmap("Data/pic03.jpg");
gamePic[3] = al_load_bitmap("Data/pic04.jpg");
gamePic[4] = al_load_bitmap("Data/pic05.jpg");
gamePic[5] = al_load_bitmap("Data/pic06.jpg");
gamePic[6] = al_load_bitmap("Data/pic07.jpg");
gamePic[7] = al_load_bitmap("Data/pic08.jpg");
gamePic[8] = al_load_bitmap("Data/pic09.jpg");
gamePic[9] = al_load_bitmap("Data/pic10.jpg");
gamePic[10] = al_load_bitmap("Data/pic11.jpg");

What mechanism should I apply so that I can run another animation that will show that "Files are being loaded..."?

A: 1) Figure out which UI framework suits your app/environment best, some examples include Qt, MFC or (might suffice for a simple window and progress bar control) plain win32 native APIs (assuming a Windows environment, GTK+ would be somewhat equivalent to the aforementioned libraries on a linux system). AFAIK allegro does not provide UI APIs but it's a graphics / image manipulation library. You could of course render your own controls with allegro but that would be even harder
2) Create a UI window with the progress bar control and put it into a separate thread (still, on a Windows platform this is accomplished by having the window creation and message dispatching on a separate thread)
3) Synchronize your progress bar with your work and make sure the window is unloaded when the loading is complete (i.e. the thread is rejoined and terminated)

A: As @Piotr S. already mentioned, you need threads. (You need to write your program in a parallel form.)
The threading model would look like this:
Shared memory: percentCounter
Thread 1: Loading the bitmaps and fonts, updating percentCounter
Thread 2: Displaying the loading bar
I'm not sure whether Allegro provides some thread functions. (As, e.g. SFML does)
Otherwise, if you use at least C++11, you use std::thread from the C++ standard library.
If you only want to show that the App is loading (and not "Not responding"), you could also write a simple "Loading" to the screen, just before or between loading the bitmaps.


text:
Q: WPF Storyboard beginner problem I'm writing my first WPF application and I'm trying to implement a fade animation when the form closes. I came across this question Fading out a wpf window on close which shows how to make a fade-out animation but I can't seem to get it working. I have this in my XAML:
<Window.Resources>
    <Storyboard Name="FadeOutStoryboard" x:Key="FadeOutStoryboard" Completed="FadeOutStoryboard_Completed">
        <DoubleAnimation Storyboard.TargetProperty="Window.Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" />
    </Storyboard>
</Window.Resources>

And I then have this event handler:
    private bool doneFade;
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if (!doneFade)
        {
            e.Cancel = true;
            Storyboard sb = (Storyboard)this.FindResource("FadeOutStoryboard");
            sb.Begin();
        }
    }

But when the sb.Begin() method is called I get this exception:
System.InvalidOperationException: No target was specified for 'System.Windows.Media.Animation.DoubleAnimation'.

As stated this is my first attempt at WPF so I'm rather comfused at what I need to do to add the fade-out when the form is closing.

A: You need to add a target UI element to your StoryBoard animation otherwise it's got nothing to apply the animation to.
<Storyboard Name="FadeOutStoryboard" x:Key="FadeOutStoryboard" Completed="FadeOutStoryboard_Completed">
     <DoubleAnimation Storyboard.TargetName="myWindow" Storyboard.TargetProperty="Window.Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" />
</Storyboard>


text:
Q: How to set preselected the 10 first values on PHP into multiple select tag I have this Ajax call and I'm getting back an array. I have insert the elements into the multiple select.
Until now the preselected values are ALL but I want to preselect only the 10 first values of this.
I know that it's missing something on this line
sel.append('<option value=" ' + getOb[i]["ObN"] + ' " selected>' + getOb[i]["Ob"] + '</option>');

but I do not know what is missing. Some help :)
$.ajax({
                            url: "data/jjj.php?call=sss"
                            , type: 'POST'
                            , success: function (getOb) {
                                if (getOb != null) {
                                    var sel = $("#mf123_ob");
                                    for (var i = 0; i < getOb.length; i++) {
                                        sel.append('<option value=" ' + getObjekte[i]["ObN"] + ' " selected>' + getObjekte[i]["Ob"] + '</option>');
                                    }
                                }

A: You can use your index to determine whether it should be selected or not:
for (var i = 0; i < getOb.length; i++) {
    sel.append('<option value="' + getObjekte[i]["ObN"] + '"' + (i < 10 ? ' selected' : '') + '>' + getObjekte[i]["Ob"] + '</option>');
}

Or with string interpolation instead of concatenation:
for (var i = 0; i < getOb.length; i++) {
    sel.append(`<option value="${getObjekte[i]["ObN"]}"${i < 10 ? ' selected' : ''}>${getObjekte[i]["Ob"]}</option>`);
}

I used a ternary expression i < 10 ? ' selected' : '' directly in the string, though you could also create a variable that hold this value beforehand and then use it when building your string.


text:
Q: Let $\lambda_{i}(A) = i$-th eigenvalue of $A$. Show that $A \mapsto \lambda_{i}(A)$ is differentiable in $\mathcal{M}_{2 \times 2}(\mathbb{R})$
Let $\mathcal{L}_{\text{sim}}(\mathbb{R}) \subset \mathcal{M}_{2 \times 2}(\mathbb{R})$ the subspace of symmetric matrix of order $2$. Consider the aplication
  $$\lambda_{i}: \mathcal{L}_{\text{sim}}(\mathbb{R}) \to \mathbb{R},\quad i=1,2,\;\; \lambda_{i}(A) = i\text{-th eigenvalue of }A.$$
  Show that $A \mapsto \lambda_{i}(A)$ is differentiable in $\mathcal{M}_{2 \times 2}(\mathbb{R})$ and to calculate $\lambda'_{i}(A)$, for every $A \in \mathcal{L}_{\text{sim}}(\mathbb{R})$.

I couldn't develop much, but I started thinking about dividing into two cases: $A$ is invertible and $A$ is not invertible.
I can to use $\operatorname{tr}(A) = \lambda_{1} + \lambda_{2}$ and $\det(A) = \lambda_{1}\lambda_{2}$. I tried to write $\lambda_{i}(A + H) = \lambda_{i}(A) + L(H) + o(H)$ where $L(H)$ is a linear function and $\displaystyle \frac{o(H)}{||H||} \to 0$. My problem is: I couldn't to expand $\lambda_{i}(A + H)$ so that it was viable. There are probably some properties that should be used that I cannot remember. Can anybody help me?

A: Let's take a general approach with any $n \times n$ matrix $A$ and see how far we get. Then take a step back and apply this to $2\times 2$ symmetric matrices.
Part 1: Generic
Note that for any $n \times n$ matrices $A$ and $B$ $$\det(A + h B) \equiv \det(A) + h \operatorname{tr}(\operatorname{Adj}(A)\cdot B) \pmod{h^2}$$ where $\operatorname{Adj}(A)$ is the adjugate matrix. Let $P \in \mathbb{R}[x]$ be the characteristic polynomial of $A$
$$P(x) = \det(x - A)$$ and let $\lambda_B$ be the directional derivative of $\lambda$ in direction $B$ (which is what we want to compute). Then the formula for the derivative of a determinant above leads to
$$
\begin{eqnarray}
0 &=& \det(\lambda(A+ h B) - A - hB) \\
&\equiv& \det(\lambda(A) - A + h (\lambda_B(A) - B)) \\
&\equiv& h \operatorname{tr}(\operatorname{Adj}(\lambda(A) - A)\cdot(\lambda_B(A) - B)) \\
&\equiv& h \ (\lambda_B(A) P'(\lambda(A)) - \operatorname{tr}(\operatorname{Adj}(\lambda(A) - A)\cdot B))
\end{eqnarray}$$
and therefore
$$ \lambda_B(A) = \frac{\operatorname{tr}(\operatorname{Adj}(\lambda(A) - A)\cdot B)}{P′(λ(A))}.$$
Note that $\lambda_B$ is well defined except where $\lambda(A)$ is a double root of $P(x)$, in other words, if $\lambda(A)$ is an eigenvalue of $A$ with multiplicity greater than one.
Part 2: Specific
Now for $2 \times 2$ symmetric matrices $A$ the formula above simplifies quite a bit. Suppose that $A$ has eigenvalues $\lambda_1$ and $\lambda_2$ and decomposes as $$A = \lambda_1(A) \pi_1(A) + \lambda_2(A) \pi_2(A)$$ where $\pi_1(A)$ and $\pi_2(A)$ are orthogonal projections onto the eigenspaces. Then $$\operatorname{Adj}(\lambda_1(A) - A) = (\lambda_1(A) - \lambda_2(A))\ \pi_1(A)$$ and $$P'(\lambda_1(A)) = \lambda_1(A) - \lambda_2(A).$$ So we get as directional derivative $\lambda_{1B}(A)$ of $\lambda_1(A)$ in the direction $B$ $$\lambda_{1B}(A) = \operatorname{tr}(\pi_1(A) \cdot B).$$


text:
Q: Convert jQuery object of 'multiple elements without parent' to string I wanted to manipulate HTML by selecting elements and convert entire object to string so I can setContent() in tinyMCE.
Problem is if there is no parent element then while converting tostring only first element is converted while rest of elements are stripped. A simple example,
var elem = jQuery('

');
elem.prop('outerHTML');

will show output as
"

"

and strip rest of the elements. How can I convert jQuery object to string without losing elements?

A:

var elem = jQuery('

');
var str=""
elem.each(function(index,item){
str+=item.outerHTML
})
console.log(str)

A: You could map them, and then join them.

var test = $('

').map(function(){ return this.outerHTML; }).get().join('');
console.log(test);

A:

var elem = jQuery('

');
var strHtml='';
$.each(elem,function(index,value){
   strHtml+=value.outerHTML;
   console.log(value);
});
console.log(strHtml);


text:
Q: UnCheck ALL checkbox not working while using cascading multi select dropdown in SSRS report I am using SQL server 2008 R2.
I have two multiselect dropdown in my report. Second dropdown values populate based on 1st dropdown selected value.
Expectation
Select ALL checkbox in 1st dropdown, second dropdown values are loaded.Then I deselect ALL checkbok in 1st dropdown, 1st dropdown checked values are unchecked and second dropdown is disabled.
Output
When I deselect All checkbox in 1st dropdown,the 1st dropdown checkbox are didn't deselect and 2nd dropdown showed previous selected value.
You have any ideas, please Let me know

A: If you select 1 or more values in the 1st dropdown then the value of 2nd dropdown should refresh automatically (ordering of your parameters is important).
Whereas if you UNCHECK ALL the value in the 1st dropdown then the 2nd dropdown will not refresh to DEFAULT value which is by the design of the SSRS. Here is the link from microsoft community.
https://connect.microsoft.com/SQLServer/feedback/details/268032/default-does-not-get-refreshed-for-cascading-parameters


text:
Q: Speeding up Hausdorff in native python? I have two Numpy arrays that describe a 3D model, each of shape (471843, 3), where the '3' depicts spatial coordinate values, x,y and z and the '471843' are the vertices.
I am trying to calculate the Hausdorff distance between the two using the Hausdorff function from https://github.com/mavillan/py-hausdorff.
The function is executing but it does not seem to stop. It ran for almost 40 minutes and still didn't show any signs of stopping. Is this because it'll take a long time or some other reason? Also, from what I gather its a parallelizable function, so how can I export execution to CUDA GPUs to speed up the process?

A:
Q : "Is this because it'll take a long time or some other reason?"

Test it!
Run the very same function on ( 1E1, 1E2, 1E3, 1E4 ) datapoints and you can easily derive your ETA for the 4.7E5 datapoints. That's fair, isn't it?
   from zmq import Stopwatch; aClk = Stopwatch()

   SIZINGs = ( 1E1, 2E1, 5E1,
               1E2, 2E2, 5E2,
               1E3, 2E3, 5E3,
               1E4, 2E4, 5E4
               )
   MASK    = "INF: a problem-size {0:>5d} took {1:>12d} [us] to process"
   TIMINGs = {}

   #-------------------------------------------------------------------------
   print(  80*"_" )
   for aSize in SIZINGs:
       aClk.start()
       _ = 3D_wrapper_for_HausdorfDistance( data     = DATA[:int(aSize),:],
                                            distance = aCustomHausdorfDistance_in3D
                                            )
       TIMINGs[aSize] = aClk.stop()
       print( MASK.format( aSize, TIMINGs[aSize] )
   print(  80*"_" )
   #-------------------------------------------------------------------------

Q : "...how can I export execution to CUDA GPUs to speed up the process?"

First solve IF it makes sense to design & execute a CUDA-kernel so as to be performance-wise meaningful to be used. If it shows, there will not be any chance to perform faster than in a native N x 3+ [GHz]-LARGE-Cache-device, then and only then start the efforts to port the algorithm so as to efficiently harness the restricted precision contemporary GPU SMX SIMD-processors.


text:
Q: SQL Server concatenation separated by comma only when column is not null I have the following SQL statement:
@All = COALESCE(NULLIF(@Asc1, '') + ',', '') +
        OALESCE(NULLIF(@Asc2, '') + ',', '') +
        OALESCE(NULLIF(@Asc3, '') + ',', '');

This will insert a comma at the end even if any of the variables (@Asc1, @Asc2, @Asc3) have NULL or empty values.
For example:

*

*if @Asc1 = 1234 and @Asc2 = 3456 and @Asc3 = '', then @All will end up being 1234,3456,
I would like @All to be 1234,3456
Thanks.

A: using stuff() to remove the first comma and reversing the comma concatenation:
set @all = stuff(
    coalesce(','+nullif(@Asc1, ''), '')
  + coalesce(','+nullif(@Asc2, ''), '')
  + coalesce(','+nullif(@Asc3, ''), '')
  ,1,1,'');

rextester demo: http://rextester.com/UNDS90887
returns: 1234,3456

A: I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.
SELECT @all = CONCAT_WS(',',@Asc1,@Asc2,@Asc3)


text:
Q: image-shadow behind the main div I have the following HTML source:

And this is the CSS source
/* html selectors ---- */

html, body {
    font-family: 'Arial Unicode MS';
    margin: 0;
    padding: 0;
    background-repeat: repeat-x;
    background-color: white;
    direction: rtl;
    font-size: 10.3pt;
}

/*page -----------*/
#page {
    width: 900px;
    padding: 0px;
    margin: 0 auto;
    direction: rtl;
    position: relative;
    z-index: 100;
    z-index: 5;
    background-image: url("images/bgimage.png");
}

#leftshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/leftshadow.png");
    position: absolute;
    right: 1220px;
    z-index: none;
    top: -50px;
}

#rightshadow {
    width: 100px;
    height: 900px;
    background-image: url("images/rightshadow.png");
    position: absolute;
    right: 345px;
    z-index: none;
    top: -25px;
}

/* header ---------- */

#header {
    height: 110px;
    top: 0px;
    line-height: 30px;
    background-image: url("images/header.png");
    background-position-x: center;
    background-repeat: repeat-x;
}

/* main -------------- */

#main {
    line-height: 21px;
    font-family: arial;
    width: 625px;
    padding: 30px;
    position: relative;
    right: 205px;
    padding-bottom: 80px;
    direction: rtl;
    top: 42px;
    padding-right: 60px;
    min-height: 750px;

      text-align: justify;

}

Normally I got this result
But in Internet-Explorer I got this result
I know that if I will insert the

******Live example here! http://lawb.co.il/******
Into the #page Div the problem could be solved, but the only problem is that the shadow than is complatly on the content, und not behund him
Can you pleas help me with this?
wish for help, thanks!

A: Any reason as to why you are using images to create shadows when you could use CSS3 box-shadow?
If you are going to use this approach I would change your HTML structure like so:

And then float the right shadow div to the right and the left shadow div to the left. Most likely you are seeing inconsistencies because
you are not using a reset, and stuff is relatively positioned. You really don't need to position everything relative and the shadows if inside the #page container won't need to be positioned absolute.


text:
Q: Blazor url always starting in https://localhost:5001http://localhost:5000 what's the problem? I Can't configure it when I delete it and paste my own, after running it is giving me an error like in the image below and when I check the url is https://localhost:5001http://localhost:5000 how to fix that? Thanks a lot

A: I finally fixed that problem as mentioned @Kirk Larkin I went to lunchSettings.json and changed there the applicationUrl

A: Just guessing, but try semicolon delimiter or comma delimiter, or just http://localhost 5000.
https://localhost:5001;http://localhost5000

Or maybe:
https://localhost:5001,http://localhost5000

Or try just one:
http://localhost5000


text:
Q: Is it possible to change an ImageBrush color inside WPF? I'm trying to do something quite simple, but I'm not sure if it's possible. I have this image:

Inside my board game project, I use this to indicate the mouse position in the board and stuff like that (being the board a 8x8 grid with a rectangle inside). I'm also setting the grid cell background brush as, say, a SolidColorBrush with Blue color and .25 opacity, while the rectangle that lies above it with the target, or vice-versa, because I couldn't achieve my desired effect, which is, the part that is black to turn full blue, as my brush, while the rest remains with the opacity and etc. The way I did, it was possible to make the black part become blueish, with a transluscent background, but the color in the border isn't quite right yet:

I don't know if I was able to make myself clear, but I guess the picture shows what is my goal.
The code:
            ImageBrush targetBrush = new ImageBrush();
            targetBrush.ImageSource = new BitmapImage(new Uri("Resources/GameScreen/selectedTile.png", UriKind.Relative));
            targetBrush.Opacity = 1;

            SolidColorBrush backBrush = new SolidColorBrush(Colors.Blue);
            backBrush.Opacity = .25;

            tile.Children.Add(new Rectangle());
            foreach (object target in tile.Children)
            {
                if (target.GetType() == typeof(Rectangle))
                {

                    ((Rectangle)target).Fill = backBrush;
                }
            }

            tile.Background = targetBrush;

Thanks in advance.

A: As the image is just a mask you could use a Rectangle with a blue Fill and an OpacityMask set to your image.


text:
Q: how to get file content from sharepoint list using restapi in java I want to get the content of a file from sharepoint list using java through rest api
Can anyone help me,I am a newbie to sharepoint
Thanks in advance

A: Sharepoint provides a REST API to access lists.
Here is a sample end point to start with.
http://server/site/_api/lists/getbytitle('listname')

Here is more documentation:
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/get-to-know-the-sharepoint-rest-service
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-lists-and-list-items-with-rest
Edit:
To download file use the following URL:
http://server/site/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/sites/Test/Shared Documents/" + sourcefile.get_name() + "')/$value?@target='myhosturl'

Refer to
https://social.msdn.microsoft.com/Forums/sharepoint/en-US/02bfbcdc-73c8-4fa5-8967-cfd903a0d72e/javascript-client-object-model-openbinary-method
http://www.techmikael.com/2013/07/how-to-copy-files-between-sites-using.html for more information.


text:
Q: Weired number when i used currentddate.setDate(currentddate.getDate() + 30) to add 30 days from today I have the following code to add 30 days to the current date:-
var currentddate = new Date();
alert(currentddate);
var currentddate2 = new Date();
alert(currentddate2.setDate(currentddate2.getDate() + 30));

now the first alert will return the current date as follow Wed Jun 12 2019 22:15:49 GMT+0100 (British Summer Time) but the second alert will return this weird number 1562966157303 ? so can anyone advice on this?

A: Even though setDate changes the date, its return value is:

The number of milliseconds between 1 January 1970 00:00:00 UTC and the
  given date (the Date object is also changed in place)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
If you alert(currentddate2) again, you'll see that it was changed correctly.

A: If some API returns an unexpected result, first of all, look into the docs!

Return value
The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place).


text:
Q: using ggvis view_static to export html file and dependencies I am using ggvis (0.4) to make a simple scatter plot, that I want to show on a website. I am using view_static to generate the html file. The docs say I can set the dest parameter to specify the target directory for the html file and dependencies. However, no matter what I put there, I end up with the files in my tmp directory.
For example, if I do
library(ggvis)
test_plot <- mtcars %>% ggvis(~wt, ~mpg) %>% layer_points()
view_static(test_plot, dest = tempfile(pattern = 'ggvis_test'))

I would expect my file to be something like my/path/tmp/RtmpZw3qDp/ggvis_test7b3166824329/index.html. Instead, it is my/path/tmp/RtmpZw3qDp/viewhtml7b3166824329/index.html, so did not adopt the pattern I specified.
Ideally, I would like to   say view_static(test_plot, dest = tempfile(pattern = '~/target_dir')) and find the output directory target_dir in my home directory.
Am I doing something wrong when calling view_static, or is there another way of exporting the html or embedding it somewhere?
EDIT - THERE IS A WORKAROUND
I have submitted an issue on the github development site for ggvis - Winston Chang confirmed that the dest parameter is now deprecated. However as a workaround it was suggested one use view_static and html_print eg.
outfile <- mtcars %>% ggvis(~wt, ~mpg) %>% view_static() %>% htmltools::html_print()
outfile
# [1] "/tmp/Rtmps5hgoi/viewhtml266b14fd08f8/index.html"

to get the location of the output file and then copy it to the target directory from there. Works fine.

A: It doesn't look like you're doing anything wrong. Here's the contents of view_static:
> ggvis::view_static
function (x, plot_id = rand_id("plot_"), dest = tempfile(pattern = "ggvis"))
{
    spec <- as.vega(x, dynamic = FALSE)
    htmltools::browsable(ggvisLayout(plot_id, length(x$controls) >
        0, spec, shiny = FALSE))
}
<environment: namespace:ggvis>

It doesn't seem to pass dest on to anything. (same hold true for the dev version)


text:
Q: SPARQL property path in reified rdf triples Is it possible, to use property path with reified rdf triples?
I like to get all superclasses of a specified class (stored in ?class).
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>

SELECT ?class ?superclass ?supersuperclass ?supersupersuperclass
WHERE{
  {
    ?s rdf:subject ?class .
    ?s rdf:predicate rdfs:subClassOf .
    ?s rdf:object ?superclass .

    OPTIONAL {
    ?s1 rdf:subject ?superclass .
    ?s1 rdf:predicate rdfs:subClassOf .
    ?s1 rdf:object ?supersuperclass .
    }

    OPTIONAL {
    ?s2 rdf:subject ?supersuperclass .
    ?s2 rdf:predicate rdfs:subClassOf .
    ?s2 rdf:object ?supersupersuperclass .
    }

  }

}

A: You can use intermediate queries, first to dereify the statements:
CONSTRUCT {
  ?s a rdfs:Class .
  ?o a rdfs:Class .
  ?s rdfs:subClassOf ?o .
}
WHERE {
  ?t a rdf:Statement .
  ?t rdf:object ?o .
  ?t rdf:predicate rdfs:subClassOf .
  ?t rdf:subject ?s .
}

Then to obtain all of the subclass relations:
SELECT ?s ?o
WHERE {
  ?s a rdfs:Class .
  ?s rdfs:subClassOf* ?o .
}

If you know that classes are not interlinked by other predicates, you may use paths:
SELECT ?s ?o
WHERE {
  ?s a rdfs:Class .
  ?o a rdfs:Class .
  ?s (^rdf:subject/rdf:object)* ?o .
}


text:
Q: How to constraint from the center in Xcode I'm new to Auto Layouts and the concept of constraints. I'm currently trying to create a single view app with two buttons:

The buttons must meet the criteria shown in the image above. I can do everything except the two constraints where the buttons have to be a 30 above and 30 below, as it resizes the entire button to the point that one overlaps the other.
Is there any way to achieve this? I'm not doing the constraints programmatically, but rather on the storyboard. Many thanks.

A: Try put both of them in a view, add constraint between them 60px height, then make the view center of the superview, leading and trailing 20px, optional 50 from top and 150 from bottom, you should get the desired result.

A: The main issue here is to ensure that after setting alignment constraints both from the center, to select the following option of either the "bottom" or the "top" depending on how you want it:

This ensures that there is no "overlapping" caused.


text:
Q: How do you write text beyond the boundaries of a textbox without it adding a new line? I have a textbox with it's multiline property set to true, and dragged it out.
As it stands, whenever I type and the next word is going to be beyond the boundaries of the textbox, it'll create a new line instead. I want to be able to keep typing without it adding a  new line.
Like in Notepad, when you're going to write beyond the boundaries of the box, it'll let you keep typing and won't start at a new line untill you press enter. Instead, you can just use the scrollbar to scroll horizontally between your text. How do I do that with the textbox?

A: Try turning off the word wrap feature:
textBox1.WordWrap = false;


text:
Q: AutoMapper not creating new Guid on mapping I am having trouble figuring out how to trigger "new Guid()" using AutoMapper.
This is my model:
public class Countries
{
    public Guid Id { get; set; } = new Guid();
    public string Name { get; set; }
}

And this is my ViewModel:
public class CountriesViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

When I map from CountriesViewModel to Countries, Id in Countries have default value of Guid ( which is {00000000-0000-0000-0000-000000000000} ), instead of creating new Guid.
This is how I am doing that mapping:
public async Task<CountriesViewModel> Add(CountriesViewModel country)
{
    var mapped = _mapper.Map<CountriesViewModel, Countries>(country);

    _context.Countries.Add(mapped);

    if (await _context.SaveChangesAsync() == 1)
    {
        _mapper = _countriesConfig.CreateMapper();
        return _mapper.Map<Countries, CountriesViewModel>(mapped);
    }

    return new CountriesViewModel();
}

A: Here you are creating instance of Guid() that creates an empty Guid i.e. 00000000-0000-0000-0000-000000000000 every time
You are looking for Guid.NewGuid() which creates new guid with unique value.
Try below
public class Countries
{
    public Guid Id { get; set; } = Guid.NewGuid();
                                  //^^^^^^^^^^This was wrong in your code
    public string Name { get; set; }
}

For reference: Guid.NewGuid() vs. new Guid()


text:
Q: vba word macro to put a string to an existing Heading i am attempting to write a macro that with find/replace a string and than move it to an existing heading. The original text is like this:
1. Heading 1
ID: abcd
1.1 Heading 2
ID: abcd
And it should look like:
1.Heading 1 abcd
1.1 Heading 2 abcd
I am having some problems with the code i tried to write, mostly because i am kinda new, but this is what i created so far:
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Style = "Heading 2"
With Selection.Find
    .Text = "abcd"
    .Replacement.Text = "abcd^p"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False

End With
Selection.Find.Execute Replace:=wdReplaceAll

The text is not so important because i managed to replace with what i want but i don't know how to align it with the Heading style.. Thanks
EDIT: I hope i don't screw up again, sorry big :). So i have raw which is the raw text and i want to process it to look like this final. I already found out, thanks to you how to replace the text, it's just that i stuck in the raw version. Thanks, I kinda own you a beer, or two
LATER EDIT: So i have 5 types of Heading formats, 1. Heading 1, 1.1 Heading 2 etc till 5, and all of them have below them an ID, each with a specific number, but the name is the same, ID ASD_PC_AWP_[XXXX]. I just have to get rid of ID ASD_PC_ and put AWP_[xxxx] at same level of the Heading eg: 1.Heading 1 AWP_[xxxx1] ** , **2. Heading 2 AWP_[xxx2]...

A: Do a wildcard find for any paragraph marker which is followed by ID:.
.Text = "^13ID:"
.Replacement.Text = ""
You will need to specify the style of the replacement text to the heading style because when you delete the paragraph marker at the end of the Heading paragraph you will also delete the style information for the heading paragraph.
You will need to do this with every style heading followed by the ID: text.
Updated 2018-11-01
The following code should work.  I got some hints from Macropods ingeneous code.
Update 2 2018-11-01
Revised to work with a list of styles defined by user at OPs request
Sub ConsolidateHeadingWithID()

Const HEADINGS                                   As String = "Heading 1,Heading 2,Heading 3,Heading 4,Heading 5,Other style,another style"

Dim my_headings                                 As Variant
Dim my_heading                                  As Variant
my_headings = Split(HEADINGS, ",")

For Each my_heading In my_headings

        With ActiveDocument.StoryRanges(wdMainTextStory)

            With .Find

                .ClearFormatting
                .format = True
                .Text = ""
                .Style = my_heading
                .MatchWildcards = True
                .Wrap = wdFindStop
                .Execute

            End With

            Do While .Find.Found

                If .Duplicate.Next(unit:=wdWord).Text = "ID" Then

                    .Duplicate.Next(unit:=wdParagraph).Style = my_heading

                End If

                .Collapse wdCollapseEnd
                .MoveStart unit:=wdCharacter, Count:=2
                .Find.Execute

            Loop

        End With

        With ActiveDocument.Range.Find

            .ClearFormatting
            .format = True
            .Text = "(^13)(ID:)(*)(AWP_)([0-9]{1,})"
            .Style = my_heading
            .Replacement.Text = " [\4\5]"
            .MatchWildcards = True
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll

        End With

    Next

End Sub

A: Try:
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "ID:*^13"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    Set Rng = .Duplicate.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
    Rng.End = Rng.Paragraphs.First.Range.End - 1
    Rng.InsertAfter Split(Split(.Duplicate.Text, ":")(1), vbCr)(0)
    .Text = vbNullString
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub


text:
Q: Django form is not valid because of empty POST My django form is not valid. I guess it occurs because request.POST is almost empty(only csrf_token is included). Still I can't find the reason. Seeking for a help.
P.S. (To make it clear, what's happening in code) I have three levels of cascading categories and a list of patterns. I want to mark all the patterns with one category. Options of select2 depend on the selected option in select1. The same thing is for select3.
The form:
class AddPatternForm(forms.Form):
    category_1 = forms.ChoiceField()
    category_2 = forms.ChoiceField(required=False)
    category_3 = forms.ChoiceField(required=False)
    patterns = forms.CharField()

    def verify(self):
        valid = []
        invalid = []
        patterns = self.patterns.split('\n')
        for pattern in patterns:
            if VALID_DOMAIN.match(pattern):
                valid.append(get_domain(pattern))
            elif VALID_REGEXP.match(pattern):
                valid.append(pattern)
            else:
                invalid.append(pattern)
        return valid, invalid

The view:
def add_pattern(request):
    patterns = Url.objects.all()
    parents = Category.objects.filter(parent=None)
    if request.method == 'POST':
         form = AddPatternForm(request.POST)
         if form.is_valid():
             valid, invalid = AddPatternForm.verify()
             if form.category_3:
                 parent_id = form.category_3
             elif form.category_2:
                 parent_id = form.category_2
             else:
                 parent_id = form.category_1
             parent = Category.objects.get(pk=parent_id)
             for pattern in valid:
                 Url(pattern=pattern, categories=parent).save()
             return HttpResponseRedirect('')
     else:
         form = AddPatternForm()

     return render(request, 'app/add_pattern.html', {
        'form': form,
        'patterns': patterns,
        'parents': parents,
    })

The html:
      <form id="chooseCategory" method="post" action="">
        {% csrf_token %}

Категория:

          <select id="select1" class="form-control">
            <option value="">---</option>
            {% for parent in parents %}
            <option value="{{ parent.id }}">
              {{ parent }}
            </option>
            {% endfor %}
          </select>
            <option value="">---</option>
          <select id="select2" class="form-control">
          </select>
            <option value="">---</option>
          <select id="select3" class="form-control">
          </select>

          <textarea class="form-control" rows="5"></textarea>

        <button type="submit" class="btn btn-default">Save</button>
      </form>

The JS (realization of cascading dropdown select):
$( "#select1" ).change(function () {
          var str = "Категория: ";
          $( "#select1 option:selected" ).each(function() {
            str += $( this ).text() + " ";
          });
          $( "#chosenCategory" ).text( str );
          $( "#select2" ).find('option').remove().end()
          $( "#select2" ).append("<option value=''>---</option>")
          $.get("/load_new_options/", {"parent_id": $( "#select1 option:selected" ).val()},
          function(data) {
            var c = JSON.parse(data);
            for (i in c) {
              $( "#select2" ).append("<option value='" + c[i].pk + "'>" + c[i].fields.name + "</option>")
            }
          })
        })
        .change();

        $( "#select2" ).change(function () {
          var str = "Категория: ";
          $( "#select2 option:selected" ).each(function() {
            str += $( this ).text() + " ";
          });
          $( "#chosenCategory" ).text( str );
          $( "#select3" ).find('option').remove().end()
          $( "#select3" ).append("<option value=''>---</option>")
          $.get("/load_new_options/", {"parent_id": $( "#select2 option:selected" ).val()},
          function(data) {
            var c = JSON.parse(data);
            for (i in c) {
              $( "#select3" ).append("<option value='" + c[i].pk + "'>" + c[i].fields.name + "</option>")
            }
          })
        })
        .change();

        $( "#select3" ).change(function () {
          var str = "Категория: ";
          $( "#select3 option:selected" ).each(function() {
            str += $( this ).text() + " ";
          });
          $( "#chosenCategory" ).text( str );
        })
        .change();

        $('#chooseCategory').cascadingDropdown({
            selectBoxes: [
                {
                    selector: '#select1',
                },
                {
                    selector: '#select2',
                    requires: ['#select1'],
                },
                {
                    selector: '#select3',
                    requires: ['#select1', '#select2'],
                    requireAll: true,
                    onChange: function(){
                    }
                }
            ]
        });

UPD
The form is still not valid. The form.errors look as follows:
category_3
Select a valid choice. 19 is not one of the available choices.
category_2
Select a valid choice. 4 is not one of the available choices.
category_1
Select a valid choice. 1 is not one of the available choices.

A: Don't guess. Output the errors in the template, then you'll know why it is not valid.
{{ form.errors }}

Edit You have not put any name attributes in your form field elements. Browsers only send data on a form submit if the field has a name, as that's what the data is associated with.
You really should be using the Django form to output the fields anyway, rather than creating the HTML manually.


text:
Q: C#: Is there a way to launch the debugger from a codeline? Question:
Is it possible to start a web project application in my current solution without debugger (keycombo: Ctrl+F5) through a codeline?
thanks in advance

A: You can add
System.Diagnostics.Debugger.Launch();

In your code to debug.

A: The method KuldipMCA given is great, it can start debugger every time this code is executed.
And there are another way, add an Assert into your code, this can enable you to attach debugger with some condition control. Such as:
//This will trigger an assert when the condition is false
System.Diagnostics.Debug.Assert(obj != null);


text:
Q: SQL Find most recent record for each unique ID MS Access, wanting to query each unique record ID based on most recent date and a third condition where another column of record ID score is less than 60
Sample table:

RecordID
Score
Date

1
80
1/1/2020

1
60
1/1/2021

2
80
1/1/2020

2
60
1/1/2021

Query would pull:

RecordID
Score
Date

1
60
1/1/2021

2
60
1/1/2021

I initially tried to just pull the Record ID & the most recent date as a starting point:
SELECT RecordID, MAX(date)
FROM table
GROUP BY RecordID;

But all it does is return me

RecordID
Date

null
1/1/2021

Thanks for any help ahead of time.

A: If you want the Score 60s to appear on your query result, the criteria must be Less than or equal to 60.
and then the code is:
SELECT Table.RecordID, Table.Score, Max(Table.Date) AS MaxDate
FROM [Table]
WHERE (((Table.Score)<=60))
GROUP BY Table.RecordID, Table.Score;


text:
Q: Magento 2 Notice: Undefined variable: images I use custom variable in Mirasvit Extension for export parent images also from variants.
For test I export single product and working correct. Now I set filter with export all configurable products in website and I get issue:
Notice: Undefined variable: images in /home/azinvest/domains/under.pl/public_html/pub/media/feed/tmp/16110634559723.php on line 14

On line 14 custom variable  is:
 }
    $images = implode(', ', $images);
}

Here is full code dynamic variable.
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$mediaUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
if ($product->getTypeId() != 'configurable') {
$images = $mediaUrl . 'catalog/product' . $product->getImage();
} else {
    $children = $product->getTypeInstance()->getUsedProducts($product);
    foreach ($children as $child){
        if ($child->getMediaGalleryImages()) {
            foreach ($child->getMediaGalleryImages() as $image) {
    $images[] = $mediaUrl . 'catalog/product' . $image['file'];
            }
        }
}
    $images = implode(', ', $images);
}
return  $images;

Any solution?

A: please define variable images before if the condition
Ex. $images = ' ';