text:
Q: How can I dynamically generate a polygon shape that moves upward in Canvas? Right now, what I have is shown in this fiddle : https://jsfiddle.net/p0o5fvdm/
What I want is the polygon to move up smoothly and fill up the portion below it with some more black color that spans a random width which is aligned with the polygon and keeps moving up smoothly like the top part. I tried to use the following code but it does not retain the shape of original polygon and new polygons are being drawn over old ones resulting in flashes.
This is my animation function:
function animate(myShape, canvas, context, startTime) {

    var time = (new Date()).getTime() - startTime;

    myShape.y1 -= 1;
    myShape.y2 -= 1;
    myShape.y3 -= 1;

    context.clearRect(0, 0, canvas.width, canvas.height);

    drawShape(myShape, context);

    requestAnimFrame(function() {
      animate(myShape, canvas, context, startTime);
    });
}

I added the following code to dynamically set the width of bottom edge using following code just above context.clearRect.
if(myShape.y2 < 400) {
    myShape.y2 = 400;
    myShape.x2 = Math.random()*300;
    myShape.y3 = 400;
}

This is the initial value of myShape:
var myShape = {
    x1: 200,
    y1: 0,
    x2: 120,
    y2: 400,
    x3: 0,
    y3: 400
};

My canvas has a height of 400 pixels. That's why I have used it as reference here. Let me know if I need to add more details.

A: Here's a plan to have a polygon with random width that infinitely scrolls up your canvas:

*

*Keep an array of random-X, increasing-Y coordinates that form your polygon.

*The first element, array[0].y should be less than zero.

*The last element, array[array.length-1].y should be greater than the canvas height.

*Animate by reducing each array.y by 1 during each animation loop.

*When array[1].y is reduced below zero, shift array[0] off the beginning of the array.

*When the last array.y is animated onto the visual canvas, push a new element into the array having array.y greater than the canvas height.

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var a=[
    {x:rx(),y:-Math.random()*100},  // y above canvas
    {x:rx(),y:ry()}                 // y below canvas
];

// redraw
draw(a);

requestAnimationFrame(animate);

function animate(){
    // update - move all y's upward
    for(var i=0;i<a.length;i++){ a[i].y-=3; }
    // test if a[1] is off top of canvas
    if(a[1].y<0){a.shift();}
    // test if last a[] is on canvas
    if(a.length<2 || a[a.length-1].y<canvas.height){
        a.push({x:rx(),y:ry()});
    }
    // redraw
    draw(a);
    // request another animation loop
    requestAnimationFrame(animate);
}
//
function draw(a){
    ctx.clearRect(0,0,cw,ch);
    ctx.beginPath();
    ctx.moveTo(0,a[0].y);
    for(var i=0;i<a.length;i++){
        ctx.lineTo(a[i].x,a[i].y);
    }
    ctx.lineTo(0,a[a.length-1].y);
    ctx.fill();
}
//
function rx(){ return(canvas.width/2+Math.random()*200); }
function ry(){ return(canvas.height*1.25+Math.random()*canvas.height/2); }
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>


text:
Q: Implementing layers when blitting an object in pygame I can't find an answer to this anywhere else but it seems to be such an obvious and necessary feature for game design that I can't imagine an implementation for it doesn't exist. I'm attempting to blit an already-created object onto the screen, however the argument I'm using for blitting does not seem to contain a space to specify what layer the sprite should be displayed on, instead displaying an error message stating "invalid rectstyle argument". If it does indeed turn out that there is no way for the standard blit() function to include layers, I would appreciate it if I could have a workaround that works in the context of object-oriented programming. Code below for context:
class Hud(pygame.sprite.Sprite):
    def __init__(self, group, layer, posX, posY):
        self.image = pygame.image.load("Hudplaceholder.png")
        self.rect = self.image.get_rect(center=(posX, posY))
        self._layer = layer
        pygame.sprite.Sprite.__init__(self, group)

    class Health(pygame.sprite.Sprite):
        def __init__(self, group, layer, posX, posY):
            self.image = pygame.image.load("Healthplaceholder.png")
            self.rect = self.image.get_rect(center=(posX, posY))
            self._layer = layer
            pygame.sprite.Sprite.__init__(self, group)
    #all of the other sprites are in the same format

    #global sprite dump
    group = pygame.sprite.LayeredUpdates()
    hud = Hud(group, 3, 655, 5)
    health = Health(group, 3, 790, 135)
    ammo = Ammo(group, 3, 795, 190)
    eye1 = Eye1(group, 3, 790, 250)
    desk = Desk1(group, 2, 409, 230)
    interior = Interior(group, 0, 410, 180)
    shelf = Shelf(group, 2, 409, 230)
    drinksMachine = DrinksMachine(group, 2, 409, 230)
    deskUnder = DeskUnder(group, 2, 409, 230)
    rifle = Gun(group, 4, 220, 250)

    group.add(hud)
    group.add(health)
    group.add(ammo)
    group.add(eye1)
    group.add(desk)
    group.add(interior)
    group.add(queueCustomer)

    screen.blit(interior.image, (-20, -20))
    screen.blit(desk.image, (0, 0))
    screen.blit(hud.image, (hud.rect.centerx, hud.rect.centery))
    screen.blit(health.image, (756, 110))
    screen.blit(health.image, (706, 110))
    screen.blit(health.image, (656, 110))
    screen.blit(ammo.image, (765, 155))
    screen.blit(ammo.image, (725, 155))
    screen.blit(ammo.image, (685, 155))
    screen.blit(ammo.image, (645, 155))
    screen.blit(eye1.image, (750, 220))
    group.update()
    pygame.display.flip()

A: If you're happy to forgo using the excellent sprite group drawing functions, a simple method to do this might be:

*

*Create a list of all Sprites: all_sprites.

*Sort your list of Sprites by their _layer

*Paint them individually

    all_sprites = [ hud, health, ammo, etc. ]

    # ...

    # sort sprites by ascending _layer
    for sprite in sorted( all_sprites, key=lambda x: x._layer ):
        # and then paint
        screen.blit( sprite.image, sprite.rect )

That said, you probably don't need to do this.  Probably a bit of re-work on your painting algorithm would remove the necessity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Speeding up path calculation of many particles using Scipy I am trying to calculate the evolution of the position of many particles using Python. Ultimately I will have many particles (on the order of 10000) being calculated over around 100000 time-steps. Since I am trying at all costs to avoid having to use Fortran, I am trying to speed up the process.
The equation I am trying to solve is
d X_i/dt = u
d Y_i/dt = v

So ideally I would work with arrays with two dimensions: one to change between particles and another to change between x, and y. So if I had 100 particles, I'd have a 100x2 array.
A part of the problem comes because scipy.integrate.odeint only takes 1-dimensional arrays, so I have to flatten my initial conditions, split it inside my derivative function (RHS_im), and then flatten it again when outputting, which is slow (this accounts for about 20% of the RHS_im call).
I can do it in an ugly way. Here's a MWE that I put up
import numpy as np
from scipy.interpolate import RegularGridInterpolator
from scipy.integrate import odeint

x=np.arange(2.5, 500, 5)
y=np.arange(2.5, 500, 5)

X, Y = np.meshgrid(x, y, indexing='xy')

U=np.full_like(X, -0.1)
V=0.2*np.sin(2*np.pi*X/200)

tend=100
dt=1
tsteps=np.arange(0, tend, dt)

#------
# Create interpolation
U_int = RegularGridInterpolator((x, y), U.T)
V_int = RegularGridInterpolator((x, y), V.T)
#------

#------
# Initial conditions
x0=np.linspace(200,300,5)
y0=np.linspace(200,300,5)
#------

#------
# Calculation for many
def RHS_im(XY, t):
    X, Y = np.split(XY, 2, axis=0)
    pts=np.array([X,Y]).T
    return np.concatenate([ U_int(pts), V_int(pts) ])
XY0 = np.concatenate([x0, y0])
XY, info = odeint(RHS_im, XY0, tsteps[:-1], args=(), hmax=dt, hmin=dt, atol=0.1, full_output=True)
X, Y = np.split(XY, 2, axis=1)

Is there a way to avoid the split process?
Furthermore, although I have chosen odeint to integrate this system, I am not committed to the choice. I would easily change if there is another function that does this faster (even with a simple Euler scheme). I just didn't find any. (The same thing goes for the interpolation scheme, which is roughly 80% of the time that RHS_im takes).
EDIT
Improved the splitting process a bit (by using np.split) but the overall program still needs improvement.

A: Thanks for the clarification on your MWE. I was able to get the MWE to run about 50% faster by combing U_int and V_int into UV_int and by changing the layout of XY so that np.reshape can be used instead of np.split. Both of these change help access memory inplace and contiguously.
x_grid=np.arange(2.5, 500, 5)
y_grid=np.arange(2.5, 500, 5)

x_mesh, y_mesh = np.meshgrid(x_grid, y_grid, indexing='xy')

u_mesh=(np.full_like(x_mesh, -0.1))
v_mesh=(0.2*np.sin(2*np.pi*x_mesh/200))
uv_mesh = np.stack([u_mesh.T, v_mesh.T], axis=-1)

tend=100
dt=1
tsteps=np.arange(0, tend, dt)

#------
# Create interpolation
UV_int = RegularGridInterpolator((x_grid, y_grid), uv_mesh)
#------

#------
# Initial conditions
npart = 5
x0=np.linspace(200,300,npart)
y0=np.linspace(200,300,npart)

XY_pair = np.reshape(np.column_stack([x0, y0]), (2*npart))
#-----

def RHS_im(XY, t):
    return np.reshape(UV_int(np.reshape(XY, (npart, 2))), (npart*2))

XY, info =  odeint(RHS_im, XY_pair, tsteps[:-1], args=(), hmax=dt, hmin=dt, atol=0.1, full_output=True)


