text:
Q: Animate thumb of UWP Slider I am using the Slider XAML control in my UWP app. Whenever we tap on the slider and change its value, I want the slider thumb to simply show a translation animation while moving from the old position to the new position. How can this be achieved?

A: You can use a property to get the last value and play an animation to set the value from the last vale to current value.
Adding a Slider in xaml
    <Slider x:Name="Slider" Value="{x:Bind Value,Mode=TwoWay}"/>

Adding a DependencyProperty in MainPage.
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value", typeof(double), typeof(MainPage), new PropertyMetadata(default(double), (s
            , e) =>
        {
            ((MainPage) s)._lastValue = (double) e.OldValue;
        }));

    public double Value
    {
        get => (double) GetValue(ValueProperty);
        set => SetValue(ValueProperty, value);
    }

    private double _lastValue;

The Value can set the _lastValue that can begin the Storyboard
Adding PointerPressedEvent and PointerReleasedEvent in MainPage code for the Slider will handle it.
    public MainPage()
    {
        InitializeComponent();
        Slider.AddHandler(PointerPressedEvent, new PointerEventHandler(Slider_OnPointerPressed), true);
        Slider.AddHandler(PointerReleasedEvent, new PointerEventHandler(Slider_OnPointerReleased), true);
    }

I save the ClickPoint in Slider_OnPointerPressed and I compare the current point in Slider_OnPointerReleased. The user may click the Slider that should begin the animation and the user drag the thumb that should not begin the animation.
    private void Slider_OnPointerPressed(object sender, PointerRoutedEventArgs e)
    {
        var slider = (Slider) sender;

        ClickPoint = e.GetCurrentPoint(slider).Position;
    }

    private Point ClickPoint { set; get; }

    private void Slider_OnPointerReleased(object sender, PointerRoutedEventArgs e)
    {
        var slider = (Slider) sender;

        var point = e.GetCurrentPoint(slider).Position;

        var x = point.X - ClickPoint.X;
        var y = point.Y - ClickPoint.Y;
        var length = x * x + y * y;
        if (length < 10)
        {
            AnimationValue();
        }
    }

The AnimationValue will begin the animation.
    private void AnimationValue()
    {
        var storyboard = new Storyboard();

        var animation = new DoubleAnimation
        {
            From = _lastValue,
            To = Value,
            Duration = TimeSpan.FromSeconds(2),
            EasingFunction = new CubicEase(),
            EnableDependentAnimation = true
        };

        Storyboard.SetTarget(animation, Slider);
        Storyboard.SetTargetProperty(animation, "Value");

        storyboard.BeginTime = TimeSpan.Zero;
        storyboard.Children.Add(animation);

        storyboard.Begin();

        _storyboard = storyboard;
    }

You can custom the Duration and EasingFunction to change the time.
All code in github
If you can read Chinese, please read my blog because my English is very poor, I am worried that I can't tell you exactly what I mean.


text:
Q: Location and time of impact for a moving point and a moving line segment (Continuous Collision Detection) I am working on a 2D collider system that breaks up shapes into one possible primitive: impenetrable segments that are defined by two points. To provide collision detection for this system, I am using a static collision detection approach that calculates the distance between the edge of one segment and the currently handled segment (point/line distance) once every frame. If the distance is too small, a collision is triggered during that frame. This works fine but has the known problem of tunneling if one or more bodies exhibit high speeds. So I am tinkering with alternatives.
Now I want to introduce continuous collision detection (CCD) that operates on dynamic points / dynamic segments. My problem is: I don't exactly know how. I do know how to do continuous collision between two moving points, a moving point and a static segment but not how to do CCD between a moving point (defined by point P) and a moving segment (defined by points U and V, both can move completely freely).
illustration of problem
I have seen similar questions beeing asked on SO and other platforms, but not with these exact requirements:

*

*both point and segment are moving

*segment can be rotating and stretching (because U and V are moving freely)

*collision time and collision point need to be found accurately between two frames (CCD, no static collision test)

*I prefer a mathematically perfect solutiuon, if possible (no iterative approximation algorithms, swept volumes)

*note: the swept line shape will not always be a convex polygon, because of the freedom of the U,V points (see image)

*note: testing for a collision with the swept volume test is inaccurate because a collision point with the polygon does not mean a collision point in the actual movement (see image, the point will have left the polygon once the actual segment has crossed the trajectory of the point)

So far I came up with the following approach, given:

*

*sP (P at start of frame),

*eP (P at end of frame),

*sU (U at start of frame),

*eU (U at end of frame),

*sV (V at start of frame),

*eV (V at end of frame)

Question: Will they collide? If yes, when and where?
To answer the question of "if", I found this paper to be useful: https://www.cs.ubc.ca/~rbridson/docs/brochu-siggraph2012-ccd.pdf (section 3.1) but I could not derive the answers to "when" and "where". I also found an alternative explanation of the problem here: http://15462.courses.cs.cmu.edu/fall2018/article/13 (3rd Question)
Solution:
Model temporal trajectory of each point during a frame as linear movement (line trajectory for 0 <= t <= 1)

*

*P(t) = sP * (1 - t) + eP * t

*U(t) = sU * (1 - t) + eU * t

*V(t) = sV * (1 - t) + eV * t
(0 <= a <= 1 represents a location on the segment defined by U and V):

*

*UV(a, t) = U(t) * (1 - a) +  V(t) * a
Model collision by equating point and segment equations:

*

*P(t) = UV(a, t)

*P(t) = U(t) * (1 - a) + V(t) * a
Derive a function for the vector from point P to a point on the segment (see picture of F):

*

*F(a, t) = P(t) - (1 - a) * U(t) - a * V(t)
To now find a collision, one needs to find a and t, so that F(a, t) = (0, 0) and a,t in [0, 1]. This can be modeled as a root finding problem with 2 variables.
Insert the temporal trajectory equations into F(a, t):

*

*F(a, t) = (sP * (1 - t) + eP * t) - (1 - a) * (sU * (1 - t) + eU * t) - a * (sV * (1 - t) + eV * t)
Separate the temporal trajectory equations by dimension (x and y):

*

*Fx(a, t) = (sP.x * (1 - t) + eP.x * t) - (1 - a) * (sU.x * (1 - t) + eU.x * t) - a * (sV.x * (1 - t) + eV.x * t)

*Fy(a, t) = (sP.y * (1 - t) + eP.y * t) - (1 - a) * (sU.y * (1 - t) + eU.y * t) - a * (sV.y * (1 - t) + eV.y * t)
Now we have two equations and two variables that we want to solve for (Fx, Fy and a, t respectively), so we should be able to use a solver to get a and t to only then check if they lie within [0, 1].. right?
When I plug this into Python sympy to solve:
from sympy import symbols, Eq, solve, nsolve

def main():

    sxP = symbols("sxP")
    syP = symbols("syP")
    exP = symbols("exP")
    eyP = symbols("eyP")

    sxU = symbols("sxU")
    syU = symbols("syU")
    exU = symbols("exU")
    eyU = symbols("eyU")

    sxV = symbols("sxV")
    syV = symbols("syV")
    exV = symbols("exV")
    eyV = symbols("eyV")

    a = symbols("a")
    t = symbols("t")

    eq1 = Eq((sxP * (1 - t) + exP * t) - (1 - a) * (sxU * (1 - t) + exU * t) - a * (sxV * (1 - t) + exV * t))
    eq2 = Eq((syP * (1 - t) + eyP * t) - (1 - a) * (syU * (1 - t) + eyU * t) - a * (syV * (1 - t) + eyV * t))

    sol = solve((eq1, eq2), (a, t), dict=True)

    print(sol)

if __name__ == "__main__":
    main()

I get a solution that is HUGE in size and it takes sympy like 5 minutes to evaluate.
I cannot be using such a big expression in my actual engine code and this solutions just does not seem right to me.
What I want to know is:
Am I missing something here? I think this problem seems rather easy to understand but I cannot figure out a mathematically accurate way to find a time (t) and point (a) of impact solution for dynamic points / dynamic segments. Any help is greatly appreciated, even if someone tells me that
this is not possible to do like that.

A: TLDR
I did read "...like 5 minutes to evaluate..."
No way too long, this is a real-time solution for many lines and points.
Sorry this is not a complete answer (I did not rationalize and simplify the equation) that will find the point of intercept, that I leave to you.
Also I can see several approaches to the solution as it revolves around a triangle (see image) that when flat is the solution. The approach bellow finds the point in time when the long side of the triangle is equal to the sum of the shorter two.
Solving for u (time)
This can be done as a simple quadratic with the coefficients derived from the 3 starting points, the vector over unit time of each point. Solving for u
The image below give more details.

*

*The point P is the start pos of point

*The points L1, L2 are the start points of line ends.

*The vector V1 is for the point, over unit time (along green line).

*The vectors V2,V3 are for the line ends over unit time.

*u is the unit time

*A is the point (blue), and B and C are the line end points (red)