text:
Q: Unit Area of largest region of 1's Consider a matrix with N rows and M columns, where each cell contains either a '0' or a '1' and any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. If one or more filled cells are connected, they form a region. The task is to find the unit area of the largest region.
Here is my code:
class GFG {
    static int max;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for (int t = 0; t < T; t++) {
            max = 1;
            int R = sc.nextInt();
            int C = sc.nextInt();
            int[][] M = new int[R][C];
            for (int i = 0; i < R; i++) {
                for (int j = 0; j < C; j++) {
                    M[i][j] = sc.nextInt();
                }
            }
            printMatrix(M, R, C);
            boolean[][] visited = new boolean[R][C];
            for (int i = 0; i < R; i++) {
                for (int j = 0; j < C; j++) {
                    int L = 1;
                    if (M[i][j] == 1 && !visited[i][j])
                        markVisited(M, visited, i, j, R, C, L);
                }
            }
            System.out.println(max);
        }
    }

    private static void printMatrix(int[][] M, int R, int C) {
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                System.out.print(M[i][j] + " ");
            }
            System.out.println();
        }

    }

    public static boolean isSafe(int[][] M, boolean[][] visited, int i, int j, int R, int C) {
        return ((i >= 0 && i < R) && (j >= 0 && j < C) && (M[i][j] == 1 && (!visited[i][j])));
    }

    public static void markVisited(int[][] M, boolean[][] visited, int x, int y, int R, int C, int L) {
        // int[] x_pos = {1 , 1, 1, 0, 0, -1, -1, -1};
        // int[] y_pos = {-1, 0, 1, -1, 1, -1, 0, 1};
        //commenting the arrays, as selecting one of the above and below combinations, result in different outputs
        int[] x_pos = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int[] y_pos = { -1, 0, 1, -1, 1, -1, 0, 1 };

        visited[x][y] = true;
        for (int k = 0; k < 8; k++) {
            if (isSafe(M, visited, x + x_pos[k], y + y_pos[k], R, C)) {
                L++;
                max = Math.max(L, max);
                markVisited(M, visited, x + x_pos[k], y + y_pos[k], R, C, L);
            }
        }

    }
}

The code is not working for below mentioned test case:
1
4 7
1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1
output is 13, expected is 14.
Interestingly, If I change x_pos and y_pos (commented in code) in markVisited method as
int[] x_pos = {1 , 1, 1, 0, 0, -1, -1, -1};
int[] y_pos = {-1, 0, 1, -1, 1, -1, 0, 1};

output is 14. I don't understand how output can change when the x_pos and y_pos combinations are same.
Its happening for other test cases also. I have commented x_pos[] and y_pos[].
Please suggest what's wrong.