There is (may) a point in time u where A is on the line B,C. At this point in time the length of the lines AB (as a) and AC (as c) sum to equal the length of line BC (as b) (orange line).
That means that when b - (a + c) == 0 the point is on the line. In the image the points are squared as this simplifies it a little. b2 - (a2 + c2) == 0
At the bottom of image is the equation (quadratic) in terms of u, P, L1, L2, V1, V2, V3.
That equation needs to be rearranged such that you get (???)u2 + (???)u + (???) = 0
Sorry doing that manually is very tedious and very prone to mistakes. I don`t have the tools at hand to do that nor do I use python so the math lib you are using is unknown to me. However it should be able to help you find how to calculate the coefficients for (???)u2 + (???)u + (???) = 0

Update
Ignore most of the above as I made a mistake. b - (a + c) == 0 is not the same as b2 - (a2 + c2) == 0. The first one is the one needed and that is a problem when dealing with radicals (Note that there could still be a solution using  a + bi == sqrt(a^2 + b^2) where i is the imaginary number).
Another solution
So I explored the other options.
The simplest has a slight flaw. It will return the time of intercept. However that must be validated as it will also return the time for intercepts when it intercepts the line, rather than the line segment BC
Thus when a result is found you then test it by dividing the dot product of the found point and line segment with the square of the line segments length. See  function isPointOnLine in test snippet.
To solve I use the fact that the cross product of the line BC and the vector from B to A will be 0 when the point is on the line.
Some renaming
Using the image above I renamed the variables so that it is easier for me to do all the fiddly bits.
/*
point P is  {a,b}
point L1 is  {c,d}
point L2 is  {e,f}
vector V1 is {g,h}
vector V2 is {i,j}
vector V3 is {k,l}

Thus for points A,B,C over time u    */
Ax = (a+g*u)
Ay = (b+h*u)
Bx = (c+i*u)
By = (d+j*u)
Cx = (e+k*u)
Cy = (f+l*u)

/* Vectors BA and BC at u */
Vbax = ((a+g*u)-(c+i*u))
Vbay = ((b+h*u)-(d+j*u))
Vbcx = ((e+k*u)-(c+i*u))
Vbcy = ((f+l*u)-(d+j*u))

/*
   thus Vbax * Vbcy - Vbay * Vbcx == 0 at intercept
*/

This gives the quadratic
0 = ((a+g*u)-(c+i*u)) * ((f+l*u)-(d+j*u)) - ((b+h*u)-(d+j*u)) * ((e+k*u)-(c+i*u))

Rearranging we get
0 = -((i*l)-(h*k)+g*l+i*h+(i+k)*j-(g+i)*j)*u* u -(d*g-c*l-k*b-h*e+l*a+g*f+i*b+c*h+(i+k)*d+(c+e)*j-((f+d)*i)-((a+c)*j))*u +(c+e)*d-((a+c)*d)+a*f-(c*f)-(b*e)+c*b

The coefficients are thus
 A = -((i*l)-(h*k)+g*l+i*h+(i+k)*j-(g+i)*j)
 B = -(d*g-c*l-k*b-h*e+l*a+g*f+i*b+c*h+(i+k)*d+(c+e)*j-((f+d)*i)-((a+c)*j))
 C = (c+e)*d-((a+c)*d)+a*f-(c*f)-(b*e)+c*b

We can solve using the quadratic formula (see image top right).
Note that there could be two solutions. In the example I ignored the second solution. However as the first may not be on the line segment you need to keep the second solution if within the range 0 <= u <= 1 just in case the first fails. You also need to validate that result.
Testing
To avoid errors I had to test the solution
Below is a snippet that generates a random random pair of lines and then generate random lines until an intercept is found.
The functions of interest are

*

*movingLineVPoint which return the unit time of first intercept if any.

*isPointOnLine to validate the result.

const ctx = canvas.getContext("2d");
canvas.addEventListener("click",test);
const W = 256, H = W, D = (W ** 2 * 2) ** 0.5;
canvas.width  = W; canvas.height = H;
const rand = (m, M) => Math.random() * (M - m) + m;
const Tests = 300;
var line1, line2, path, count = 0;
setTimeout(test, 0);

// creating P point L line
const P = (x,y) => ({x,y,get arr() {return [this.x, this.y]}});
const L = (l1, l2) => ({l1,l2,vec: P(l2.x - l1.x, l2.y - l1.y), get arr() {return [this.l1, this.l2]}});
const randLine = () => L(P(rand(0, W), rand(0, H)), P(rand(0, W), rand(0, H)));
const isPointOnLine = (p, l) =>  {
    const x = p.x - l.l1.x;
    const y = p.y - l.l1.y;
    const u = (l.vec.x * x + l.vec.y * y) / (l.vec.x * l.vec.x + l.vec.y * l.vec.y);
    return u >= 0 && u <= 1;
}
// See answer illustration for names
// arguments in order Px,Py,L1x,l1y,l2x,l2y,V1x,V1y,V2x,V2y,V3x,V3y
function movingLineVPoint(a,b, c,d, e,f, g,h, i,j, k,l) {
    var A = -(i*l)-(h*k)+g*l+i*h+(i+k)*j-(g+i)*j;
    var B = -d*g-c*l-k*b-h*e+l*a+g*f+i*b+c*h+(i+k)*d+(c+e)*j-((f+d)*i)-((a+c)*j)
    var C = +(c+e)*d-((a+c)*d)+a*f-(c*f)-(b*e)+c*b

    // Find roots if any. Could be up to 2
    // Using the smallest root >= 0 and <= 1
    var u, D, u1, u2;
    // if A is tiny we can ignore
    if (Math.abs(A) < 1e-6) {
        if (B !== 0) {
            u = -C / B;
            if (u < 0 || u > 1) { return }  // !!!!  no solution  !!!!
        } else { return }                   // !!!!  no solution  !!!!
    } else {
        B /= A;
        D = B * B - 4 * (C / A);
        if (D > 0) {
            D **= 0.5;
            u1 = 0.5 * (-B + D);
            u2 = 0.5 * (-B - D);
            if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1))  { return }  // !!!!  no solution  !!!!
            if (u1 < 0 || u1 > 1) { u = u2 }        // is first out of range
            else if (u2 < 0 || u2 > 1) { u = u1 }   // is second out of range
            else if (u1 < u2) { u = u1 }            // first is smallest
            else { u = u2 }
        } else if (D === 0) {
            u = 0.5 * -B;
            if (u < 0 || u > 1)  { return }  // !!!!  no solution  !!!!
        } else { return }                    // !!!!  no solution  !!!!
    }
    return u;
}

function test() {
   if (count> 0) { return }
   line1 = randLine();
   line2 = randLine();
   count = Tests
   subTest();
}
function subTest() {
   path = randLine()
   ctx.clearRect(0,0,W,H);
   drawLines();
   const u = movingLineVPoint(
       path.l1.x, path.l1.y,
       line1.l1.x, line1.l1.y,
       line2.l1.x, line2.l1.y,
       path.vec.x, path.vec.y,
       line1.vec.x, line1.vec.y,
       line2.vec.x, line2.vec.y
   );

   if (u !== undefined) { // intercept found maybe
      pointAt = P(path.l1.x + path.vec.x * u, path.l1.y + path.vec.y * u);
      lineAt = L(
          P(line1.l1.x + line1.vec.x * u, line1.l1.y + line1.vec.y * u),
          P(line2.l1.x + line2.vec.x * u, line2.l1.y + line2.vec.y * u)
      );
      const isOn = isPointOnLine(pointAt, lineAt);
      if (isOn) {
          drawResult(pointAt, lineAt);
          count = 0;
          info.textContent = "Found at: u= " + u.toFixed(4) + ". Click for another";
          return;
      }
   }
   setTimeout((--count < 0 ? test : subTest), 18);
}

function drawLine(line, col = "#000", lw = 1) {
    ctx.lineWidth = lw;
    ctx.strokeStyle = col;
    ctx.beginPath();
    ctx.lineTo(...line.l1.arr);
    ctx.lineTo(...line.l2.arr);
    ctx.stroke();
}
function markPoint(p, size = 3, col = "#000", lw = 1) {
    ctx.lineWidth = lw;
    ctx.strokeStyle = col;
    ctx.beginPath();
    ctx.arc(...p.arr, size, 0, Math.PI * 2);
    ctx.stroke();
}
function drawLines() {
   drawLine(line1);
   drawLine(line2);
   markPoint(line1.l1);
   markPoint(line2.l1);
   drawLine(path, "#0B0", 1);
   markPoint(path.l1, 2, "#0B0", 2);
}
function drawResult(pointAt, lineAt) {
   ctx.clearRect(0,0,W,H);
   drawLines();
   markPoint(lineAt.l1, 2, "red", 1.5);
   markPoint(lineAt.l2, 2, "red", 1.5);
   markPoint(pointAt, 2, "blue", 3);
   drawLine(lineAt, "#BA0", 2);
}
div {position: absolute; top: 10px; left: 12px}
canvas {border: 2px solid black}
<canvas id="canvas" width="1024" height="1024"></canvas>

Click to start

A: There are two parts of @Blindman67's solution I don't understand:

*

*Solving for  b^2 - (a^2 + c^2) = 0 instead of sqrt(b^2)-(sqrt(a^2)+sqrt(b^2)) = 0

*The returned timestamp being clamped in the range [0,1]
Maybe I'm missing something obvious, but in any case, I designed a solution that addresses these concerns:

*

*All quadratic terms are solved for, not just one

*The returned time stamp has no limits

*sqrt(b^2)-(sqrt(a^2)+sqrt(b^2)) = 0 is solved for, instead of  b^2 - (a^2 + c^2) = 0
Feel free to recommend ways this could be optimized:
# pnt, crt_1, and crt_2 are points, each with x,y and dx,dy attributes
# returns a list of timestamps for which pnt is on the segment
# whose endpoints are crt_1 and crt_2
def colinear_points_collision(pnt, crt_1, crt_2):
    a, b, c, d = pnt.x, pnt.y, pnt.dx, pnt.dy
    e, f, g, h = crt_1.x, crt_1.y, crt_1.dx, crt_1.dy
    i, j, k, l = crt_2.x, crt_2.y, crt_2.dx, crt_2.dy

    m = a - e
    n = c - g
    o = b - f
    p = d - h
    q = a - i
    r = c - k
    s = b - j
    u = d - l
    v = e - i
    w = g - k
    x = f - j
    y = h - l

    # Left-hand expansion
    r1 = n * n + p * p
    r2 = 2 * o * p + 2 * m * n
    r3 = m * m + o * o
    r4 = r * r + u * u
    r5 = 2 * q * r + 2 * s * u
    r6 = q * q + s * s

    coef_a = 4 * r1 * r4  # t^4 coefficient
    coef_b = 4 * (r1 * r5 + r2 * r4)  # t^3 coefficient
    coef_c = 4 * (r1 * r6 + r2 * r5 + r3 * r4)  # t^2 coefficient
    coef_d = 4 * (r2 * r6 + r3 * r5)  # t coefficient
    coef_e = 4 * r3 * r6  # constant

    # Right-hand expansion
    q1 = (w * w + y * y - n * n - p * p - r * r - u * u)
    q2 = 2 * (v * w + x * y - m * n - o * p - q * r - s * u)
    q3 = v * v + x * x - m * m - o * o - q * q - s * s

    coef1 = q1 * q1  # t^4 coefficient
    coef2 = 2 * q1 * q2  # t^3 coefficient
    coef3 = 2 * q1 * q3 + q2 * q2  # t^2 coefficient
    coef4 = 2 * q2 * q3  # t coefficient
    coef5 = q3 * q3  # constant

    # Moves all the coefficients onto one side of the equation to get
    # at^4 + bt^3 + ct^2 + dt + e
    # solve for possible values of t
    p = np.array([coef1 - coef_a, coef2 - coef_b, coef3 - coef_c, coef4 - coef_d, coef5 - coef_e])

    def fun(x):
        return p[0] * x**4 + p[1] * x**3 + p[2] * x**2 + p[3] * x + p[4]

    # could use np.root, but I found this to be more numerically stable
    sol = optimize.root(fun, [0, 0], tol=0.002)
    r = sol.x

    uniques = np.unique(np.round(np.real(r[np.isreal(r)]), 4))
    final = []

    for r in uniques[uniques > 0]:
        if point_between(e + g * r, f + h * r, i + k * r, j + l * r, a + c * r, b + d * r):
            final.append(r)

    return np.array(final)

# Returns true if the point (px,py) is between the endpoints
# of the line segment whose endpoints lay at (ax,ay) and (bx,by)
def point_between(ax, ay, bx, by, px, py):
    # colinear already checked above, this checks between the other two.
    return (min(ax, bx) <= px <= max(ax, bx) or abs(ax - bx) < 0.001) and (min(ay, by) <= py <= max(ay, by) or abs(ay - by) < 0.001)

An example (L1 and L2 are endpoints of line):
P = (0,0) with velocity (0, +1)
L1 = (-1,2) with velocity (0, -1)
L2 = (1,2) with velocity (0, -1)
The returned result would be t=1, because after 1 time step, P will be one unit higher, and both endpoints of the line will each be one unit lower, therefore, the point intersects the segment at t=1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ajax to read from form I'm writing a store system for my game,
it worked quite well until I found out that it only takes the amount of first entered Item.
function pbuy(buyitem) {
 var amountc = "amount-"+buyitem,
 var amount = $("#"+amountc+"").val();
   $.ajax({
   type: "POST",
   url: "store2.php",
   data: "buyitem="+ buyitem+"&amount="+amount,
   success: function(resp){
   document.getElementById('ajaxDiv').innerHTML =  resp;

   },
   error: function(e){
     alert('Error: ' + e);
   }
 });
}

I'm trying to give it it the Id of the form like so:
function pbuy(buyitem) { var amountc = "amount-"+buyitem, var amount = $("#"+amountc+"").val();

But nothing happens.
The code the creation of the forms is:

        <?PHP echo $itemstore->itemname;?>

        Price:<?PHP echo $itemstore->newprice;?>
        <form  method="post">
            <input type='text' id='amount-<?PHP echo $row;?>)' />
            <input name="itembid" type="button" onclick="pbuy(<?PHP echo $row;?>)"  value="Buy" />
        </form>

If I hardcode the amount in the ajax function it all runs fine like it should.

A: Did you checked the response of the AJAX request?

A: You're getting a javascript error before the AJAX-request is being sent since you are defining your amountc and amount variables separated by a comma. Either do
 var amountc = "amount-"+buyitem;
 var amount = $("#"+amountc+"").val();

semicolon separated, or keep the comma and skip the second var
 var amountc = "amount-"+buyitem,
 amount = $("#"+amountc+"").val();


text:
Q: If you roll 8 standard six-sided dice, what's the probability that you get at least one 3 or at least one 1? What is the probability that on 8 rolls of dice, there will be at least one '3' or one '1' showing up?
My attempt was:
$\frac{{8 \choose 1} * 6^7 + {8 \choose 1} * 6^7}{6^8}$
Because 7 dice have 6 possible results, there are $6^7$ variations. The last one has to have the result 3. There are ${8 \choose 1} = 8$ ways to combine it with the other results. Becuase the question asks for a '3' or a '1', I added the same calculation for the result '1'.
To get the probability, I divided everything by the total number of variations, which is $6^8$.
Indeed, my result is bigger than $1$.

A: You want the probability for "at least" not that for "exactly".
Your calculation also over counts the intersections; where you have more than one result of $3$ or $1$ among the eight results.

Let $X_n$ be the count for showing a result of $n$ among eight rolls of a die.   This is easiest evaluated by way of the complement.
$$\mathsf P(X_3\geq 1\cup X_1\geq 1) = 1-\mathsf P(X_3=0\cap X_1=0) \\ = 1-\frac{4^8}{6^8}$$


text:
Q: Can another account share its Playstation Plus membership to play my Plus games again? I received some Playstation Plus free games during my subscription, but my subscription has since expired and I am unable to play them. If a friend with Playstation Plus signs into my console and activates it as their primary console, can I play the games I received for free as a Playstation Plus subscriber from my account again?

A: If your friend activates your PS4 as their primary and they have PlayStation Plus while you do not, then you can play whatever games they have licenses for (what is in their Library).
If you have games that you downloaded as free PS+ games during your PS+ subscription that your friend also received during that time (e.g. your friend also had a PS+ subscription and was able to receive that game for free) or your friend simply has bought that game, then yes, you will regain access to it, as the primary user's licenses are shared with all secondary accounts on the console.
However, if your friend does not have a license for that game, then you will not be able to play it, regardless of whether or not your friend has PS+.

tl;dr: If your friend owns the games in question, then yes. Otherwise, no.


text:
Q: Refused to frame 'https://www.youtube.com/embed/xxxxx because it violates Content Security Policy directive I am trying to  embed a youtube video in my  page and see an error like this in the console:
Refused to frame 'https://www.youtube.com/embed/<~videoId~>?showinfo=0'
because it violates the following Content Security Policy directive:
"default-src 'self'". Note that 'frame-src' was not explicitly set, so
'default-src' is used as a fallback.

This seems clear enough, so  after a bit of reading I found two ways of setting an appropriate content security policy.

*

*by setting a response header (which I did in my  web.config file):

<httpProtocol>
  <customHeaders>
    <add name="Content-Security-Policy" value="frame-src https://www.youtube.com/" />
  </customHeaders>
</httpProtocol>

*with a meta tag in the page header:

<meta http-equiv="Content-Security-Policy" content="frame-src https://www.youtube.com">

Neither of these methods worked; Chrome keeps on giving the same result in the console (even though I have done what I thought the message meant and set the requested content security policy). The iframe remains blocked and empty.
There are lots of questions and answers about content security policies but I can't find any with this combination of circumstances.
My  site is running on https and my iframe and embedded video looks like this:

<div id="videoContainer">
    <iframe src="https://www.youtube.com/embed/<~videoId~>?showinfo=0"
            frameborder="0"
            allowfullscreen>
    </iframe>
</div>

The problem only shows up for Chrome and FFirefox; Internet Explorer 11 is fine without a content security policy.
Thanks in advance for any advice.

A: I found the answer to this myself. I was trying to embed a video on the login page of an Identity Server 3 installation and this made a bigger difference than I thought it would.
the Chrome network tab contained a csp report from Identity Server, from which clue a quick search revealed the answer here in the Identity Server documentation:
    https://identityserver.github.io/Documentation/docsv2/advanced/csp.html
Adding a cspOptions entry to the identity server options fixed the issue entirelt without the need for me to add any of my own custom headers:
var options = new IdentityServerOptions
{
    SigningCertificate = Certificate.Load(),
    Factory = factory,
    RequireSsl = true,
    CspOptions = new CspOptions() {FrameSrc = "https://www.youtube.com"},
              ...
              ...
 }


text:
Q: Can I show an image with BIOS interrupts or assembly? I am trying write a simple bootloader, and I want to show an image when my bootloader starts. How can I do this?
I am using assembly with nasm assembler.

A: Depends on what kind of video mode you want use and what to do with the picture. But I think the resources below by almost 100% to answer your questions and create new ones).
PC Games Programmers Encyclopedia book: archive Zip
PC Games Programmers Encyclopedia part source code
File Description PCGPE
Good Luck!


text:
Q: QT - slot preemption / interrupt I'm trying to write an app for testing ST board via serial port and I'm currently facing the following issue. (The code below is just a simplification of a problem.)
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , m_button(new QPushButton(this))
    , m_timer(new QTimer(this))
{
    m_timer->setSingleShot(true);
    connect(m_button, &QPushButton::released, this, &Widget::RunTest);
    connect(m_timer, &QTimer::timeout, this, &Widget::OnTimeout);
}

void Widget::RunTest()
{
    qDebug() << "Start test";

    m_timer->start(1000);
    while (m_timeout != true);

    qDebug() << "Start end";
}

void Widget::OnTimeout()
{
    qDebug() << "Timeout";
    m_timeout = true;
}

I want to have a seprate class for gathering and running tests. The tests are triggered by clicking on a button. Some tests will have to send data via serial port and wait for the reply. I would like to be able to implement a timeout feature (if board doesn't reply then finish test with failure). However I the app is waiting for the m_timeout flag indefinitely. So my question is: Is there any signal/slot mechanism similar to interrupt preemption? If no how sush problems are solved in Qt? Shall I create seprate QTimer object and run it in separate thread?


text:
Q: ML Pipeline on AWS SageMaker: How to create long-running query/preprocessing tasks I'm a software engineer transitioning toward machine learning engineering, but need some assistance.
I'm currently using AWS Lambda and Step Functions to run query and preprocessing jobs for my ML pipeline, but am restrained by Lambda's 15m runtime limitation.
We're a strictly AWS shop, so I'm kind of stuck with SageMaker and other AWS tools for the time being. Later on we'll consider experimenting with something like Kubeflow if it looks advantageous enough.
My current process

*

*I have my data scientists write python scripts (in a git repo) for the query and preprocessing steps of a model, and deploy them (via Terraform) as Lambda functions, then use Step Functions to sequence the ML Pipeline steps as a DAG (query -> preprocess -> train -> deploy)

*The Query lambda pulls data from our data warehouse (Redshift), and writes the unprocessed dataset to S3

*The Preprocessing lambda loads the unprocessed dataset from S3, manipulates it as needed, and writes it as training & validation datasets to a different S3 location

*The Train and Deploy tasks use the SageMaker python api to train and deploy the models as SageMaker Endpoints

Do I need to be using Glue and SageMaker Processing jobs? From what I can tell, Glue seems more targeted towards ETLs than for writing to S3, and SageMaker Processing jobs seem a bit more complex to deploy to than Lambda.

A: There is a solution that just came out for long running actions in Redshift - Redshift Data API.  https://aws.amazon.com/about-aws/whats-new/2020/09/announcing-data-api-for-amazon-redshift/
This allows Lambdas in a Step function to issue a set of SQL to Redshift and poll to see when the SQL is done.  Now the run time of your Lambda is only as long as it needed to launch the SQL.
As for the processing steps - I'd recommend doing as much of the processing inside of Redshift before unloading the data to S3 (I hope you are not pulling lots of data through a select statement).  This will be much faster than processing in Lambda and can benefit from Data API as well.  Now there will likely be some processing steps that you cannot do in Redshift and Lambda is a good option.  One additional benefit of UNLOAD is that you can set the output file size.  This way you can launch a Lambda per file of the output and then you have many, shorter running Lambdas.
You could attempt to break up the work and have many Lambdas running in series but processing large amounts of data at once is not a strength of Lambda. Being able to do this will depend on the data processing you are doing.
You could use Glue for this but this is likely complete overkill, a whole new service to learn, and since it is an EMR wrapper it can get costly.  To be honest Glue is not my favorite AWS service as it only does the most basic things easily and anything even slightly complex becomes a battle. So if this is a tool you know and like go for it.


text:
Q: Direct image sheaf and tensor product (is the projection formula an isomorphism?) Assume we have two "nice" schemes $X$ and $Y$ over $k=\mathbb{C}$, a finite flat map $f:X\rightarrow Y$ and a k-algbera $A$. Then we get an induced finite flat map $f_A:X\times_k A \rightarrow Y\times_k A$.
Now given an $O_{X\times_k A}$-module $M$, flat over $A$ and an $A$-module $N$.
Is $(f_A)_{*}(M\otimes_A N)=((f_A)_{*}M)\otimes_A N$?
My idea was to use the projection formula: let $\pi:Y\times_k A \rightarrow A$ and $\phi:X\times_k A \rightarrow A$ be the structure morphisms, i.e. $\phi=\pi\circ f_A$. Then: $M\otimes_A N=M\otimes_{O_{X\times_k A}} \phi^{*} \tilde{N}$, where $\tilde{N}$ is the sheaf associated to $N$ on Spec(A). But $\phi^{\*}=(f_A)^{\*}\circ\pi^{\*}$, so we get $(f_A)_{*}(M\otimes_A N)=(f_A)_{*}(M\otimes_{O_{X\times_k A}} (f_A)^{\*}(\pi^{\*}\tilde{N}))$.
Now if the projection formula was an isomorphism in this case the last module would be $(f_A)_{*}(M)\otimes_{O_{Y\times_k A}} \pi^{\*}\tilde{N}$, which is nothing else but $((f_A)_{*}M)\otimes_{A} N$.
So is the projection formula an isomorphism in this case?

A: Most of this becomes obvious when translated using affine charts. For the first question, use a presentation of $N$ and the fact that $(f_A)_*$ is exact to reduce to the case $N=A$. The projection formula is stated in EGA I (new edition), Corollaire 9.3.9.


text:
Q: How to recognize this simple capcha? alt text http://internationalpropertiesregistry.com/Server/showFile.php?file=%2FUpload%2F02468.gif358455ebc982cb93b98a258fc4d6ee60.gif
Is there a simple solution in MATLAB?

A: Easy answer:  NOPE

A: For a simple one like that you can probably just run a median filter and ocr.
A median filter will, for every pixel in the image, look at the area around it, usually a 3x3 or 5x5 pixel area, determine the median pixel value in that area and set the pixel to that median value. In a block of the same colour nothing will happen, the whole area is the same colour as the pixel under consideration so the median i sthe same as the current value (or at least almost the same permitting slight colour variations. On the other hand noise pixels, i.e. a single pixel with a differently coloured area around it will simply disappear, since the median value of the area will be the colour of all the pixels around the noise pixel.
As for the ocr, or optical character recognition, I'd just use an existing program/library, it would certainly be possible to write an ocr algorithm in Matlab, but would be a much bigger exercise than writing a simple algorithm in an hour. You'd first need to read up on ocr techniques and algorithms.

A: For very simple: read the image as grayscale, threshold, clean up and run it through an ocr program.
%# read the image
img = imread('http://internationalpropertiesregistry.com/Server/showFile.php?file=%2FUpload%2F02468.gif358455ebc982cb93b98a258fc4d6ee60.gif');

%# threshold
bw = img < 150;

%# clean up
bw = bwareaopen(bw,3,4);

%# look at it - the number 8 is not so pretty, the rest looks reasonable
figure,imshow(bw)

Then, figure out whether there is an OCR program that can help, such as this one
For even simpler:
%# read the image
[img,map] = imread('http://internationalpropertiesregistry.com/Server/showFile.php?file=%2FUpload%2F02468.gif358455ebc982cb93b98a258fc4d6ee60.gif');

%# display
figure,imshow(img,map)

%# and type out the numbers. It's going to be SO much less work than writing complicated code

A: *

*Clean up the image

*Separate each character into distinct images

*Compare each character against a set of reference characters

*The best matches are the most likely original character

A: You may consult this post. I succeeded in cracking a simpler CAPTCHA with the illustrated approach.


text:
Q: Can not Parse string to DateTime in Windows Phone 7 I am trying to convert the string to DateTime. But I can not convert.
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);

The error is FormatException.
My input time format is "dd/MM/yyyy".
Please let me any idea to resolve my problem.

A: Because InvariantCulture doesn't have dd/MM/yyyy as a standard date and time format, but it has MM/dd/yyyy as a standard date and time format.
That's why it thinks your string is MM/dd/yyyy format, but since there is no 16 as a month in Gregorian calender, you get FormatException.
Instead of that, you can use DateTime.TryParseExact method to specify exact format like;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{

}

A: Given that you know your input format, you should specify it with `ParseExact:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
                                  CultureInfo.InvariantCulture);

I would always recommend being as explicit as you can be about date/time formats. It makes your intention very clear, and avoids the possibility of getting months and days the wrong way round.
As Soner has stated, CultureInfo.InvariantCulture uses MM/dd/yyyy as its short date pattern, as you can validate with:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)

As a mild plug, you might want to consider using my Noda Time project for your date/time handling - aside from anything else, that allows you to treat a date as a date, rather than as a date and time...


text:
Q: How to filter createdAt from current date to 90 days ago? I'm trying to filter the results of a listing for the last 90 days, but I don't know how to do it.
It currently looks like this:
const initialFilter = [
  {
    term: {
      createdAt: Date.now || new Date(Date.now() - 90 * 24 * 60 * 60 * 1000),
    },
  },
];

A: You can do arithmetic operations with date like < or >.
Example
const dateOne = new Date()
const dateTwo = new Date("02/01/2021")
const dateThree = new Date("01/01/2022")
const dateToCompare = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)

console.log(dateToCompare > dateTwo)
console.log(dateToCompare > dateOne)
console.log(dateToCompare > dateThree)
console.log(dateToCompare < dateThree)


text:
Q: Can't create a new OpenSSL key I want to learn OpenSSL but I'm just getting boolean false when I am trying to use this code:
$config = array('private_key_bits' => 512);
$privKey = openssl_pkey_new($config);