A: So, your issue is the way you accumulate L recursively. Here is your input array:
1 1 1 1 0 0 1
1 0 1 0 1 1 0
0 0 0 0 1 0 1
1 0 0 0 1 1 1
Just as an example. If the path you have already accumulated is splitted in two different paths (let's pick up the first 3 rows of your input for better understanding)
1 1 1 1 0 0 1
1 0 1 0 1 1 0
0 0 0 0 1 0 1
At position (1, 5), you can go either to the 1 at the top right, or the 1 at the bottom right (your path is divided in two), you are passing the current L to each of those and then, each of those paths are accumulating L on their own, instead of accumulating a global L which is intended to accumulate all the 1's found that belongs to the main path whose root is the first 1 you found.
Your fix is really simple, just move L to the top of your variables, like this:
static int max;
static int L;

Then instead of passing L through your methods, just reset its value back each time you start a new root 1:
if (M[i][j] == 1 && !visited[i][j]) {
    L = 1;
    markVisited(M, visited, i, j, R, C);
}

And finally, in your markVisited, just do the same thing you do but getting rid of that L param at the end of your method, since you are going to use the global one:
max = Math.max(++L, max);

Hope that helps, let me know if it is not clear so I can add more details if needed ^-^
It worth to mention that the fact that your code works well if you change the variables is a coincidence because this behavior depends on the way you go through the 1's in your iteration. Depending on which 1 you choose first, you can either fall in this case or not, so changing them is not the solution.

A: The problem is with the way you're accumulating the count of visited cells.
Firstly you need to change your outer loop to:
int max = 0;
for (int i = 0; i < R; i++) {
    for (int j = 0; j < C; j++) {
        if (M[i][j] == 1 && !visited[i][j])
          max = Math.max(max, markVisited(M, visited, i, j, R, C));
    }
}
System.out.println(max);

Then your markVisited method should return the count of cells visited, so change the signature to:
public static int markVisited(int[][] M, boolean[][] visited, int x, int y, int R, int C)

Finally you need to accumulate the count as you recurse into the neighbors of a cell:
int L = 1;
for (int k = 0; k < 8; k++) {
    if (isSafe(M, visited, x + x_pos[k], y + y_pos[k], R, C)) {
        L += markVisited(M, visited, x + x_pos[k], y + y_pos[k], R, C);
    }
}
return L;

With these changes you get the desired output, regardless of the order in which you visit neighbors:
1 1 1 1 0 0 1
1 0 1 0 1 1 0
0 0 0 0 1 0 1
1 0 0 0 1 1 1
14


text:
Q: SPSS Selecting cases (outliers) seperately for each split file I divided my dataset in 10 groups (because I have 10 different industries). Now, in SPSS one can use "select cases" to get rid of outliers.This is fine. However, I want to apply a different "select cases" rule for each of the 10 groups because it would be wrong to just set the same threshold value for each industry. Does anybody know how to do it?
Many thanks for your help guys!
Cheerz
Steven


text:
Q: A sequence where $d(x_{n}, x_{n+1})\leq\frac{1}{n^2}$ for all $n\geq 1$ Let $(X,d)$ be a metric space. Suppose I've got a sequence $\{x_{n}\}_{n=1}^{\infty}$ with the property that $d(x_{n}, x_{n+1})\leq\frac{1}{n^2}$ for all $n\geq 1$.
I'm trying to prove that $d(x_{m},x_{n}) \leq \frac{1}{m-1}$ for all $2 \leq m \leq n$.
MY ATTEMPT:
Fix $m,n\in\mathbb{N}$ such that $2 \leq m \leq n$. Define the integer $k=n-m$. Since $m\leq n$ we are guaranteed that $k \geq 0$. Then write:
$d(x_{m},x_{n}) = d(x_{m},x_{m+k}) \leq d(x_{m},x_{m+1})+d(x_{m+1},x_{m+2})+\dots + d(x_{m+k-1},x_{m+k})$
$=\sum\limits_{j=0}^{k-1}d(x_{m+j},x_{m+j+1})$
$\leq \sum\limits_{j=0}^{k-1} \frac{1}{(m+j)^2}$
So it would seem that I need to show that $\sum\limits_{j=0}^{k-1} \frac{1}{(m+j)^2} \leq \frac{1}{m-1}$. I have no clue how to do this. I am unable to add up this summation. Am I even attempting this in the right way?

A: By drawing the graph of $y=\frac1{x^2}$ you can see that
$$\sum_{k=m}^{n-1}\frac1{k^2}<\int_{m-1}^{n-1} \frac{dx}{x^2}<\int_{m-1}^\infty \frac{dx}{x^2}=\frac1{m-1}\ .$$

A: Or more simple
$$
\frac1{k^2}<\frac{1}{k(k-1)}=\frac1{k-1}-\frac1k
$$
and then apply telescoping sums.


text:
Q: How to test type equality at type-level in scala? I would like to do some type level programming.
Scala type macros are dead, and it seems that shapeless is unable to do what I want.
All my problems would be resolve if I can get the following code to work
(this code is borrowed from http://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala/ and http://michid.wordpress.com/2010/06/18/type-level-programming-equality/)
It shows the implementation of a HList that has a "type remove" operator.
The bug come from the "EQ" structure that test wether two type are equivalent in order to remove then or not.
It seems to always return false in my case. I think that it's because I'm using "aliases" (?) but i do not see how to overcome this difficulty.
class Root {

  def typed[T](t: => T) {}
}

trait BooleanCompute extends Root {

  trait BOOL {
    type OUT <: BOOL

    type SELECT[TrueAction <: Action, FalseAction <: Action, Action] <: Action
  }

  case class TRUE() extends BOOL {
    type OUT = TRUE

    type SELECT[TrueAction <: Action, FalseAction <: Action, Action] = TrueAction
  }

  case class FALSE() extends BOOL {
    type OUT = FALSE

    type SELECT[TrueAction <: Action, FalseAction <: Action, Action] = FalseAction
  }

}
object  BooleanCompute extends BooleanCompute

import BooleanCompute._

case class Equality[A]() {
  def check(x: A)(implicit t: TRUE) = t

  def check[B](x: B)(implicit f: FALSE) = f
}

object Equality {
  def witness[T] = null.asInstanceOf[T]

  implicit val t: TRUE = null
  implicit val f: FALSE = null
}

trait EQ[A, B] extends {

  import Equality._

  type OUT = out.type
  val out = Equality[A]() check witness[B]

  val test1 = Equality[List[Boolean]] check witness[List[Boolean]]
  implicitly[test1.OUT =:= TRUE]
  // Does not compile since tt is True
  //implicitly[test1.t =:= FALSE]

  val test2 = Equality[Nothing] check witness[AnyRef]
  // Does not compile since ft is False
  // implicitly[test2.t =:= TRUE]
  implicitly[test2.OUT =:= FALSE]
}

object HList extends Root {

  type :+:[H, T <: HList] = HCons[H, T]
  val :+: = HCons

  sealed trait HList {
    self: HList =>

    type SELECT[ConsAction <: Action, NilAction <: Action, Action] <: Action

    type Remove[A] <: HList
  }

  final case class HCons[Head, Tail <: HList](head: Head, tail: Tail) extends HList {
    self: HList =>

    type SELECT[ConsAction <: Action, NilAction <: Action, Action] = ConsAction

    type Remove[A] = SELECT[
      EQ[Head, A]#OUT#SELECT[Tail#Remove[A], Head :+: Tail#Remove[A], HList],
      HNil,
      HList]

    def :+:[T](v: T) = HCons(v, this)
  }

  sealed case class HNil() extends HList {
    type SELECT[ConsAction <: Action, NilAction <: Action, Action] = NilAction

    type Remove[A] = HNil

    def :+:[T](v: T) = HCons(v, this)
  }

}

object yo extends App {

  import HList._

  case class AA()
  case class BB()
  case class CC()
  case class DD()

  type YO =  AA :+: BB :+:CC :+: HNil
  type YoRemoved =  AA :+:  CC :+: HNil
  val a = AA() :+: CC() :+: HNil()

  typed[YoRemoved](a)
  typed[YO#Remove[BB]](a)
}

A: What's the issue you're having with shapeless? The following works perfectly well,
scala> val yo = AA() :: BB() :: CC() :: HNil
yo: AA :: BB :: CC :: HNil = AA() :: BB() :: CC() :: HNil

scala> typed[YO](yo) // Compiles

scala> val yoRemoved = yo.filterNot[BB]
yoRemoved: AA :: CC :: HNil = AA() :: CC() :: HNil

scala> typed[YoRemoved](yoRemoved)  // Compiles


text:
Q: MySQL query WHERE NOT EQUAL not working I have 3 tables in my DB: recipes, ingredients and recipe_ingredients. Recipes and ingredients are connected with many-to-many, so the table recipe_ingredients is a junction table. I want to select all recipes from table recipes, which does not include ingredient with id X. And it's still returns all the recipes. If I write a query to return recipes with ingredient X, it works. Here's my query:
select * from recipes
join recipe_ingredients ON recipes.id = recipe_ingredients.fk_Recipe
join ingredients ON recipe_ingredients.fk_Ingredient = ingredients.id
where recipe_ingredients.fk_Ingredient != 307
GROUP by recipes.url

A: Any recipe that as an ingredient other than 307 will satisfy the condition.
That is, to this query, it doesn't matter if one of the ingredients is 307, as long as the recipe has some other ingredient other than 307, it's a match.
To get recipes that do not have 307 as an ingredient, we can use an anti-join or a NOT EXISTS

anti-join pattern
 SELECT r.id
      , r.url
   FROM recipes r
   LEFT
   JOIN recipe_ingredients s
     ON s.fk_recipe     = r.id
    AND s.fk_ingredient = 307
  WHERE s.fk_ingredient IS NULL

-or-
not exists pattern
 SELECT r.id
      , r.url
   FROM recipes r
  WHERE NOT EXISTS
        ( SELECT 1
            FROM recipe_ingredients s
           WHERE s.fk_recipe     = r.id
             AND s.fk_ingredient = 307
        )

FOLLOWUP
To return recipes that do not have 307 as an ingredient, but do have 42 as an ingredient...
 SELECT r.id
      , r.url
   FROM recipes r
   JOIN recipe_ingredients t
     ON t.fk_recipie    = r.id
    AND t.fk_ingredient = 42
   LEFT
   JOIN recipe_ingredients s
     ON s.fk_recipe     = r.id
    AND s.fk_ingredient = 307
  WHERE s.fk_ingredient IS NULL

-or-
 SELECT r.id
      , r.url
   FROM recipes r
  WHERE NOT EXISTS
        ( SELECT 1
            FROM recipe_ingredients s1
           WHERE s1.fk_recipe     = r.id
             AND s1.fk_ingredient = 307
        )
    AND EXISTS
        ( SELECT 1
            FROM recipe_ingredients s2
           WHERE s2.fk_recipe     = r.id
             AND s2.fk_ingredient = 42
        )

A: The problem is that you will still include a recipe if it has at least one ingredient that is not 307, as that ingredient will pass the where condition.
You could use a having condition, like this:
select   recipes.url
from     recipes
    join recipe_ingredients on recipes.id = recipe_ingredients.fk_Recipe
    join ingredients        on ingredients.id = recipe_ingredients.fk_Ingredient
group by recipes.url
having   not(sum(recipe_ingredients.fk_Ingredient = 307))

When using this in combination with "positive" conditions, i.e. where a certain ingredient must be used, then keep using the same pattern, but this time without not:
select   recipes.url
from     recipes
    join recipe_ingredients on recipes.id = recipe_ingredients.fk_Recipe
    join ingredients        on ingredients.id = recipe_ingredients.fk_Ingredient
group by recipes.url
having   not(sum(recipe_ingredients.fk_Ingredient = 307))
   and   sum(recipe_ingredients.fk_Ingredient = 1105)

When on top of that you have conditions on the number of ingredients, then add a count condition in the having clause, for instance:
select   recipes.url
from     recipes
    join recipe_ingredients on recipes.id = recipe_ingredients.fk_Recipe
    join ingredients        on ingredients.id = recipe_ingredients.fk_Ingredient
group by recipes.url
having   not(sum(recipe_ingredients.fk_Ingredient = 307))
   and   sum(recipe_ingredients.fk_Ingredient = 1105)
   and   count(*) = 2

This method should be very efficient: it does not require to perform a sub query or to join the same table more than once.


text:
Q: How does a compiler string together addresses in a linked list? How does a compiler know which nodes to point to next in a linked list since each node's next or previous can be anywhere in the heap. Can i attach a specific memory address say 0x00000001 to a pointer and bind it to that address?

A:
Also, can you bind a specific address to a pointer?

Yes. In fact, that is precisely the purpose of a pointer. Memory is addressed by numbers. The first byte is in the address 0, the next is 1 and so on. A pointer is essentially an object that stores a memory address, which is internally simply a number.
In following example, we store the address of the object i into a pointer:
int i;
int* ptr = &i;

How does a compiler string together addresses in a linked list

A linked list node is simply a structure with a pointer to the next (and previous in case of doubly linked list) node. The address of the next node is stored in the pointer.

how does the compiler allocate [...] these addresses during runtime?

In whatever way the language implemnetation chooses to allocate. The language does not specify "how" memory is allocated. The way will differ depending on the storage duration class of the object.
Typically in practice, the language implementation will ask the operating system to map some memory. Variables with automatic storage are stored in what is called the "call stack", and dynamic objects are stored in "free store". How either of these are implemented is outside the scope of my answer. I would suggest studying how operating systems and compilers are made. It's a wide topic.

how does the compiler [...] reference these addresses during runtime?

It stores the address. There are CPU instructions for accessing memory at given address.

Can I for example , bind 0x00000001 to node3?

I don't know what "node3" is, but you can point at the address 1 if you want to. There's not much you can do with the pointer unless there actually is an object at the address. There's no way of creating objects into unallocated memory, and there is no way of allocating memory from arbitrary address in standard C++.


text:
Q: Android Internet connectivity I've recently downloaded Android x86 (Android 4.0) and installed it in VirtualBox using using android-x86-4.0-RC1-eeepc.iso. Everything is working fine except the Internet connection. I've tried searching for a solution but none of them works for me.
I'm using a Samsung notebook with a wireless connection on Ubuntu 11.10.
Here's a screenshot of the network settings of the VirtualBox:

I've even tried with NAT, but it still dosen't work.

A: There is one made for VirtualBox that seems to work, see How To Run Android 4.0 ICS On Windows, Mac & Linux Using VirtualBox. I notice in VirtualBox that networking is configured for port forwarding and in Android it shows

Internet Not Connected

but it works anyway.


text:
Q: Converting a pointer into a MemoryStream? I am trying to fetch a Device Independent Bitmap from the clipboard. I am well-aware that this can be done through the Clipboard.GetData function inbuilt in the .NET Framework, but since it is very buggy (as documented many places on the web), I want to use the APIs only.
I have written the following code which works.
//i can correctly cast this to a MemoryStream
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream;

But I want to use it with the APIs, which just return a pointer (an IntPtr) that point to the stream somehow. I took a look at the UnmanagedMemoryStream but fail to understand how to correctly convert an IntPtr into that.
Here's my API code (using the GetClipboardData API where the CF_DIB format is set as its argument).
IntPtr p = GetClipboardData(8);
//what do I do from here to get a MemoryStream from this pointer?

I'm a bit confused. I already researched it myself, but couldn't come up with something useful.

A: As you said you can use UnmanagedMemoryStream(byte* pointer, long length) and to use it you should have a pointer and the length of the bytes. So you can use IntPtr.ToPointer() method to get the pointer, but you should know the length of the memory content.
UnmanagedMemoryStream unmanagedmemstream = UnmanagedMemoryStream(p.ToPointer(), 100);

There is another method to retrieve an array of bytes, but also here you should know the length of the memory bytes that you want and it is Marshal.Copy(IntPtr source, byte[] destination, int startIndex,int length):
byte[] buffer = new byte[100];
Marshal.Copy(p , buffer, 0, buffer.Length);


text:
Q: How do I define an array of arrays of scalars in Symfony Configuration.php? I want to parse a YAML configuration that looks like this:
pageRoles:
  Report1: [abc, xyz, def]
  Report2: [fgh, xxx, yyy, rrr]

I want the resulting configuration array to look like this:
'pageRoles':
  'Report1':
    [
      'abc',
      'xyz',
      'def'
    ],
  'Report2':
    [
      'fgh',
      'xxx',
      'yyy',
      'rrr'
    ]

I have this at the moment:
    ->arrayNode( 'pageRoles' )
      ->prototype( 'array' )
        ->useAttributeAsKey( 'name' )
        ->prototype( 'array' )
          ->prototype( 'scalar' )->end()
        ->end()
      ->end() // array prototype
    ->end() // pageRoles

And am getting this error:

Invalid type for path "site.pageRoles.ActivityReport.0". Expected
array, but got string

What am I missing?

A: Making Symfony configuration trees.  My favorite way to kill a boring day.  This seems to work:
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('my');
        $treeBuilder->getRootNode()
            ->children()
                ->arrayNode('pageRoles')
                    ->useAttributeAsKey('name')
                     ->arrayPrototype()->scalarPrototype()->end()->end()
                ->end() // pageRoles
            ->end() // root node
        ;
        return $treeBuilder;
    }

After processing I get:
array:1 [
  "pageRoles" => array:2 [
    "Report1" => array:3 [
      0 => "abc"
      1 => "xyz"
      2 => "def"
    ]
    "Report2" => array:4 [
      0 => "fgh"
      1 => "xxx"
      2 => "yyy"
      3 => "rrr"
    ]
  ]
]


text:
Q: Use poll() to check for file modification There is a file and I would like to check it with poll() that the contents have changed.
On Raspi there is a file called gpio value, if the value changed the poll() was triggered with POLLPRI, I would like to do the same with an ordinary file.
Here is the code I am using to check the GPIO file:
int gpio_fd = gpio_fd_open();
int timeout = POLL_TIMEOUT;
struct pollfd fdset;
int nfds = 1;
char *buf[MAX_BUF];
int len;
int rc;
fdset.fd = gpio_fd;
fdset.events =  POLLPRI | POLLERR | POLLHUP | POLLNVAL; // POLLIN | | POLLOUT
unsigned int c1, c2, c3;
do{
    rc = poll(&fdset, 1, timeout);

And the gpio_fd_open function:
int gpio_fd_open() {
    printf("opening File: " SYSFS_GPIO_DIR "\n");

    int fd, len;
    char buf[MAX_BUF];

    len = snprintf(buf, sizeof (buf), SYSFS_GPIO_DIR);
    fd = open(buf, O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
        perror("gpio/fd_open");
    }
    return fd;
}

A: In Linux, unlike with your special GPIO file, you can not poll the fd to an open ordinary file like that.
To watch a file for changes you can use the inotify family of functions.  Conveniently for you they use a file descriptor which can be passed to poll() along with your GPIO file descriptor, so you can watch both at the same time.
So, some minor additions/changes to your code:
int fw_fd = file_watch_fd("/some/file/to/watch");
struct pollfd fdset[2];
int nfds = 2;
int rc;
fdset[0].fd = gpio_fd;
fdset[0].events =  POLLPRI | POLLERR | POLLHUP | POLLNVAL;
fdset[1].fd = fw_fd;
fdset[1].events = POLLIN;
do {
    rc = poll(fdset, nfds, timeout);

You are polling on the inotify fd, which you read to return one more watched events which occurred.  Since this code is only watching one file for one event, we're pretty sure what the event is, but we still need to read it out of the fd, then we can actually read the file.
    if (fdset[1].revents & POLLIN) {
        if (ready(fw_fd)) {
            /* file has changed, read it */
        }
    }

Here is the file_watch_fd() function:
int file_watch_fd ( const char * filename ) {
        static int      inot    = ERR;
        static int      iflags  = IN_CLOEXEC | IN_NONBLOCK;
        static uint32_t mask    = IN_MODIFY;
        int             watch;

        if (inot == ERR) {
                inot = inotify_init1(iflags);
                if (inot == ERR) return ERR;
        }
        watch = inotify_add_watch(inot, filename, mask);
        if (watch == ERR) return ERR;
        return inot;
}

And here is the ready() function:
int ready ( int inot ) {
        uint64_t                buffer[8192];
        ssize_t                 nr;
        char *                  p;
        size_t                  n;
        struct inotify_event *  evP;
        int                     ready   = 0;

        while ((nr = read(inot, (char *)buffer, sizeof(buffer))) > 0) {
                for (p = buffer; p < buffer + nr; p += n) {
                        evP = (struct inotify_event *)p;
                        if (evP->mask & IN_MODIFY) ready = 1;
                        n = sizeof(struct inotify_event) + evP->len;
                }
        }
        return ready;
}

(People experience in the use of inotify will notice that I ran roughshod over the functionality of it to keep this example as simple as I can)


text:
Q: Detect whether sentence contains a word in a file When the user enters something, the script is suppose to check if the input contains any of the words from the wordfile.
Input:
A sentence that contains the word, word1.

Wordfile:
word1
word2
word3

Code:
[[ -z $(cat 'vocabulary/lists/wordfile' | grep -Fe $($input//" "/"\|")) ]]

Output:
> [WORD]
./core.sh: line 168: [WORD]// /\|: No such file or directory
grep: option requires an argument -- 'e'
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
[WORD]

A: I think that this might be what you need:
grep -Fqf wordfile <<<"$input" && echo 'found a word'

This does a fixed string match (-F) using patterns from the file wordfile (-f wordfile) and uses -q to silently exit successfully if any matches are found.
For example:
$ cat wordfile
apple
ball
cat
$ input='a string containing the word ball'
$ grep -Fqf wordfile <<<"$input" && echo 'found a word'
found a word

A: Try this :
[[ -n $(sed -n -f <(sed 's/^/\//g;s/$/\/p/g' vocabulary/lists/wordfile) <<< "$input") ]] && echo Found


text:
Q: Trying to understand ISO image in context of VirtualBox I have created a CentOS VM on VirtualBox. I have used an ISO image to boot it.
Now, in the CentOS VM image, there is an option to install to hard drive. I chose that option, went through all the installation steps. But even after that, in the settings window for the VM, the IDE controller is shown as the iso image wit the same location of the iso file.
Is this how an installation using ISO image supposed to behave?
I am confused because, when I use live CD or DVD to install a VM, I can then remove the DVD or CD and the VM still works. But here it seems that I am always dependent on the iso image being perpetually present in my machine. Is that so?

A: In the storage page of the settings window for the VM you are shown all the IDE and SATA controllers that exist in the virtual machine. By default VirtualBox seems to create virtual IDE optical drives and virtual SATA hard drives (you can change that, but you probably don't need to).
I suspect that what you are seeing is that the Centos ISO file image is still associated with the virtual optical drive. That just means that when you start the VM Centos will think that the CD is still inserted in the drive. You can "eject" the CD from the "Devices" menu of the VM by selecting "CD/DVD Devices" and "Remove disk from virtual drive".
You probably want to install the VirtualBox guest additions, though. When you do that VirtualBox will replace the Centos virtual CD with the guest additions virtual CD.


text:
Q: Using same foreign key twice in a model in django as different fields I have a model Transaction Type that has credit_account and debit_account fields. Both fields are foreign keys from the Account model. Is it good idea to have them like the way I have implemented below?
class TransactionType(models.Model):
    name = models.CharField(max_length=255)
    organization = models.IntegerField(null=False, blank=False)
    credit_account = models.ForeignKey(Account)
    debit_account = models.ForeignKey(Account)

Account Model
class Account(MPTTModel):

    TYPES = Choices(
        ("AS", "asset", "Asset"),  # Eg. Cash in bank
        ("LI", "liability", "Liability"),  # Eg. Loans, bills paid after the fact (in arrears)
        ("IN", "income", "Income"),  # Eg. Sales, housemate contributions
        ("EX", "expense", "Expense"),  # Eg. Office supplies, paying bills
        ("EQ", "equity", "Equity"),  # Eg. Money from shares
        ("TR", "trading", "Currency Trading"),  # Used to represent currency conversions
        ("OR", "operating_revenues", "Operating Revenues"),
        ("OX", "operating_expenses", "Operating Expenses"),
        ("NR", "nonoperating_revenues", "Non-Operating Revenues"),
        ("NX", "nonoperating_expenses", "Non-Operating Expenses"),
    )

    uuid = SmallUUIDField(default=uuid_default(), editable=False)
    name = models.CharField(max_length=255,blank=True, null=True)
    parent = TreeForeignKey(
        "self",
        null=True,
        blank=True,
        related_name="children",
        db_index=True,
        on_delete=models.CASCADE,
    )
    code = models.CharField(max_length=3, null=True, blank=True)
    full_code = models.CharField(max_length=100, db_index=True, unique=True, null=True, blank=True)
    account_type = models.CharField(max_length=255,choices=TYPES, blank=True)
    # is_bank_account = models.BooleanField(default=False, blank=True,)
    currencies = ArrayField(models.CharField(max_length=255, db_index=True))
    organization = models.IntegerField(null=False, blank=False)

    objects = AccountManager.from_queryset(AccountQuerySet)()

A: It is generally not a bad idea but you should add a related_name so Django can differentiate between them in related queries

A: You will need to add different related names for both the foreign keys and you are gtg.


text:
Q: minimum number of character deletions (of both) required to turn these strings into anagrams? Two strings are given,how many minimum number of character deletions (of both) required to turn these strings into anagrams.
Constraint: Need to use single hash
aaabbc abc
Output - 3 ( 2 a and 1 b)
I was able to achieve this using two hashes and tried below solution using one hash -
my $str1 = 'aaabbc';
my $str2 = 'abc';

my %h;

map{$h{$_}++} sort(//,$str1);
map{$h{$_}++} sort(//,$str2);

my $c = 0;

foreach (keys(%h)) {
    if($h{$_} == 1) {
        $c++;
    }
}

print "$c\n";

It will fail in many case like ('xxx', 'yyy').
Any suggestions?

A: To use a single hash (smells like homework) increment the count for characters in the first string and decrement it for characters in the second string. Equal numbers of the same character will cancel out. Any non-zero values that remain are the magnitude of the difference, so take the absolute value when tallying the total number of differences.
my $str1 = 'aaabbc';
my $str2 = 'abc';
my %h;
my $c;

$h{$_}++ foreach split //, $str1;
$h{$_}-- foreach split //, $str2;

$c += abs($_) foreach values %h;

print $c;


text:
Q: How do you stub all methods of a particular mock instance I have a particular mock that is being handled by a third party. I just want to check that the same mock has been returned back.
However, the third party calls array methods and save methods that my test doesnt really care about. Is there a way to tell my mock that it expects/stub all methods to do with that particular mock instance?
eg.
user = mock(User)
user.stub_all

Thanks!
EDIT
More info about the problem:
Test:
  it "creating an invitation should return invitation" do
    invitation = mock_model(Invitation)
    invitation.stub(:[]=)
    invitation.stub(:save)
    Invitation.stub(:create).and_return(invitation)
    @user.create_invitation
    @user.create_invitation.should == invitation
  end

Code being tested:
 def create_invitation
    invitation = Invitation.create
    self.invitations.push(invitation)
    return invitation
  end

I need to mock the following which are not directly related to what I am testing:
invitation.stub(:[]=)
invitation.stub(:save)

A: The answer is
user = mock(User).as_null_object

but in general this approach means your objects are too large and your tests aren't granular enough

A: I came across this accidentally - but the 'blessed' way of doing this (now) is using the spy method, which essentially is the same thing as above:
reference: https://thoughtbot.com/blog/a-closer-look-at-test-spies
You don't have to stub out any methods that the class implements already.


text:
Q: Collision stops all characters moving in the list I am making a game where characters come from opposite sides of the screen and collide and attack each other then they are removed when they die. I have managed to enable the lists to stop moving and do damage when they collide but my problem is when 2 of them collide all of them stop moving.
My code for the shortswordsman collisions is:
private void shortMoveCollisions(GameTime gameTime)
    {
        Rectangle shortRect;
        int shortSpeed = 2;
        int shortDamage = 20;
        bool collided = false;

        for (int i = 0; i < shortList.Count; i++)
        {
            List<Goblin> tempGoblinList = new List<Goblin>(goblinList);
            shortRect = new Rectangle((int)shortList[i].position.X, (int)shortList[i].position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);

            foreach (Goblin goblin in tempGoblinList)
            {
                Rectangle goblinRect = new Rectangle((int)goblin.position.X, (int)goblin.position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
                if (shortRect.Intersects(goblinRect))
                {
                    collided = true;
                    shortList[i].AnimateAttack(gameTime);

                    shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (shortTimer >= shortDelay)
                    {
                        shortTimer -= shortDelay;
                        goblin.health -= shortDamage;
                        if (goblin.health <= 0)
                        {
                            goblinList.Remove(goblin);
                        }
                    }
                }
            }
            if (shortRect.Intersects(background.badCastleRect))
            {
                collided = true;
                shortList[i].AnimateAttack(gameTime);

                shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (shortTimer >= shortDelay)
                {
                    shortTimer -= shortDelay;
                    badCastleHealth -= shortDamage;
                }
             }
            if (collided == false)
            {
                shortList[i].AnimateWalk(gameTime);

                shortList[i].position.X += shortSpeed;
            }
        }
    }

And my code for the goblins collisions is:
private void GoblinMoveCollisions(GameTime gameTime)
    {
        Rectangle goblinRect;
        int goblinSpeed = 2;
        int goblinDamage = 20;
        bool collided = false;

        for (int i = 0; i < goblinList.Count; i++)
        {
            List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);
            goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);

            foreach (ShortSwordsman shortSwordsman in tempShortList)
            {
                Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
                if (goblinRect.Intersects(shortRect))
                {
                    collided = true;
                    goblinList[i].AnimateAttack(gameTime);

                    goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (goblinAttackTimer >= goblinAttackDelay)
                    {
                        goblinAttackTimer -= goblinAttackDelay;
                        shortSwordsman.health -= goblinDamage;
                        if (shortSwordsman.health <= 0)
                        {
                            shortList.Remove(shortSwordsman);
                        }
                    }
                }
            }
            if (goblinRect.Intersects(background.goodCastleRect))
            {
                collided = true;
                goblinList[i].AnimateAttack(gameTime);

                goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (goblinAttackTimer >= goblinAttackDelay)
                {
                    goblinAttackTimer -= goblinAttackDelay;
                    goodCastleHealth -= goblinDamage;
                }
            }
            if (collided == false)
            {
                goblinList[i].AnimateWalk(gameTime);

                goblinList[i].position.X -= goblinSpeed;
            }
        }
    }

A: Your collided bool shouldn't be a variable of those classes, as those classes seem to operate on the entire lists of all the entities. Instead the collision detection should happen on an entity by entity basis, basically: make the collided bool a property of goblins and swordsmen. This would mean that you'll have to check for intersections with other creatures of the same type as well, probably without an attack command.

A: This is the code I am using at the moment - shortswordsman and goblin are the same so i will only show one:
In the goblin class:
public Goblin(Vector2 position, float health, bool Collided, Rectangle goblinRect)
    {
        this.position = position;
        this.health = health;
        this.Collided = Collided;
        this.goblinRect = goblinRect;
    }

In the game1 class:
void CreateGoblin()
    {
        goblinList.Add(new Goblin(new Vector2(1900, 270), 100, false, new Rectangle()));
    }

And then for the collisions i tried this - this includes the bit to try and stop them overlapping each other:
private void GoblinMoveCollisions(GameTime gameTime)
    {
        int goblinSpeed = 2;
        int goblinDamage = 20;

        for (int i = 0; i < goblinList.Count; i++)
        {
            goblinList[i].Collided = false;
            goblinList[i].goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
            List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);

            foreach (ShortSwordsman shortSwordsman in tempShortList)
            {
                Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
                if (goblinList[i].goblinRect.Intersects(shortRect))
                {
                    goblinList[i].Collided = true;
                    goblinList[i].AnimateAttack(gameTime);

                    goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (goblinAttackTimer >= goblinAttackDelay)
                    {
                        goblinAttackTimer -= goblinAttackDelay;
                        shortSwordsman.health -= goblinDamage;
                        if (shortSwordsman.health <= 0)
                        {
                            shortList.Remove(shortSwordsman);
                        }
                    }
                }
            }
            if (goblinList[i].goblinRect.Intersects(background.goodCastleRect))
            {
                goblinList[i].Collided = true;
                goblinList[i].AnimateAttack(gameTime);

                goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (goblinAttackTimer >= goblinAttackDelay)
                {
                    goblinAttackTimer -= goblinAttackDelay;
                    goodCastleHealth -= goblinDamage;
                }
            }
            if (goblinList[i].goblinRect.Intersects(goblinList[i].goblinRect))
            {
                goblinList[i].Collided = true;
                goblinList[i].AnimateStill(gameTime);
            }
            if (goblinList[i].Collided == false)
            {
                goblinList[i].AnimateWalk(gameTime);
                goblinList[i].position.X -= goblinSpeed;
            }
        }
    }


text:
Q: updating data in codiegniter with out selecting the file field in form I am updating the data in database where I have images file too .So what i want is to put the condition on the image input field if the user want to update data as well as the image so the image will be updated accordingly and if user don't want to update image the rest of the data will be updated now I am having problem in getting the image input field data in controller. I am unable to get the filename directly in controller please help me out.
Here is the code.
function save_update()
    {
         $id=$this->input->post('id');

        if(!empty($_FILES['userfile']['name']))
        {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2048';
        $config['max_width']  = '2000';
        $config['max_height']  = '2000';
        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_successful', $error);
        }
        else
        {

                $data1 = $this->upload->data();
                $filename=$data1['file_name'];

        $data=array(
        'pname'=>$this->input->post('product_name'),
        'pprice'=>$this->input->post('product_price'),
        'pquantity'=>$this->input->post('product_quantity'),
        'pcategory'=>$this->input->post('category'),
        'product_pic'=>$filename
        );
      $result=$this->cartmodel->update_data($data,$id,'product');
        }
      }

     else
     {
        $data=array(
        'pname'=>$this->input->post('product_name'),
        'pprice'=>$this->input->post('product_price'),
        'pquantity'=>$this->input->post('product_quantity'),
        'pcategory'=>$this->input->post('category'),
        'product_pic'=>$this->input->post('oldfile')
        );
      $result=$this->cartmodel->update_data($data,$id,'product');
      if($result==true)
      {
          redirect('cart/admin');
      }
      else
      {
          echo '';
      }

     }

    }

Html is here.
<form class="form-horizontal" method="post" action="<?php echo base_url(); ?>cart/save_update" enctype="multipart/form-data">
                    <?php
                    if(isset($specific))
                    {?>
                                  <fieldset>
                                    <legend>Form Components</legend>

                                      Product Name

                                        <input type="text" class="span6" id="typeahead"  name="product_name" value=
                                        "<?=$specific->pname;   ?>">

                                    <input type="hidden" name="id" value="<?=$specific->pid ?>">

                                      Price

                                        <input type="text" class="span6" id="typeahead"  name="product_price"
                                        value=
                                        "<?=$specific->pprice;   ?>">

                                      Quantity

                                        <input type="number" class="span6" id="typeahead"  name="product_quantity"
                                        value=
                                        "<?=$specific->pquantity;   ?>">

                                      Category

                                        <select name="category">
                                        <option value=
                                        "<?=$specific->pcategory;   ?>"><?=$specific->pcategory;   ?></option>

                                        </select>

                                      Product Pic

                                        <input type="file" class="span6" id="typeahead"  name="userfile" >

                                   <input type="hidden" name="oldfile" value="<?=$specific->product_pic;   ?>" >

                                      <button type="submit" class="btn btn-primary">Save changes</button>
                                      <button type="reset" class="btn">Cancel</button>

                                  </fieldset>
                                         <?php
                }
                    ?>
                                </form>

A: Replace
if(!empty($_FILES['userfile']['name']))

With
if(isset($_FILES['userfile']))

It is best practice to use isset() to see whether the data is being set or not

A: Replace

if ( ! $this->upload->do_upload())

With

if ( ! $this->upload->do_upload($_FILES['userfile']['name']))


text:
Q: Keyboard shorcuts like copy, paste, select all not working 14.04 Fresh install of 14.04 unity ubuntu. These shortcuts don't work.
Was not able to find the solution. Has anybody has the same problem?

A: From what I understand this may be a bug in 14.04 Unity. See bug report here looks like a few others have had some problems
https://bugs.launchpad.net/ubuntu/+source/gnome-control-center/+bug/1224732
Looks like this was for 13.10 but seems can affect 14.04 unity desktop as well. Maybe try using Compiz to set your own shortcuts up and see if that helps...
I am running Xubuntu 14.04 and don't have any problems. Hope this helps...


text:
Q: Find the limit $\lim_{n\to\infty} \frac{(3n)! \, e^n}{(2n)!\,n^n\,8^n}$ Find $$\lim_{n\to\infty} \frac{(3n)! \, e^n}{(2n)!\,n^n\,8^n}$$
I tried by simplifying $n!$ divided by $n! = 1$? What should I do next? I get then $3!e^n / 2!n^n8^n$

A: HINT
$$
\frac{(3n)! e^n}{(2n)! n^n 8^n}
  = \left(\frac{e}{8n}\right)^n \prod_{k=1}^n (2n+k)
  = \prod_{k=1}^n \frac{2n+k}{8n/e}
  = \prod_{k=1}^n \left(\frac{e}{4} + \frac{ke}{8n}\right)
$$

A: Alternative Method:
Obviously, $$0\le\frac{(3n)! e^n}{(2n)! n^n 8^n}$$
Also, observe $$\frac{(3n)! e^n}{(2n)! n^n 8^n}=\frac{(3n)!}{(2n)!}\cdot(\frac{e}{8n})^n\le\frac{(3n)^n}{n^n}\cdot(\frac{e}{8n})^n=(\frac{3e}{8n})^n$$
So
$$0\le\frac{(3n)! e^n}{(2n)! n^n 8^n}\le(\frac{3e}{8n})^n$$
$$\lim_{n\to\infty}0\le\lim_{n\to\infty}\frac{(3n)! e^n}{(2n)! n^n 8^n}\le\lim_{n\to\infty}(\frac{3e}{8n})^n$$
$$0\le\lim_{n\to\infty}\frac{(3n)! e^n}{(2n)! n^n 8^n}\le0$$
So by Squeeze Theorem,
$$\lim_{n\to\infty}\frac{(3n)! e^n}{(2n)! n^n 8^n}=0$$


text:
Q: Using collection_select for saving ID of two classes in a booking through has_many and belongs_to association throws error 'must exist' when saving I am building a simple booking application for learning rails. I scaffolded people, cars and bookings.
Now when I try to create bookings I get

2 errors prohibited this booking from being saved:

*

*Person must exist

*Car must exist

Code
car.rb
class Car < ApplicationRecord
  has_many :bookings

  def brand_with_licence_plate
    "#{brand} #{licence_plate}"
  end

end

person.rb
class Person < ApplicationRecord
  has_many :bookings

  def complete_name
    "#{first_name} #{last_name}"
  end

end

bookings.rb
class Booking < ApplicationRecord
  belongs_to :Person
  belongs_to :Car
end

I added the columns for ID like so:
class AddItemsToBookings < ActiveRecord::Migration[6.1]
  def self.up
    add_column :bookings, :car_id, :integer
    add_column :bookings, :person_id, :integer
  end
end

I added to following to _form.html.erb

    <%= form.label :Person %>
    <%= form.collection_select(:person_id, Person.all, :id, :complete_name) %>

    <%= form.label :Car %>
    <%= form.select :car_id, options_from_collection_for_select(Car.all, 'id','brand_with_licence_plate') %>

and added to bookings_controller.rb
def booking_params
      params.require(:booking).permit(:start, :end, :person_id, :car_id)
end

I have looked here and tried to change to <%= form.select :car_id, options_from_collection_for_select(Car.all, 'id', 'brand_with_licence_plate') %> as stated in one answer, but giving me the same error.
When I look at the documentation everything seems to be fine as well.
It seems as if am missing something fundamental here. Any ideas how to fix this are appreciated.

Update:
I deleted the integer id column and run a new migration
class AddReferencesToBookingForPersonAndCar < ActiveRecord::Migration[6.1]
  def change
    add_reference :bookings, :people, foreign_key: true
    add_reference :bookings, :cars, foreign_key: true
  end
end

and adjusted the permissions for params as well.

A: You code doesn't look ok to me. I would change it like:
class Booking < ApplicationRecord
  belongs_to :person
  belongs_to :car
end

Mainly, person and car are lower case. Also, I noticed that in your migration you create cars, in plural. It should be:
class AddReferencesToBookingForPersonAndCar < ActiveRecord::Migration[6.1]
  def change
    add_reference :bookings, :person, foreign_key: true
    add_reference :bookings, :car, foreign_key: true
  end
end

belongs_to :car expects a car_id and it looks like that the migration is creating a cars_id instead.
It would be easier to provide more help if you post the full controller code.


text:
Q: distorted Mesh with threejs Hi I am trying to draw a model in threejs.
I tried drawing it with lines resulting in a correct representation of the bim model.
Drawing it with a mesh results in a distorted model
My approach to drawing it with a Mesh is
let vertices = [];
for (let part of this.BUILDINGINFORMATION) {
  for (let point of part.Polyhedron.Points) {
    vertices.push(point);
  }
}
let holes = [];
let triangles, mesh;
this.GEOMETRY= new THREE.Geometry();
this.GEOMETRY.vertices = vertices;
triangles = new THREE.ShapeUtils.triangulateShape(vertices, holes);
for (let i = 0; i < triangles.length; i++) {
  this.GEOMETRY.faces.push(new THREE.Face3(triangles[i][0], triangles[i][1], triangles[i][2]));
}
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh(this.GEOMETRY, material);

A: as a disclaimer, I don't have any experience with threeJS or JS in general.
First of all, you should not combine all vertices from all parts into one vertex array.
Make separate arrays for each part, or maybe even each polyhedron.
With that being said, from the documentation, it seems that ShapeUtils.triangulateShape only works on 2D collections of points. And if I'm interpreting your first picture correctly, your points are actually 3D.
https://threejs.org/docs/#api/extras/ShapeUtils.triangulateShape
Triangulation of 3D points with K vertices per face
This thread might give you some ideas on how you could reduce each face to 2D.
However, did you try pushing the points you have directly as faces, creating a mesh for each part?


text:
Q: Edited: calculating variables in PHP I am a beginner in PHP and I was given the assignment of creating a Gas Budget calculator.
I am stuck on how to add the mathematical operations and return the value after submitted. Here is what I have in the form and one of the linked PHP files.
When I run this as is, the data gets stored on the server, but the total doesn't return. It feels like I'm pretty close but I've been staring at this code for 4 hours and my brain hurts. Please help!
Thank you in advance!
HTML:
    <?php
require_once 'functions.php';
$model = getViewModel();

?>
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gas Budget Calculator</title>
<link rel="stylesheet" href="main.css">

<?php if($model->msg): ?>

<?=$model->msg?>

<?php endif; ?>
<form action="" method = "post">
    <fieldset>
        <legend>Gas Budget Calculator</legend>

            Price of Gas:
            <select name = "type">
                <option></option>
               <?php foreach ($model->price as $value => $label): ?>
                <option value="<?=$value?>"><?=$label?></option>
               <? endforeach; ?>
            </select>

             Average Commute Mileage:
            <input type="text" name = "commute" id = "commute">

             Car Average Miles Per Gallon (MPG):
            <input type="text" name = "mpg" id = "mpg">

                <input type="checkbox" name="perks">Are you going to use fuel perks? (Check box if yes)

             If yes, what is the average amount spent on groceries?
            <input type="text" name = "groceries" id = "groceries">

            <button type="submit">Submit</button>

    </fieldset>
</form>
<?php if ($model->info): ?>

        Price of Gas 	<?=$model->info->type?>

        Commute	<?=$model->info->commute?>

        Miles Per Gallon	<?=$model->info->mpg?>

        Fuel Perks?	<?=$model->info->perksYesNo()?>

        Average Groceries	<?=$model->info->groceryAverage()?>

        Total	<?=$model->info->calculateTotal()?>

<?php endif; ?>

PHP:
class viewModel {
public $info;
public $msg;

public $price = [
            '87 octane' => 1.89,
            '89 octane' => 1.99,
            '92 octane' => 2.09
        ];

    if(isset( $_POST['Submit']) {
            if($msg!='')

}
    class GasInfo {
    private $isPerks;

    public $type;
    public $commute;
    public $mpg;
    public $groceries;
    public $total;

    public function __construct(int $type, int $commute, int $mpg, bool $perks, int $groceries,       int $total){
        $this ->type = $type;
        $this ->commute = $commute;
        $this ->mpg = $mpg;
        $this ->perks = $perks;
        $this ->groceries = $groceries;
        $this ->total = $total;
    }
public function isValid(): bool {
if (empty($this->commute)) {
    return false;
}

if (empty($this->mpg)) {
    return false;
}

return true;
}
    function perksYesNo(): string {
        return $this->isPerks ? 'Yes' : 'No';
    }

    function groceryAverage(int $groceries){
        return floor( $groceries/100);
    }

function calculateTotal (int $type, int $commute, int $mpg, bool $perks, int $groceries, int $total){
if ($perks == 'on'){
    $total = ($commute / $mpg)*$type;
} else {
    $total = ($commute / $mpg) * ($type - $groceries);
}
return $total;
echo "You spend $" + $total + " on gas every day.";
}
}

More PHP:
<?php

require_once 'GasInfo.php';

function getViewModel(): ViewModel {
$model = new ViewModel();

 }
return $model;
}

function handleSubmit() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        return null;
    }

    $type = $_POST['type'];
    $commute = $_POST['commute'];
    $mpg = $_POST['mpg'];
    $isPerks = isset($_POST['perks']) ?? null;
    $groceries = $_POST ['groceries'];
    $total = $_POST('total');

    $info = new GasInfo(
        (int)$type,
        (int)$commute,
        (int)$mpg,
        $isPerks,
        (int)$groceries,
        (int)$total
    );
    if (!$info->isValid()) {
        throw new Exception("Please enter gas price, commute, and miles per gallon");
    }

    return $info;

}


text:
Q: Linear combination of symmetric matrices. Today my friend told that any matrix can be written as a linear combination of symmetric matrices and skew symmetric matrices.. we had this question that a linear transformation $T:M_n(R) \to M_n(R)$ which maps every symmetric matrix or skew symmetric matrices to zero matrix, find the rank of the linear transformation. He said simply 0, but i have a doubt.. is that true?

A: If $A$ is a matrix in $\mathbb{R}^{n\times n}$, then$$A=\frac{A+A^t}{2}+\frac{A-A^t}{2},$$and$$(A+A^t)^t=A^t+(A^t)^t=A^t+A=A+A^t,$$so $A+A^t$ is symmetric, while$$(A-A^t)^t=A^t-(A^t)^t=A^t-A=-(A-A^t),$$so $(A-A^t)$ is skew symmetric. So it is true that every matrix can be written as a linear combination of symmetric and skew symmetric matrices. Thus a linear transformation mapping symmetric and skew symmetric matrices to $0$ is actually zero, thus it does have rank $0$.


text:
Q: Simple function resulting in Type of expression is ambiguous without more context - SwiftUI this function is supposed to just get a substring but I can't seem to quite get it.
I've tried pretty much all combinations of types but nothing seems to work
Code Causing the error:
let final = temp.substring(with: 9..<11)

all the functions code:
func decodeInput(update: String) -> String {
    var temp = String(describing: update)

    let final = temp.substring(with: 9..<11)

    return String(temp)
}

A: This is because String collection is not indexed by integer. You need to use String.Index instead. You should also make sure your string has at least 11 characters and use the final instead of temp when returning the result. Btw substring with range is deprecated you should use subscript:
func decodeInput(update: String) -> String? {
    guard update.count > 10 else { return nil }
    let start = update.index(update.startIndex, offsetBy: 9)
    let end = update.index(start, offsetBy: 2)
    return String(update[start..<end])
}


text:
Q: The different use of Task Parallel library I saw few people call function using syntax like:
Parallel.Invoke(() => Method1(yourString1),() => Method2(youString2));

And few people write code like:
Task myFirstTask = Task.Factory.StartNew(() => Method1(5));
Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));

So my question is when one should use Parallel.Invoke() and when one should create instance of Task class and call StartNew() method.
Parallel.Invoke() looks very handy.so what is the significance of using Task class & StartNew() method.........put some light and tell me the importance of different approach for same kind of job means call two function parallel with two different syntax.
i never use before the Task Parallel library. so there could be some hidden reason for using two approach for calling function. please guide me in detail. thanks

A: Well, Parallel.Invoke will block until both of the new tasks have completed.
The second approach will start two new tasks, but not wait for them to be completed. You could await them manually, or in C# 5 the new async/await feature will help you "wait" asynchronously.
It really depends what you want to do. If you want your thread to block until all the tasks have finished, Parallel.Invoke is handy.


text:
Q: How to get Paypal Transaction id and make refunds in ruby on rails I am using: Ruby 2.4, Rails 5.2.1,  Paypal in sandbox mode:
 gem 'paypal-sdk-rest', '~> 1.7.3'

Paypal payment as:
  items << {
      :name => title,
      :price => unit_price,
      :currency => "USD",
      :quantity => quantity,
      :description => short_description
  }

amount = {
    :total => subtotal,
    :currency => "USD",
    :details => {"subtotal": subtotal, "shipping": "0", "tax": "0"}
}

invoice_number = "invoice-#{rand(1111..9999)}"
@payment = Payment.new({
                           :intent => "sale",
                           :payer => {
                               :payment_method => "paypal"},
                           :redirect_urls => {
                               :return_url => "http://localhost:3000/payments/#{order.id}/make_payment",
                               :cancel_url => "http://localhost:3000/"},
                           :transactions => [{
                                                 :item_list => {
                                                     :items => items,

                                                 },

                                                 :amount => amount,
                                                 :description => "Transaction description.",
                                                 :invoice_number => invoice_number
                                             }]
                       })

Payment create as :
 if @payment.create
      render json: {success: true, paymentID: @payment.id}
    else
      @payment.error # Error Hash
      render json: {success: false}
    end

Payment capture:
 if payment.execute(payer_id: params[:payerID])
      render json: {msg: 'payment_completed', result: 'completed', }
    else
      render json: {msg: payment.error, result: 'failed'}
    end

A: Refund :
step 1: find paypal payment object from paypal:
payment = PayPal::SDK::REST::Payment.find(order.paypal_id)

step 2:  find the transaction to that payment:
transaction = payment.transactions.last

Step2: find related resources to that payment:
related_resource = transaction.related_resources.last

step 3: find the sale object form paypal sdk:
sale = related_resource.sale
sale = Sale.find(sale.id)

Now proceed with refunds:
refund = sale.refund({
                         :amount => {
                             :total => "1.31",
                             :currency => "USD"
                         }
                     })
if refund.success?
  logger.info "Refund[#{refund.id}] Success"
  render json: { result: 'success '}
else
  logger.error refund.error.inspect
  render json: { result: 'fail'}
end


text:
Q: Intuition and counterexamples for higher-order derivative test In the higher-order test we keep differentiating a function till we find the n'th derivative (n being even) to be greater than or less than zero thereby identifying it as a minimum or maximum.
My two questions refer to the one-dimensional case only:

*

*What is the intuition behind this result? To be more exact: How could the first and second derivatives be zero yet we have an extreme value anyway? If you put a tangent line on a function and trace the function with it (from smaller to bigger x-values that is) intuition has it that it would e.g. first point down and then point up, being horizontal in between: Bingo, you found a minimum. How can you have a minimum without this happening (i.e. first and second derivatives being zero)?

*In all the text I have found so far they seem to be a little passive when it comes to the part when even this procedure won't work. There seem to be cases where all derivatives are zero yet we have an extreme value anyway. So in which cases will this happen? What will you have to do then? Could you give a (counter-)example?

A: Consider a particle which is at position $x(t) = \frac{t^4}{4!}$ at time $t$. Its acceleration is $\ddot{x}(t) = \frac{t^2}{2!}$, which means that at $t=0$ it is stationary and it does not (at the moment) accelerate. Shouldn't it stay in place forever? No, the thing is that it will accelerate in a moment (precisely for any positive time), and the reason is, that jounce (i.e. the fourth derivative) is positive.
This could be formulated as "promises", where velocity is a promise that the position will change. To go further consider the following table:
$$\begin{array}{|c|c|c|}\hline
\textbf{condition} & \textbf{name} & \textbf{description} \\\hline
|x| > 0 & \text{position} & \text{the position has changed} \\\hline
|\dot{x}| > 0 & \text{velocity} & \text{the position is changing} \\\hline
|\ddot{x}| > 0 & \text{acceleration} & \text{promise that } \\
&&\text{the position will be changing} \\\hline
|\dddot{x}| > 0 & \text{jerk} & \text{promise about promise that }\\
&&\text{the position will be changing} \\\hline
|\ddddot{x}| > 0 & \text{jounce} & \text{promise about promise about promise }\\
&&\text{that the postition will be changing}
\\\hline
\end{array}$$
Although we have no names for higher derivatives, it's easy to generalize the above. So, even if many derivatives are zero, we still has the appropriate promise, hence the function might have an extremum in that point.
However, this is not all! There are even more funny examples, like $$x \mapsto \begin{cases}e^{-\frac{1}{x^2}} & \text{ if} x \neq 0 \\ 0 & \text{ otherwise}\end{cases}$$ which also has minimum at zero, but all its derivatives there are zero (picture courtesy of Wolfram Alpha)!
$\hspace{70pt}$
Of course, one also could consider $x \mapsto \mathrm{sgn}(x)\cdot e^{-\frac{1}{x^2}}$ (with the obvious smoothness fix at zero) which does not have minimum nor maximum there, i.e. all derivatives being zero tells us very little about how the function might look in the future.
You might argue that this is a weird example, but observe that in nature all functions/movements might be just like that. A car might be stationary, but then it starts moving. How did it happen? Is its movement infinitely differentiable? You might say that no, because combustion in engine and other things are not, but what about the tires and ground friction? I shall stop here, as this is not mathematics anymore.
I hope this helps $\ddot\smile$


text:
Q: Gathering outputs from an MSBuild exec task I have a batch script that I want to call from an MSBuild project, and the documentation says I can't use output from the batch (either console / environment variables) in the MSBuild project.
Is there a workaround?

A: You can redirect the output of the command to a file using "> output.txt" and read that into a variable.
<PropertyGroup>
   <OutputFile>$(DropLocation)\$(BuildNumber)\Output.txt</OutputFile>
</PropertyGroup>
<Exec Command="dir > "$(OutputFile)"" />
<ReadLinesFromFile File="$(OutputFile)">
   <Output TaskParameter="Lines" ItemName="OutputLines"/>
</ReadLinesFromFile>
<Message Text="@(OutputLines->'%(Identity)', '%0a%0d')" />


text:
Q: using "like" to compare a string with two wildcards VBA I am comparing two sheets of data. One on sheet, I have a bunch of strings like this: "Apples - are good (YES)" while on the other sheet, I have strings like this "Apples - YES" . in this scenario, the two strings should be compared as the same. When the original data was compiled, there was no naming standard between the two sources. This means that when im using the "like" function, I need it to handle two separate wildcards because there are two parts of the string that need to be compared. What I have right now:
 Dim TorF as Boolean
 TorF = stringToCompare Like subString1 & "*YES*"

I know my function as a whole is sound, because previously I was only using one wildcard and simply ignoring any strings that contained "-". However, now I actually have to deal with the extra results.

A: You can do this by searching the substring1 and "YES" within your stringToCompare and proceed with your code when True:
If InStr(1, stringToCompare, subString1, vbTextCompare) > 0 And InStr(1, stringToCompare, "YES", vbTextCompare) > 0 Then
        'your code
End If


text:
Q: How to read different files paths from a txt file using for loop in SNAKEMAKE Hi I have a rscript that reads files from different locations based on a text file.
The text file named scenarios.txt is here:
scenario    name    directory
2017    Dijn    2017-v0
2022    Pikn    2030-v1
2040    Enn 2040

A sample rscirpt is like the following:
library(tidyverse)
library(sf)
ss = read.delims("Simulations/scenarios.txt")
for(i in rows.along(ss){
gps = st_read(paste0("/usd/clove/simulations/",ss$directory[i],"/trips_gps.gpkg") )
st_write(gps, paste0("/usd/clove/simulations/",ss$directory[i],"/trips_gps_",ss$name[i],".gpkg") )

}

How will I write a snakemake file in such scenarios, where the file path is taken as an input from a text file ?

A: I'll give it try answering, but I'm not sure I understand the question and this below is not tested at all.
import pandas

ss = pandas.read_csv('Simulations/scenarios.txt', sep='\t')

rule all:
    input:
        expand('/usd/clove/simulations/{directory}/trips_gps_{name}.gpkg', zip,
            directory=ss['directory'], name=ss['name'])

rule writer:
    input:
        fin='/usd/clove/simulations/{directory}/trips_gps.gpkg',
    output:
        fout='/usd/clove/simulations/{directory}/trips_gps_{name}.gpkg',
    script:
        'io.R'

where io.R may be something like this:
library(sf)

gps = st_read(snakemake@input[['fin']])
st_write(snakemake@output[['fout']])

First you read the sample sheet and you use the information there to prepare the output files (rule all). Then for each row (i.e. output file) you run rule writer.
I wouldn't hardcode file names and path in the snakefile, better to pass them as configuration parameters but this is a separate issue.


text:
Q: React JS: How to add multiple placeholder object inside components Sorry this question might be duplicated, but none of the existing answers helped me
I'm a beginner in React and js
I want to add multiple objects inside the component
Like:
src={url}
name={text}
subTitle={subtext}

my index.js

const tableColumns = [
  {
    title: 'Title/Artist',
    dataIndex: 'name',
    key: 'name',
    render: (text) => (

        <AvatarStatus
          shape="square"
          src="https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946"
          name={text}
          subTitle="Dua Lipa"
        />

    ),
  },
];

return (
<>

 </>

my data.js

export const RecentReleasesData = [
  {
    id: '#5332',
    artwork: 'https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946',
    name: 'Future Nostalgia',
    artist: 'Dua Lipa',
    label: 'Warner Records',
    barcode: '19029500',
    releasedate: '2021-02-11',
    tracks: '11',
    promolink: 'Smart Link',
    status: 'Approved',
  },
  {
    id: '#6438',
    artwork: 'https://i.scdn.co/image/ab67616d00001e02caf82abb2338880577e472be',
    name: 'Love',
    artist: 'Someonw',
    label: 'UMG Records',
    barcode: '50029500',
    releasedate: '2017-08-21',
    tracks: '2',
    promolink: 'Smart Link',
    status: 'Rejected',
  },
];

My comp AvatarStatus.js

import React from 'react';
import PropTypes from 'prop-types'
import { Avatar } from 'antd';

const renderAvatar = props => {
    return <Avatar {...props} className={`ant-avatar-${props.type}`}>{props.text}
    </Avatar>;
}

export const AvatarStatus = props => {
  const { name, suffix, subTitle, id, type, src, icon, size, shape, gap, text,
  onNameClick } = props
    return (

        {renderAvatar({icon, src, type, size, shape, gap, text })}

                {
                  onNameClick ?

 onNameClick({name, subTitle, src, id})}
                      className="avatar-status-name clickable">{name}

                    :

                      {name}

                }
            {suffix}

{subTitle}

  )
}

AvatarStatus.propTypes = {
  name: PropTypes.string,
  src: PropTypes.string,
  type: PropTypes.string,
  onNameClick: PropTypes.func
}

export default AvatarStatus;

https://reactjs.org/docs/components-and-props.html
components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
This function is a valid React component because it accepts a single "props" (which stands for properties) object argument with data and returns a React element. We call such components "function components" because they are literally JavaScript functions.
codepen example

A: I found the solution

index.js

render: (_, record) => (
  <Flex>
    <AvatarStatus
      shape="square"
      size={50}
      src={record.artwork}
      name={record.title}
      subTitle={record.artist}/>
  </Flex>
),


text:
Q: Controls do not fit to form resizing WPF I'm trying to create an app responsive, all the effort I'm putting is not giving me results on the new standard WPF.
  I would make sure to resize the application controls when the form is shrunken or expanded.
As you can see from the pictures item 3 is not completely visible when the form is shrunken and as a result does not fit the new dimension given by the user.
How do I create an application that can automatically adjust the controls? On the normal form I had no problem doing this, but in WPF does not really understand how to adapt automatically, despite having read numerous tutorials. Thank you.
CODE:
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="SpanCore.MainWindow"
    Title="SpanCore" Height="522" Width="783" MinWidth="400" MinHeight="522">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition />
        <RowDefinition />SpanCoreSpanCore
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3">
        <Menu Height="21" VerticalAlignment="Top" HorizontalContentAlignment="Stretch" Background="#FFF0EDED" Grid.ColumnSpan="3">
            <MenuItem ToolTip="File" Header="File">
            </MenuItem>
        </Menu>
        <DataGrid HorizontalContentAlignment="Stretch" VerticalAlignment="Top" Grid.ColumnSpan="3" Margin="10,26,10,0" Grid.RowSpan="2">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="h" CanUserResize="False" MinWidth="100" Width="150"/>
                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="a" CanUserResize="False" MinWidth="100" Width="150"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    <TabControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Width="auto" Height="auto">
        <TabItem Header="tab1">
            <Canvas>
                <DockPanel>
                    <GroupBox Header="item1" Grid.Row="2" Grid.Column="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Height="168" Width="300">
                        <DataGrid>
                            <DataGrid.Columns>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="S"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="P"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="V"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="P"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Pa"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="G"/>
                            </DataGrid.Columns>
                        </DataGrid>
                    </GroupBox>
                    <GroupBox Header="item2" Canvas.Left="303" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Height="168" >
                        <DataGrid>
                            <DataGrid.Columns>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Book" MinWidth="80"/>

                            </DataGrid.Columns>
                        </DataGrid>
                    </GroupBox>
                    <DockPanel DockPanel.Dock="Right" HorizontalAlignment="Right">
                        <GroupBox Header="item3" Canvas.Left="903" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Width="202" Height="168" DockPanel.Dock="Right" >
                            <Grid>
                                <RadioButton Content="1t" HorizontalAlignment="left" DockPanel.Dock="left"/>
                                <RadioButton Content="2t" HorizontalAlignment="Right" DockPanel.Dock="Right"/>
                            </Grid>
                        </GroupBox>
                    </DockPanel>
                </DockPanel>
            </Canvas>
        </TabItem>
        <TabItem Header="tab2">
        </TabItem>
        </TabControl>
</Grid>

IMAGE EXAMPLE:

A: Try following code:
<Window x:Class="WPFDevelopement.SampleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SampleWindow" Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3">
            <Menu Height="21" VerticalAlignment="Top" HorizontalContentAlignment="Stretch" Background="#FFF0EDED" Grid.ColumnSpan="3">
                <MenuItem ToolTip="File" Header="File">
                </MenuItem>
            </Menu>
            <DataGrid HorizontalContentAlignment="Stretch" VerticalAlignment="Top" Grid.ColumnSpan="3" Margin="10,26,10,0" Grid.RowSpan="2">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="h" CanUserResize="False" MinWidth="100" Width="150"/>
                    <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="a" CanUserResize="False" MinWidth="100" Width="150"/>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
        <TabControl Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Width="auto" Height="auto">
            <TabItem Header="tab1">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="2*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>

                    <GroupBox Grid.Column="0" Header="item1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" MinWidth="300">
                        <DataGrid>
                            <DataGrid.Columns>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="S"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="P"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="V"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="P"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Pa"/>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="G"/>
                            </DataGrid.Columns>
                        </DataGrid>
                    </GroupBox>
                    <GroupBox Grid.Column="1" Header="item2" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
                        <DataGrid>
                            <DataGrid.Columns>
                                <DataGridTextColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Book" MinWidth="80" />
                            </DataGrid.Columns>
                        </DataGrid>
                    </GroupBox>
                    <GroupBox Grid.Column="2" Header="item3" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" >
                        <StackPanel Orientation="Horizontal">
                            <RadioButton Content="1t" />
                            <RadioButton Content="2t" Margin="8,0" />
                        </StackPanel>
                    </GroupBox>
                </Grid>
            </TabItem>
            <TabItem Header="tab2">
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Result:

And final comment for all WPF programmers: don't use Canvas and avoid hardcoded Width, Height and other such properties. Use Grid instead with proprotional or Auto columns.


text:
Q: Native (C#, C++) UI plugins for Cordova Windows? For Cordova iOS and Cordova Android it is possible to create plugins that create native UI on top of your app - you just include the libraries in your plugin and execute their API. Example for Android InAppBrowser.
For Cordova Windows, the native code is HTML and Javascript, hence the InAppBrowser plugin also adds a standard HTML tag for a Webview (or even plain Iframe) to get the same effect.
But you can also create plugins for Cordova Windows that use C# or C++ native code via a Windows Runtime Component. A public example is the globalization plugin that uses a .winmd file to offer APIs to the Javascript code  (source code for this). This works great and is pretty awesome.
Unfortunately all the plugins that I could find use this C#/C++ native plugin mechanism only to receive some method call, do something with the parameters and return some data. None of those open any windows or create any other GUI (that might for example be offered by an external C# SDK).
How can one create a plugin for Cordova Windows that creates User Interface with native (C#, C++) code? Is this possible at all?

A: Got a response in a Apache Cordova mailing list that I am reproducing here:

Unfortunately, No.  C#/C++ Portable Class Library ( PCL ) code cannot
  render on top of the web component.
  The libraries that you can use are limited in PCLs and for projects
  targeting Windows Store it is not possible to render UI.
  If the entire cordova-windows platform were re-architected to be a C# or
  C++ based application, with a native webview container in which to render,
  then everything is possible.  This is a long risky road though ...
  everything from the cordova.js and the bridge would have to change, and
  every plugin would need to be rewritten.


text:
Q: Зациклить progressbar DelphiXE Как сделать: что бы - progressbar, по нажатию на кнопку, работал без остановки и после окончания цикла - заполнить прогресс бар на 100% и остановить. ?
В коде:
Min и Max - это свойства отвечающие за диапазон значений.
Position - позиция, на которой находится в данный момент индикатор.
i - переменная для перебора целых чисел.
Label - показывает какое сейчас обрабатывается число.
procedure TForm1.Button1Click(Sender: TObject);
var
   i, proc, Max : integer;
begin
    Max := 50000;
   for i:=0 to Max do
     begin
       proc := ((i * 100) div Max);
       Label1.Caption := IntToStr(i);
       ProgressBar1.Position := proc ;
       Application.ProcessMessages;
// Тут нужный цикл
........................................................

.........................................................

// И после окончания цикла - заполнить прогресс бар на 100% и остановить.
         end;
    end;

То есть простыми словами, говоря - Сделать "бесконечный" прогресс-бар, который просто показывает, что процесс закачки идёт и после окончания цикла остановить его.

A: Рекомендую использовать свойство Smooth, со значениями true или false в зависимости что вам нужно, этот режим предназначен специально для таких случаев как у вас!


text:
Q: I have two title in my database and I take a while loop, I want to display multi collapse title how much that I have title records in database And this is the code.

    <?php
        while($row=mysqli_fetch_assoc($result))
        {
            echo '
';
            echo '
';
            echo '<button class="btn btn-link" type="button" data-toggle="collapse"
            aria-expanded="true" aria-controls="collapseOne">';

            echo $row['title'];

           echo '</button>';
           echo '
';
           echo '
';
           echo '
';
       }
   ?>

but now it display the second record with one collapse title, it must dispaly two title with two collapse title.

A: Place the main card div within your while loop:

<?php
    while($row=mysqli_fetch_assoc($result))
    {
        echo '
';
        echo '
';
        echo '
';
        echo '<button class="btn btn-link" type="button" data-toggle="collapse"
        aria-expanded="true" aria-controls="collapseOne">';

        echo $row['title'];

       echo '</button>';
       echo '
';
       echo '
';
       echo '
';
   }
?>


text:
Q: Reducing boilerplate in Spring Cloud Kafka Streams app In my Spring Cloud Kafka Streams app, I want to join a KTable<String, Foo> to a KTable<String, Bar>. The inputs to my app have been encoded using MessagePack, so I've defined Serdes for Foo and Bar using the code below.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Foo {
  String a;
  String b;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bar {
  String c;
  String d;
}

// ObjectMapper mapper = new ObjectMapper(new MessagePackFactory());

@Bean
public Serde<Foo> fooSerde() {
  return new JsonSerde<Foo>(Foo.class, mapper);
}

@Bean
public Serde<Bar> barSerde() {
  return new JsonSerde<Bar>(Bar.class, mapper);
}

My question is, to specify the value type of the KTable after the join, do I have to now define:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FooBar {
  String a;
  String b;
  String c;
  String d;
}

@Bean
public Serde<FooBar> fooBarSerde() {
  return new JsonSerde<FooBar>(FooBar.class, mapper);
}

It just seems like quite a lot of boilerplate? Especially if Foo and Bar have many fields. Is there anything I could do shorten my code?

A: Kafka newbie here.
what I've seen so far, is to have a FooBar class that has an instance of Foo and Bar, so you don't need to touch the 'joined' class. For example
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FooBar {
  Foo foo;
  Bar bar;
}


text:
Q: Actionscript 3 - Completely removing a child I have an array of objects that when another object hits one of them, the object will be removed. I have removed it from the stage using removeChild() and removed from the array using splice(), but somehow the object is still calling some of its functions which is causing errors. How do I completely get rid of an object? There are no event listeners tied to it either.

A: You need to make sure that the display object you're removing:

*

*has no listeners registered on the stage, e.g. you need to call stage.removeEventListener(...) for any corresponding stage.addEventListener(...)

*doesn't have a listener for the Event.ENTER_FRAME event

*doesn't listen for events on any timers

*isn't called by a timer set up with setInterval anywhere

*etc. basically anything having to do with timers, the stage, it's parent, loaders and the time line can cause objects to linger and not be removed

So when you have removed the object with removeChild and removed it from the array you kept it in, also call its stop method to make sure it's not playing its timeline. It may also be a good thing to have a method on that object called something like halt, cleanup or finalize that unregisters any listeners, stops timers, timeouts, intervals, etc., clears references (i.e. sets the variables to null) to it's parent, the stage or any object that isn't going away too.

A: It sounds like you may be running into a garbage collection issue with the flash player.
A new API has been added to Flash Player 10 that should address this:
unloadAndStop()
Grant Skinner has more info on this on his blog:
http://www.gskinner.com/blog/archives/2008/07/unloadandstop_i.html
You can grab a beta of Flash Player 10 at:
http://labs.adobe.com/technologies/flashplayer10/
mike chambers
mesh@adobe.com

A: To completely get rid of an object in AS3 you must set its value to null.  Garbage collection will have no problems removing it because there are no references to it.  Also if can be helpful to use "weak references" with event listeners.  When creating an event listener it typically is the event type and the function to be fired.
addEventListener(SomeEvent.EVENT_HAPPEND, onEventHappend);

below I will illustrate the same, but with a weak reference.
addEventListener(SomeEvent.EVENT_HAPPEND, onEventHappend, false, 0, true);

We know what the first two parameters are so lets begin with the third.  The third parameter dictates whether the event fires the onEventHappened function during the capture phase (true) or the bubbling phase (false which is also the default).  The only reason I am mentioning this parameter is that it is required prior to setting the weak reference parameter.  The fourth parameter is priority and dictates which events have priority when both listening on the same object and same phase of the event flow.  The fifth parameter sets the weak reference to true or false, for this case we will use true which is helpful for garbage collection.

A: Is the object in question a MovieClip, and does it have a timeline playing?
If so you will need to stop it before removing.
Also keep in mind that storing a reference to the object in any way (although most commonly in an Event listener) will keep it from getting garbage collected. This includes any references to functions or child objects.

A: For a function to be called, by definition there must be either a listener or setTimeOut somewhere, or the timeline must be playing. Make sure you remove all listeners and all references to the object. What kind of object is it?
The output window or debugger should show you the stack of function calls that led to the unwanted call. If you paste the error output into your question then we will be able to give you a more accurate answer.

A: Also remember to stop and remove any related Timers when disposing of the removed objects: BIT-101: Running timers are not garbage collected. Ever.

A: I would look at Event.ENTER_FRAME and TimerEvent.TIMER listeners, make sure they're nullified before you remove the object.


text:
Q: Spring mvc 3.x global .net web.config equivalent? I'm new to Spring and I'm wondering what the equivalent of Spring's .NET globabl web.config file is and how to access custom values from that equivalent web.config file?  I want store a couple of URLs (for starters) and I need to know how to access each property globally from any controller?
Specifically for spring mvc 3.x (not sure if there is a difference or not per other versions).
What is best practice here? There seems to be a lot of variations on this theme. thx!