var_dump($privKey);

The OpenSSL extension is activated on my server. Have I missed something?

A: Use openssl_error_string() after your openssl_* function is called:
while($e = openssl_error_string() ) {
    print_r($e."\n");
}

On my Windows it outputs:
error:02001003:system library:fopen:No such process
error:2006D080:BIO routines:BIO_new_file:no such file
error:0E064002:configuration file routines:CONF_load:system lib
error:02001003:system library:fopen:No such process
error:2006D080:BIO routines:BIO_new_file:no such file
error:0E064002:configuration file routines:CONF_load:system lib

See the first note at this function openssl_pkey_new():

Note: You need to have a valid openssl.cnf installed for this function
  to operate correctly. See the notes under the installation section for
  more information.


text:
Q: Handling collections with mixed POJOS, with different handler for each POJO I'm trying to find an elegant OOP solution for the following problem.
Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).
A basic assumption is that we can't decorate the POJOs with appropriate handlers, since we don't control their generation, and receive the collection as is. Thus, any mechanism for this falls into the same trap. However, item 3 stil deals with this possibility.
There are some possible solutions, some very ugly, some more elegant but complicated:

*

*The obvious solution, and the ugliest, is using instanceOf operators to pass POJO to handler.

*A slightly better modification of 1, is to use a chain of responsibility for this, with chained dispatcher, so that new types just need a new dispatcher. However, each dispatcher stills needs instanceOf.

*Create enhanced objects, not POJOS, where each object holds a reference to its handler. This creates a coupling between POJO and our processor.

*Create (I know how to do this correctly in Java) a dispatcher service which registers handlers to the specific event class, and use generics (Typesafe container, as in effective java) to dispatch event to handler.

4 is the most elegant, but I was wondering if there are any better ideas.

A: Simplification of #4:
Use a Map to store the handler for each event class.
Map<Class, Handler> classHandlers = new HashMap<Class, Handler>();
classHandlers.put(EventA.class, new EventAHandler());
classHandlers.put(EventB.class, new EventBHandler());

Now use the class of the event to get the handler for the event.
Handler handler = classHandlers.get(event.getClass());
handler.handle(event);

Of course this requires knowledge of all possible event classes at coding time and is thus less flexible than an external event dispatcher.

A:
Assume we have a collection of POJOS, events in this case, where each POJO is possibly different class. We need to process this collection, using different rules for each POJO class (or type).

Congratulations If the classes of POJOs are stable (new class types aren't often added) you've just described the motivation for using the Visitor Pattern!
Even better, because you probably want to do different things to your collection of POJOs, you can create an AbstractBaseVisitor and extend it to handle the different things you need to do!
This will require putting a tiny wrapper around each POJO, with one wrapper class per POJO class, to add a visit() function that calls back to the Visitor.

A: I have used the solution in number 4 in this scenario and I think its a good one. I will also look for other opinion on better solution.

A: 4 is the best of the solutions you present.  #1 & 2 will be painful with a mess of instanceof's floating around.
Another solution: annotate each class with it's dispatcher method.  You won't need a central place to handle the dispatcher calls and the POJO/dispatcher won't be coupled outside of the annotation.

A: The question is actually not language agnostic at all. In some languages you could easily decorate the classes. But let's stick to Java. Even there I say "it depends".
An apparent thing we would like to do is some sort of auto-discovery of the handlers. For example, annotate your handlers with a @Handler(handles=PojoA.class) annotation, then scan for all classes annotated with @Handler (either the messy way that basically requires the class files to be loaded or using something like Scannotation).
If you are running in a context such as Spring, an even more interesting option arises. You can get all beans implementing a certain interface, such as the following:
public interface Handler<T> {
    void handle(T object);
}

and then find them in your dispatcher code:
Collection<Handler> handlers = applicationContext.getBeansofType(Handler.class).values();
for (Handler handler : handlers) {
    Method handleMethod = handler.getClass().getMethod("handle", Object.class);
    Class<?> type = handleMethod.getParameterTypes()[0];
    register(type, handler);
}

(admittedly, the code above is untested)
I realize I go out of the boundaries here. My point is that the elegance of the solution depends on your language of choice, what external tools you are willing to use and what framework you are using.


text:
Q: Can't get head around parsing nested JSON I am having a hard time trying to get my head around this here:
so I have the following JSON:
"posts": [
{
  "id": 42400,
  "type": "post",
  "url": "http://dummy.com/noticias/2014/06/senado-promulga-emenda-contra-trabalho-escravo-42400/",
  "status": "publish",
  "title": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
  "title_plain": "Lorem ipsum dolor sit amet, consectetur adipisicing elit",
  "content": "
Lorem ipsum dolor sit amet, consectetur adipisicing elit
",
  "excerpt": "
Lorem ipsum dolor sit amet, consectetur adipisicing elit
",
  "date": "2014-06-05 16:59:55",
  "modified": "2014-06-05 17:00:42",
  "author": {
    "id": 2,
    "slug": "author",
    "name": "Author",
    "first_name": "Author",
    "last_name": "",
    "nickname": "Author",
    "url": "",
    "description": ""
  },
  "thumbnail_images": {
    "full": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo.jpg",
      "width": 585,
      "height": 390
    },
    "thumbnail": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-110x110.jpg",
      "width": 110,
      "height": 110
    },
    "medium": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-230x130.jpg",
      "width": 230,
      "height": 130
    },
    "large": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-585x360.jpg",
      "width": 585,
      "height": 360
    },
    "slider-thumb": {
      "url": "http://dummy.com/wp-content/uploads/2014/06/pec-trabalho-escravo-520x390.jpg",
      "width": 520,
      "height": 390
    }
  }
},

And this is how I am parsing this JSON:
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

if (localError != nil ) {
    *error = localError;
    return nil;
}

NSMutableArray *posts = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:@"posts"];

for (NSDictionary *postDic in results) {

    Data *data = [[Data alloc] init];
    for (NSString *key in postDic) {
        if ([data respondsToSelector:NSSelectorFromString(key)]) {
            [data setValue:[postDic valueForKey:key] forKey:key];
        }
    }

    [posts addObject:data];
}

return posts;

What I can't seem to understand is how can I access the first value inside "thumbnail_images", which is "full" and then get its 'url' value.

A: The key "posts" has an NSArray for it's value, which is your variable named results. Each index of the results array can contain an array or dictionary.
thumbnail_images is at index 1, so you can get it like this NSDictionary *thumbImages = results[1];
From here on out, you can access all the nested keys you want like this. So for "full" and then "url": NSString *url = thumbImages[@"thumbnail_images"][@"full"][@"url"];

A: The JSONObjectWithData method creates an object that consists of nested NSArrays and NSDIctionarys.   To extract items of interest you have to drill down into the object, repeatedly extracting arrays and dictionaries until you reach whatever it is that you want.  Using the modern syntax for arrays and dictionaries makes this relatively easy.
Also note that the error return is only valid if the return value from JSONObjectWithData is nil.
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

if ( parsedObject == nil )
{
    *error = localError;
    return nil;
}

NSMutableArray *results = [NSMutableArray new];
NSArray *posts = parsedObject[@"posts"];

for ( NSDictionary *post in posts )
{
    NSDictionary *thumb = post[@"thumbnail_images"];
    NSDictionary *full  = thumb[@"full"];
    NSString *urlString = full[@"url"];
    NSLog( @"%@", urlString );

    [results addObject:urlString];
}

return [results copy];

A: You can check if the object is a dictionary and then traverse through it:
for (NSDictionary *postDic in results) {

Data *data = [[Data alloc] init];
for (NSString *key in postDic) {
    if ([data respondsToSelector:NSSelectorFromString(key)]) {
        if ([results[postDic] isMemberOfClass:[NSDictionary class]) {
            // At this point you will get the "full", "thumbnail", etc dictionaries
            NSDictionary *childDict = results[postDic];
            //Now you can just do the same thing once again to get the url value.
        }
        [data setValue:[postDic valueForKey:key] forKey:key];
    }
}

[posts addObject:data];
}


text:
Q: Conflict between packages in laravel I'm trying to install two packages. The passport and the auth. The Auth is because the passport requires this package, but when trying to install the passport, it says that it already finds a version but that it is not active/installed because of a conflict with another package.
I have no idea, I did some tests here, but I couldn't solve it. I really need help
I'll leave my composer.json below
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2.5|^8.0",
        "aws/aws-sdk-php": "^3.208",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^6.3",
        "kitetail/zttp": "^0.6.0",
        "laracasts/flash": "^3.2",
        "laravel/framework": "^7.29",
        "laravel/tinker": "^2.5",
        "laravel/ui": "2.4",
        "maatwebsite/excel": "^3.1",
        "timehunter/laravel-google-recaptcha-v2": "~1.0.0"
    },
    "require-dev": {
        "facade/ignition": "^2.0",
        "fakerphp/faker": "^1.9.1",
        "lucascudo/laravel-pt-br-localization": "^1.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^4.3",
        "phpunit/phpunit": "^8.5.8|^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

These are the errors/warnings you get when trying to install each package
composer require laravel/passport:
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - Root composer.json requires laravel/passport ^10.4 -> satisfiable by laravel/passport[v10.4.0, v10.4.1, 10.x-dev].
    - laravel/passport[v10.4.0, ..., 10.x-dev] require illuminate/auth ^8.37|^9.0 -> found illuminate/auth[v8.37.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require laravel/passport:*" to figure out if any version is installable, or "composer require laravel/passport:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

composer require illuminate/auth ^8.37:
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - Root composer.json requires illuminate/auth 8.37, found illuminate/auth[v8.37.0] but these were not loaded, likely because it conflicts with another require.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.


text:
Q: Google Spreadsheet ImportXML Error: Imported XML content cannot be parsed This function seems to work in general, but in this case:
URL: http://www.londonstockexchange.com/exchange/prices/stocks/summary/fundamentals.html?fourWayKey=GB00B1YW4409GBGBXSET1
XPATH: //*[@id='leftTable']/table[1]/tbody/tr[23]/td[2] (although it doesn't work with any XPATH).
I get the error
Error: Imported XML content cannot be parsed.

I think the problem is with the page itself, but I cannot see what Google is seeing (or can I?) Any pointers would be much appreciated.

A: Incredibly odd, but the general solution for problems regarding the IMPORTXML function in the new version of Google Sheets is - use the older version.
There, if the following formula is used in a cell:
=IMPORTXML("http://www.londonstockexchange.com/exchange/prices/stocks/summary/fundamentals.html?fourWayKey=GB00B1YW4409GBGBXSET1","//*[@id='leftTable']/table[1]/tbody/tr[23]/td[2]")

The displayed result is:
8.10p

Which is correct, I assume.

A: Most ImportXML errors today are because the page is using Javascript.
If you use Developer Tools and inspect the site in Chrome, you find the HTML which was rendered into the DOM by the Javascript. BUT if you look at the the page source, you won't find the data.
Google Sheets doesn't act as a client browser so there is nowhere for the JS to execute.
This is why the copied XML path from Inspect Element into Google Sheets IMPORTXML errors out.


text:
Q: Azure SDK v2.7 diagnostics issue is preventing publish/package I've recently upgraded an Azure cloud service with a web role and worker role to v2.7 of the SDK.
Debugging locally works great.
When I try to publish from within VS 2015 Community, the process fails with an error in the build output:
6>Done building project "Cloud.ccproj" -- FAILED.
6>
6>Build FAILED.
========== Build: 5 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Publish: 0 succeeded, 1 failed, 0 skipped ==========

Dropping down to msbuild I can see more verbose output and notice the following:
Failed to produce diagnostics extension's config for Cloud.WebRoleContent\diagnostics.wadcfgx.
Error : Value cannot be null. Parameter name: input

Removing the diagnostics.wadcfgx files from the web and worker roles actually solves this issue and allows me to publish, however I'd prefer to keep my diagnostics.
Adding them back in via the UI lands me at the same error as above.
Has anyone else come across this?

A: I don't remember the exact error we got but recently we had to add a storage account for diagnostics where previously we didn't. In your ServiceConfiguration you need a line like
  <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="...."/>

A: I just had this same issue, but I was not missing the settings in Batavia's solution. I didn't see any other posts with the solution I found, so here you go:
The issue was that there was a file called "diagnostics.wadcfgx" referenced in the csproj of the offending project that was not present in the folder. Removing this item from the proj file resolved the issue.


text:
Q: Как узнать остаток от деления? Мне надо с помощью побитовых операций узнать, равен ли остаток от деления на 9 нулю.
Как мне это реализовать, можете посоветовать?

A: Интересные вам задачки дают. Полное решение не дам, это не спортивно, но идею и некоторые заготовки покажу. В основе лежит тот факт, что результат операции XOR эквивалентен результату полусумматора и остается только корректно учесть бит переноса. Разумеется, на аппаратном уровне все реализуется проще на последовательной цепочке полных сумматоров, так что тут только имитация работы такой схемы.
//сумматор
int Summ(int a, int b)
{
    int t;
    do
    {
        t = a & b; //получаем поразрядные биты переносов
        a ^= b;    //получаем поразрядные биты полусумм
        b = t << 1;//сдвигаем биты переносов влево на их потенциальное место
    }
    //продолжаем пока есть хоть один бит переноса
    while (t != 0);
    return a;
}

//двоичная инверсия
int BinNegate(int a)
{
    return a ^ -1;
}

//арифметическая инверсия
int MathNegate(int a)
{
    return Summ(BinNegate(a), 1);
}

Дальше уже сами. Двоичное деление в столбик достаточно простое, алгоритм находится элементарно, но на крайний случай можно и просто циклом вычитания обойтись, ну а сделать из сложения вычитание предоставленными средствами элементарно. Двоичное сравнение это вычитание и проверка знакового разряда. К сожалению обойтись без операции сравнения с нулем не получится, процессоры для этого используют специальный флаг в регистре флагов, который выставляется во время выполнения арифметической операции, а в C# не поддерживается соглашение "все что не ноль - истина" для условных операторов, но, например, в C/C++ это соглашение поддерживается и там можно обойтись без сравнения с нулем. Понятно, что задачка преследует исключительно академический интерес, но она интересная и ее можно решить используя только битовые операции и операции на (не)равенство нулю, без применения других операций прямого сравнения чисел и любых арифметических операций.


text:
Q: Length of each list object - Java I have a list:
List list = new ArrayList();
list.add(23.23);
list.add(234);
list.add("abcd");

I am iterating it like:
for(Object o : list){
    // System.out.println(o.getClass());
    if(o.getClass().equals(Integer.class)){

    }
    else if(o.getClass().equals(Double.class)){

    }
    else if(o.getClass().equals(String.class)){

    }
}

How to get the length of each object?
Expected output:
4
3
4

A: If primitives like integer, double are passed, they are auto-boxed to their wrappers like Integer, Double. And they don't have length attribute. Yes String has length attribute and a method with the same name.
So,

*

*Use Generics .

*If you want to find length of int / double, convert them to a String using String.valueOf() and then call length().

A: As TheLostMind said :
for(Object o : list){
    System.out.println(String.valueOf(o).length());
}


text:
Q: How can I display the completion state of an activity without refreshing the page? Activities in a course have checkboxes on the right where they can tick them as they finish an activity or the platform does it automatically if certain conditions are met. When it's set to automatic, the webpage needs to refresh before displaying the checks on each completed activity. This presents a problem in that if an activity is a video set to play in a pop-up video, which is the case of my platform, the users won't know they have finished an activity until they reload said page.
All the documentation I've read suggests that there isn't a way of accomplishing this with Moodle's functionality, it's a limitation of the system. Still, I ask in case anyone here has an idea on how to solve this.
Some of the ideas I have are to simply set all videos to embed, meaning the user will have to navigate between pages circumventing the problem. Another is to set the platform to refresh every set amount of time but this is evidently not a great solution.
Appreciate any help.

A: If I had to do it fast and dirty, I would write some custom JS that, on opening the popup, requests via ajax an updated version of the current page (GET against the current URL) and replaces the specific check with the updated one via ajax content replacement and some jquery selectors magic, then I would get sure that the event handlers that hang on those replaced checks are still working, otherwise I would freshly re-set them.
An alternative more elegant way would be to write a web service (external function as it is called in Moodle) that checks for the completion of the activity after the popup has been opened (just once or periodically) and then replaces just the check with the one that represents the updated completion state (then, again, see if the check event handlers still work after the replacement).


text:
Q: Maven DependencyResoulutionException Error I am trying to run apache maven project but encounter with the following problem.
When I try to run mvn clean install, it shows this error.
[ERROR] Failed to execute goal on project admin: Could not resolve dependencies for project
com.fengmaotec:admin:jar:0.0.1-SNAPSHOT:
The following artifacts could not be resolved:
nl.jworks.markdown_to_asciidoc:markdown_to_asciidoc:jar:1.0, ch.netzwerg:paleo-core:jar:0.11.0:
Failure to find nl.jworks.markdown_to_asciidoc:markdown_to_asciidoc:jar:1.0 in
https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be
reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

pom.xml of my project.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.fengmaotec</groupId>
    <artifactId>admin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>admin</name>
    <description>fengmaotec admin project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mybatis.spring.boot.starter.version>2.1.2</mybatis.spring.boot.starter.version>
        <mybatis.plus.boot.starter.version>3.3.1</mybatis.plus.boot.starter.version>
        <swagger.version>2.9.2</swagger.version>
        <fastjson.version>1.2.68</fastjson.version>
        <freemarker.version>2.3.29</freemarker.version>
        <ECharts.version>4.7.0.1</ECharts.version>
        <!-- 打包跳过测试 -->
        <skipTests>true</skipTests>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.spring.boot.starter.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--常用工具类 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis.plus.boot.starter.version}</version>
        </dependency>

        <!-- swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--防止进入swagger页面报类型转换错误,排除2.9.2中的引用,手动增加1.5.21版本-->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

        <!-- swagger2-UI-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <!--阿里 FastJson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <!--代码生成器依赖-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
            <scope>provided</scope>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--    安全框架    -->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-security</artifactId>-->
<!--        </dependency>-->

        <!-- https://mvnrepository.com/artifact/io.github.swagger2markup/swagger2markup -->
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.3</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>1.2.0</version>
                <configuration>
                    <!--此处端口一定要是当前项目启动所用的端口-->
                    <swaggerInput>http://localhost:8080/v2/api-docs?group=api</swaggerInput>
                    <outputDir>src/docs/asciidoc/generated/all</outputDir>
                    <config>
                        <!-- 除了ASCIIDOC之外,还有MARKDOWN和CONFLUENCE_MARKUP可选 -->
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                    </config>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.3</version>
                <!-- Include Asciidoctor PDF for pdf generation -->
                <dependencies>
                    <dependency>
                        <groupId>org.asciidoctor</groupId>
                        <artifactId>asciidoctorj-pdf</artifactId>
                        <version>1.5.0-alpha.10.1</version>
                    </dependency>
                    <dependency>
                        <groupId>org.jruby</groupId>
                        <artifactId>jruby-complete</artifactId>
                        <version>1.7.21</version>
                    </dependency>
                </dependencies>
                <!-- Configure generic document generation settings -->
                <configuration>
                    <sourceDirectory>src/docs/asciidoc/generated/all</sourceDirectory>
                    <sourceHighlighter>coderay</sourceHighlighter>
                    <attributes>
                        <toc>left</toc>
                    </attributes>
                </configuration>
                <!-- Since each execution can only handle one backend, run
                     separate executions for each desired output type -->
                <executions>
                    <execution>
                        <id>output-html</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>html5</backend>
                            <outputDirectory>src/docs/asciidoc/html</outputDirectory>
                        </configuration>
                    </execution>

                    <execution>
                        <id>output-pdf</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>process-asciidoc</goal>
                        </goals>
                        <configuration>
                            <backend>pdf</backend>
                            <outputDirectory>src/docs/asciidoc/pdf</outputDirectory>
                        </configuration>
                    </execution>

                </executions>
            </plugin>
        </plugins>
    </build>

</project>

A: First, you can try what suggested here.
Then, since that jar (Maven page), need a specific repository, you could try adding this code in your pom.xml
<repositories>
    <repository>
        <id>Spring</id>
        <name>Spring</name>
        <url>https://repo.spring.io/plugins-release/</url>
    </repository>
</repositories>

Hope it helps.


text:
Q: On duplicate key update error I used the function ON DUPLICATE KEY UPDATE. It's weird because on my other codes, it works just fine, but with this one, I can still get records that are the same.
Here's my stored proc.
IF ((SELECT COUNT(playlist_id) FROM playlists WHERE playlist_id = i_playlistid) > 0)  THEN

   INSERT INTO playlist_terminal (playlist_id,terminal_id,userid,booking_id) VALUES        (i_playlistid,i_terminal_id,i_userid,i_booking_id)
   ON DUPLICATE KEY UPDATE terminal_id = i_terminal_id;

   SELECT terminal.terminal_id,terminal.plate_number,terminal.terminal_status,
   terminal.location, terminal_sum.booking_id FROM terminal
   INNER JOIN playlist_terminal
   ON terminal.terminal_id = playlist_terminal.terminal_id
   INNER JOIN terminal_sum
   ON playlist_terminal.terminal_id = terminal_sum.terminal_id
   WHERE playlist_terminal.userid = i_userid AND playlist_id = i_playlistid;


text:
Q: How to loop trough subquery and fill fields in array Json object I have created a custom object to create a json string. I kan loop trough the list to fill in the first level/parent fields. How do I loop trough the subquery and fill the arrays in the json object.
  SprResult =  [SELECT id,name, Productcode__c,
                  (select id from Sales_Product_Sections__r)
                                        FROM Sales_Product__c
                                        WHERE Productcode__c  = :ProductCode ];
        system.debug(SpJsonList);
        for(Sales_Product__c sp : SprResult){
        SalesProductJSON spJson = new SalesProductJSON();
        SpJson.ProductCode = sp.Productcode__c;
        SpJson.ProductName = sp.Name;
            for(Sales_Product_Section__c Sps: sp.Sales_Product_Sections__r){
                spJson.

            }
        SpJsonList.add(spJson);
        }

Json object
public class SalesProductJSON{
    public String ProductCode;  //Productcode
    public String ProductName;  //Name
    public cls_SalesProductSections[] SalesProductSections;
    class cls_SalesProductSections {
        public String SectionCode;  //MAIN
        public String SectionName;  //Main
        public cls_SalesProductItems[] SalesProductItems;
    }
    class cls_SalesProductItems {
        public String ItemCode; //Itemcode
        public String ItemName; //Itemname
    }
    public static List<salesProductJSON> parse(String json){
        return (List<salesProductJSON>) System.JSON.deserialize(json, List<salesProductJSON>.class);
    }
}

How would I fill for example Sectioncode or Itemcode

A: Note that you can only query one level "down" in the child hierarchy, so you'll need a second query:
Map<Id, Sales_Product_Section__c> productSections = new Map<Id, Sales_Product_Section__c>([
  SELECT (SELECT ... FROM Sales_Product_Items__r) ... FROM Sales_Product_Section__c WHERE Sales_Product__c = :sprResult
]);

You'd create a List and populate it:
for(Sales_Product__c sp : SprResult){
    SalesProductJSON spJson = new SalesProductJSON();
    SpJson.ProductCode = sp.Productcode__c;
    SpJson.ProductName = sp.Name;
    SalesProductJSON.cls_SalesProductSections[] sections = new SalesProductJSON.cls_SalesProductSections[0];
    for(Sales_Product_Section__c Sps: sp.Sales_Product_Sections__r){
        SalesProductJSON.cls_SalesProductSections section = new SalesProductJSON.cls_SalesProductSections();
        // set data //
        Sales_Product_Section__c subItems = productSections.get(sps.Id);
        SalesProductJSON.cls_SalesProductItems items = new SalesProductJSON.cls_SalesProductItems();
        for(Sales_Product_Item__c recordItem: subItems.Sales_Product_Items__r) {
            SalesProductJSON.cls_SalesProductItems item = new SalesProductJSON.cls_SalesProductItems();
            // set more data //
            // then //
            items.add(item);
        }
        section.salesProductItems = items;
        // then //
        sections.add(section);
    }
    SpJsonList.add(spJson);
}

I've probably made some mistakes here, but hopefully this should help you with your project.


text:
Q: Changing texture depending on action So when a user makes a purchase they get a new texture available that will replace the original one. I´ve sort of pulled it of. But I also want the user to ba able to replace back to the original one if the wish to do so.
At the moment the user makes a purchase and the texture changes fine. But as I store that change in preferences it makes it permanent. So when I try to press the button to change to the original stone, which simply calls "setStone(...)" , nothing happends.
Anyone that can see where I´ve gone wrong?
P.S the code is not copied straight of, just cut in the important parts.
ObjectMap<Integer, Texture> screenMap = new ObjectMap<Integer, Texture>();
ObjectMap<String, Boolean> mTexturesStatus = new ObjectMap<String, Boolean>();

public void setStone1() {
    stoneImage = new Image(screenMap.get(0));

}

public void setStone(int screenId) {
    stoneImage = new Image(screenMap.get(screenId));

  }

screenMap.put(0, sdStone);
    screenMap.put(1, stone_3);

mTexturesStatus.put("stone1", stone1);
    mTexturesStatus.put("stone2", stone2);

btnArrow.addListener(new ChangeListener() {

                @Override
                public void changed(ChangeEvent event, Actor actor) {

                    game.setScreen(0);

                    //Saves the entered text.

                    Preferences prefs = Gdx.app.getPreferences("preferences");
                    prefs.putString("textField", textField.getText());
                    prefs.putString("textArea", textArea.getText());
                    prefs.getBoolean("stoneOne");
                    prefs.getBoolean("stoneTwo");
                    prefs.flush();

                }

            });
    //screenMap.put(prefs.getInteger("stoneOne", 0), sdStone);
    //screenMap.put(prefs.getInteger("stoneTwo", 1), stone_3);
            setStone1();
            if(stone1 = true) {
                setStone(0);
                prefs.putBoolean("stoneOne", true);

            }
            if(stone2 = true) {
                setStone(1);
                prefs.putBoolean("stoneTwo", true);
            }

}


text:
Q: sending php array to javascript function onclick Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";

$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);

mysql_close();

if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{

    $GameID = mysql_result($TicketResult,$s,"GameID");
    $TipID = mysql_result($TicketResult,$s,"TipID");
    $ArrayIDs[$s] = $GameID;
    echo "";
    $s++;
}
}
?>

So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script

<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)">POTVRDI

And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {

    var MatchID = $(this).attr('id');
    var lab = "Label";

    var Label = lab + MatchID;

    var Final = document.getElementById(Label);

    var TipID;

    if (Final.innerHTML == '1') {
        TipID = 1;
    }
    else if (Final.innerHTML == 'X') {
        TipID = 2;
    }
    else if (Final.innerHTML == '2') {
        TipID = 3;
    }
    else {
        return;
    }

    var request_type;
    var browser = navigator.appName;

    if (browser == "Microsoft Internet Explorer") {
        request_type = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        request_type = new XMLHttpRequest();
    }

    var http = request_type;

    var AlreadyPlayed = false;

    if (Ticket != null) {
        var TicketExists = Ticket;
        for (var i = 0; i < TicketExists.length; i++) {
            if (TicketExists[i] == MatchID) {
                AlreadyPlayed = true;
                break;
            }
        }
    }

    if (http != null) {

        if (AlreadyPlayed == true) {
            http.open('get', 'update.php?MatchID=' + MatchID +
            '&TipID=' + TipID + '&UserID=' + 1, true);
        }
        else {
            http.open('get', 'insert.php?MatchID=' + MatchID +
            '&TipID=' + TipID + '&UserID=' + 1, true);
        }
        http.send(null);
    }
});

if (Ticket == null) {
    alert('Tiket je napravljen');
}
else {
    alert('Tiket je promenjen');
}
}

With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out

A: Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">

to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">

I'd also reccomend not outputting
"";

for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
    //...do things here...
}

A: You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo  json_encode($ArrayIDs); ?>)


text:
Q: out of memory Error Unsolved I am taking the image from internal memory.and pasting it on the greator image in the merge function.after the 66 image the app is crashing badly and the error is out of memory .                                                                                Do you have any idea why the app crashing and how to solve it.here the app crashes after image no 66 come`
     public void mergeImageClicked(View v) {
    int noOfImage = listFile.length;
    Bitmap[] bitmap = new Bitmap[noOfImage];
    Bitmap[] resizedBitmap = new Bitmap[noOfImage];
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    for (int j = 0; j < listFile.length; j++) {
        bitmap[j] = BitmapFactory.decodeFile(listFile[j].getAbsolutePath(), options);

        resizedBitmap[j] = ThumbnailUtils.extractThumbnail(bitmap[j], 30, 30);

    }

`

A: You are keeping huge number of full sized bitmaps in your bitmap array. Instead you should keep only one bitmap for loading and resizing.
public void mergeImageClicked(View v) {
   int noOfImage = listFile.length;
   Bitmap[] resizedBitmap = new Bitmap[noOfImage];
   BitmapFactory.Options options = new BitmapFactory.Options();
   options.inPreferredConfig = Bitmap.Config.ARGB_8888;
   for (int j = 0; j < listFile.length; j++) {
      Bitmap bitmap = BitmapFactory.decodeFile(listFile[j].getAbsolutePath(), options);

      resizedBitmap[j] = ThumbnailUtils.extractThumbnail(bitmap, 30, 30);
}

A: You have limited memory per app on Android. Look into heap size and memory management here.
In you code, you seem to be be decoding the Bitmap and then holding into memory, this is bad practise - as you will always run out of memory sooner or later.
Its best to keep only the Bitmap you require, and then release when you have no need for it. Take a look at this on how to manage Bitmaps


text:
Q: Scripting sleep and wake up I have an iMac that when it boots up the screen is all red and fuzzy, but if you put the Mac to sleep and wake it up again the screen is normal.

*

*Has anyone had this issue? If so what is it?

*I am looking for a sleep and wake up script so the Mac will load the script automaticaly once it has got the user select screen.

Any info would be great.

A: A mac I had would have graphical problems similar to what you're describing when the logic board was going out. So that might be the answer to your first question.
That being said, the problem on mine wasn't only when the machine booted up.


text:
Q: Fugas de memoria en Android Buenas, mi primera vez por aca. Estoy aprendiendo de forma totalmente autodidacta a programar en Java, principalmente para Android.

Me vendría muy bien la opinión de los que saben sobre las fugas de memoria (Por ahora es lo que se me está haciendo más difícil comprender.)
La pregunta en definitiva es, ¿Qué parte de estos códigos provoca fugas de memoria?

Esto es lo que muestra el DDMS después de un cambio de orientación de pantalla filtrando por el nombre del paquete principal: DDMS Output ... y los códigos de la clases involucradas, son:
ScreenSearchFragment.java

public class ScreenSearchFragment extends Fragment{

    private RecyclerSearchAdapter myAdapter;
    private DialogSearch dialog;
    private static final String TAG_DIALOG = "Search Dialog";

    @NonNull
    public static ScreenSearchFragment newInstance(String tabTitle){
        String title = "title";

        ScreenSearchFragment fragment = new ScreenSearchFragment();
        Bundle arguments = new Bundle();
        arguments.putString(title, tabTitle);
        fragment.setArguments(arguments);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_screen_definition, container, false);
        FloatingActionButton btnAddWord = (FloatingActionButton) view.findViewById(R.id.btn_add_word);
        if(dialog == null) {
            Log.d("ScreenSearchFragment", "dialog es null");
            dialog = new DialogSearch();
        }

        btnAddWord.setOnClickListener(new MyOnClickListener(dialog, getFragmentManager()));

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initAdapter();
        setRecycler(view);

    }

    private void initAdapter(){
        List<Word> words = new ArrayList<>();
        myAdapter = new RecyclerSearchAdapter(words);

        //Examples
        myAdapter.addWord(new Word("Word 1", "Here is the definition of the word"));
        myAdapter.addWord(new Word("Word 2", "Here is the definition of the word"));
        myAdapter.addWord(new Word("Word 3", "Here is the definition of the word"));
        myAdapter.addWord(new Word("Word 4", "Here is the definition of the word"));
        myAdapter.addWord(new Word("Word 5", "Here is the definition of the word"));

        //Example multiline
        myAdapter.addWord(new Word("Word 6", "Here \nis \nthe \ndefinition \nof \nthe \nword"));
    }

    private void setRecycler(View view){
        RecyclerView rV = (RecyclerView) view.findViewById(R.id.recycler_search);
        RecyclerView.LayoutManager llm = new LinearLayoutManager(view.getContext());

        rV.setLayoutManager(llm);
        rV.setAdapter(myAdapter);

        DefaultItemAnimator itmAnim = new DefaultItemAnimator();

        itmAnim.setAddDuration(1000);
        itmAnim.setRemoveDuration(200);
        itmAnim.setMoveDuration(800);

        rV.setItemAnimator(itmAnim);

        //Delete item when is swiped to LEFT
        ItemTouchHelper.SimpleCallback simpleCallback = new MySimpleCallback();

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(rV);
    }

    private static class MyOnClickListener implements View.OnClickListener {
        private final DialogSearch dialog;
        private final FragmentManager fragmentManager;

        MyOnClickListener(DialogSearch dialog, FragmentManager fm) {
            this.dialog = dialog;
            this.fragmentManager = fm;
        }

        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.btn_add_word) {
                if (!dialog.isVisible()) {
                    dialog.show(fragmentManager, TAG_DIALOG);
                }
            }
        }
    }

    private class MySimpleCallback extends ItemTouchHelper.SimpleCallback {
        MySimpleCallback() {
            super(0, ItemTouchHelper.LEFT);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                              RecyclerView.ViewHolder target) {
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            if (direction == ItemTouchHelper.LEFT){
                myAdapter.removeWord(viewHolder.getLayoutPosition());
            }
        }
    }
}

DialogSearch.java

public class DialogSearch extends DialogFragment implements View.OnClickListener {

    private ProgressBar progressBar;
    private Button btnCancel;
    private Button btnSearch;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.alert_dialog, container, false);
        btnSearch = (Button) view.findViewById(R.id.btn_search);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        progressBar = (ProgressBar) view.findViewById(R.id.progress_search);

        TextInputLayout inputLayout = (TextInputLayout) view.findViewById(R.id.search_input_layout);

        TextInputEditText etWord = (TextInputEditText) view.findViewById(R.id.et_word);

        etWord.addTextChangedListener(new MyTextWatcher(inputLayout, btnSearch));

        btnSearch.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        return view;
    }

    @Override
    public void dismiss() {
        if(! (progressBar.getVisibility() == View.VISIBLE)){
            super.dismiss();
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        if(! (progressBar.getVisibility() == View.VISIBLE)){
            setCancelable(true);
            super.onCancel(dialog);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btn_search:
                progressBar.setVisibility(View.VISIBLE);
                btnCancel.setEnabled(true);
                btnSearch.setEnabled(false);
                setCancelable(false);
                //Download definition in a new AsyncTask
                break;

            case R.id.btn_cancel:
                progressBar.setVisibility(View.INVISIBLE);
                //Stop the AsyncTask if is running
                dismiss();
                break;
        }
    }

    private static class MyTextWatcher implements TextWatcher{
        private TextInputLayout inputLayout;
        private Button button;

        MyTextWatcher(TextInputLayout inputLayout, Button button){
            this.inputLayout = inputLayout;
            this.button = button;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {

            if(button.getId() == R.id.btn_search){
                if(editable.length() < 3){
                    button.setEnabled(false);
                    inputLayout.setError("Invalid Text.");
                    if(editable.length() == 0){
                        inputLayout.setError(null);
                    }
                }else{
                    button.setEnabled(true);
                    button.setVisibility(View.VISIBLE);
                    inputLayout.setError(null);
                }
            }
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity{

    private MainFragmentAdapter fragmentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initFragmentAdapter();
        initViews();
    }

    private void initFragmentAdapter(){
        fragmentAdapter = new MainFragmentAdapter(getSupportFragmentManager());

        //Add fragments here
        fragmentAdapter.addFragment(ScreenAntonimosFragment.newInstance("Example 1"));
        fragmentAdapter.addFragment(ScreenSinonimosFragment.newInstance("Example 2"));

        fragmentAdapter.addFragment(ScreenSearchFragment.newInstance("Search"));
    }

    private void initViews(){

        ViewPager viewPager = (ViewPager) findViewById(R.id.main_view_pager);
        if(viewPager != null){
            viewPager.setAdapter(fragmentAdapter);
        }

        TabLayout tabLayout = (TabLayout) findViewById(R.id.main_tab);
        if(tabLayout != null){
            tabLayout.setupWithViewPager(viewPager);
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        boolean opc = false;

        if(id == R.id.action_settings){
            opc = super.onOptionsItemSelected(item);
        }
        return opc;
    }
}


text:
Q: How many cells will be born before it dies?
A given cell can replicate at rate $\lambda$ and die at rate $\mu$. Upon replication, the cell divides into 2.

The question asks: how many cells will be produced by this cell before it dies?

My interpretation:
Case 1) I only count the cells which are born directly by this cell, e.g. if it replicates, I don't count the replications of the 2nd cell.
Case 2) I consider the total number of cells generated.

Case 1: With probability $\lambda / \mu$ the cell will replicate before it dies, with probability $(\lambda / \mu)^2$ it will replicate twice and so on using the memoryless property of the exponential. Each time we get an extra cell, hence we have $E(X)=\sum_1^\infty (\lambda /\mu)^i \times i$
Case 2: I don't know how to include all possible divisions of daughter cells. Maybe it's not required?

A: For your case 1, your calculation is not quite correct. The probability of no offspring is $\dfrac{\mu}{\lambda+\mu}$, of exactly one offspring $\dfrac{\lambda\mu}{(\lambda+\mu)^2}$, of two $\dfrac{\lambda^2\mu}{(\lambda+\mu)^3}$ etc. giving the expectation  $$\sum_{i=0}^\infty i\dfrac{\lambda^i\mu}{(\lambda+\mu)^{i+1}} = \sum_{i=1}^\infty  \dfrac{\lambda^i}{(\lambda+\mu)^{i}} = \dfrac{\lambda}{\mu}$$
An alternative way would be to assume the expectation was $x$ and then using memorylessness to solve $x=\dfrac{\lambda}{\lambda+\mu}(1+x)$ to give $x=\dfrac{\lambda}{\mu}$ again
The latter approach works for case 2 too.  Suppose its expectation is $y$.  You would then want to use memorylessness to solve $y=\dfrac{\lambda}{\lambda+\mu}(1+2y)$ to give $y=\dfrac{\lambda}{\mu-\lambda}$, at least when $\mu \gt \lambda$


text:
Q: Django - Get latest related object for each object in queryset using one database query I have a Django app where I collect data from sensors which are divided into areas.
class Area(models.Model):
  name = models.CharField(max_length=50)
  code = models.IntegerField(unique=True, primary_key=True)

class Sensor(models.Model):
  name = models.CharField(max_length=30)
  area = models.ForeignKey(Area, on_delete=models.CASCADE)

class Observation(models.Model):
  date_time = models.DateTimeField()
  sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE)
  value = models.DecimalField(max_digits=4, decimal_places=1)

What I need for each area is a list of the latest observations in that area, that is, one per sensor.
So far, I solved it like this:
class Sensor(models.Model)
  ...
  def latest_observation(self):
    return self.observation_set.latest('date_time')

Now, I can loop through my sensors to get the latest observation for each sensor.
class Area(models.Model):
  ...

  def latest_observations_per_sensor(self):
    return [s.latest_observation() for s in self.sensor_set.all()]

This returns a list of what I want, but it is not very efficient since it makes a database query for each individual sensor. Ideally, I would do this in one database query for all areas, but I don't know if this is possible in Django.


text:
Q: displayed equation immediately after an \item, want it to not leave a blank line I have an enumerate environment where each item is just a single displayed equation.  This starts on a new line so the "(a)" ends up on a blank line.  Can I make the displayed equation not skip a line, so that the first line of the displayed equation is aligned with the "(a)"?
I thought \vspace{-\baselineskip} would do the trick, but of course it applies to the \item as well.
I use enumitem in case that matters; also in Real Life I have adjusted the various spacing parameters so that it looks better that the mwe.
\documentclass{amsart}

\usepackage{enumitem}

\begin{document}

\begin{enumerate}
\item
  Each item starts with an ugly blank line.
  \begin{enumerate}
  \item
    %\vspace{-\baselineskip} % doesn't work, moves the "(a)" up as well
    \begin{equation*}
      E=mc^2
    \end{equation*}
  \item
    %\vspace{-\baselineskip} % doesn't work, moves the "(b)" up as well
    \begin{align*}
      a^2+b^2 &= c^2
      \\ &= E/m
    \end{align*}
  \item
    In this case we have some text, so it looks right.
    \begin{align*}
      \sin^2x + \cos^2x + e^{\pi i} = 0
    \end{align*}
  \end{enumerate}
\end{enumerate}

\end{document}

A: The problem lies in the timing of when LaTeX starts a new paragraph in a list environment. The item tag doesn't get typeset until a new paragraph begins and when there's no text, the paragraph begins (and then ends immediately) when you enter display math mode.
Adding \mbox{} after the \item command will persuade LaTeX to begin a new paragraph and then your \vspace command will work as expected. I would be inclined to wrap up the whole of \item, \mbox and the \vspace into a macro, perhaps \displaymathitem to (a) avoid repeating yourself and (2) make it clear to anyone looking at your document what you're trying to do, not least of why is that a change in document class will likely change the required amount to pass to \vspace. I'm still not entirely convinced that

*

*E = mc²

is the appropriate typographic and textual solution for this, but I don't have a better option, so let's go with it.

A: I use inline math with \hfils as a substitute.  One can add \displaystyle, if needed.  For the align structures, I substitute an \alignLongunderstack (or \alignShortunderstack) from the tabstackengine package.
\documentclass{amsart}

\usepackage{enumitem,tabstackengine}
\TABstackMath
\begin{document}

\begin{enumerate}
\item
  Each item starts with an ugly blank line.
  \begin{enumerate}
  \item
    \hfil$\displaystyle%\begin{equation*}
      E=mc^2
    $\hfil\mbox{}%\end{equation*}
  \item
    \hfil$\alignLongunderstack{%\begin{align*}
      a^2+b^2 =& c^2
      \\ =& E/m
    }$\hfil\mbox{}%\end{align*}
  \item
    In this case we have some text, so it looks right.
    \begin{align*}
      \sin^2x + \cos^2x + e^{\pi i} = 0
    \end{align*}
  \end{enumerate}
\end{enumerate}

\end{document}


text:
Q: How to enable SSL with Qt QODBC I can't find information about this. Is it possible to enable SSL with QODBC? If so, how?
I have no issues using SSL with QMySql or using non-SSL connection with QODBC.
 However, the QODBC driver documentation at http://qt-project.org/doc/qt-5.1/qtsql/sql-driver.html#qodbc makes no mention of SSL + ODBC and QODBC rejects parameters not on the list at http://qt-project.org/doc/qt-5.1/qtsql/qsqldatabase.html#setConnectOptions , none of which pertain to SSL.
Interestingly enough, I cannot find documentation for those options, their meanings, or their allowed values anywhere. The only mention of those options I can find at all is on that documentation page, which does not state whether it is a comprehensive list or provide any further information.
The only other direct reference I can find to using SSL with QODBC is an unanswered post from four years ago:
http://www.qtcentre.org/threads/34367-SSL-with-QODBC
Finding this information is further compounded by the fact that QODBC is also the name of an apparently unrelated ODBC product for Quickbooks.
This is a copy of my post at http://qt-project.org/forums/viewthread/36850/

A: You need to pass your secure connection options as part of ODBC datasource to QSqlDatabase::setDatabaseName. ODBC datasource should look similar to:
Driver={MySQL ODBC 5.1 Driver};Server=server_address;Database=database;
User=username;Password=password;
sslca=ca.crt;sslcert=client.crt;sslkey=client.key;sslverify=1;

I haven't checked this exact string, just show the idea (taken from here). See MySQL Connector/ODBC documentation for details.