How many unique rows of pebbles are there?

Question:
A valid row of pebbles has $n$ white, and $n$ black pebbles. Thus, its
  length is $2n$.
Two rows of pebbles are considered equivalent if one can be produced
  from another by any combination of inversions (replacing all whites with
  blacks and vice versa) and flips (reverse the order of pebbles).
How many unique rows of pebbles are there for some $n$?
If we want our rows of pebbles to look mixed, we can say
  that a mixed row of pebbles can't have more than $2$ consecutive
  pebbles of the same color.
(mixed case $m=1$ is trivial with only one solution per $n$)
Then, how many rows of unique mixed pebbles are there for some
  $n$? (mixed case $m=2$)

We can represent pebbles with $0$'s and $1$'s.
I've tried generating examples for some $n$'s by iterating binary numbers;
We have solutions for first few $n$'s, for unique rows:
$$  1, 3, 7, 23, 71, 252, 890, 3299, 12283, 46508, \dots$$
Edit: Corrected thanks to Jeremy Dover from comments: Now,  this sequence is in OEIS.

If we eliminate ones with $3$ or more same consecutive pebbles from previous examples;
Then we have the number of unique mixed ones for $n=1,\dots,10,\dots$ below ($m=2$):
$$ 1 ,3 ,5 ,12 ,25 ,61 ,140 ,347 ,841 ,2108 , \dots$$
Edit: Also corrected. This sequence still does not appear in OEIS.

Q: How can we find these values for unique mixed examples algebraically?

P.S. Is there any significantly faster way to generate all solutions for some $n$? The outputs with all examples for the second sequence so far: pastebin.com ; Where second column is the decimal value and third is the difference between consecutive examples.

Also, would it be interesting to generalize this and find solutions for rows of size $k\times n$ where $k$ is the number of distinct
  colors of pebbles, and also consider $m$ consecutive pebbles allowed?
   How does one calculate/compute a solution for some $(k,n,m)$?

A follow up; If we were to have $2n$ rows of pebbles together to form a "pebble garden", how many unique mixed pebble gardens are there?
That is, now we also need to check the columns, as well as rows, for the same number of pebbles and for no three consecutive pebbles of same color. We also need to consider both horizontal and vertical flips and the 90° degree rotations for uniqueness, then this follow up is equivalent to the following question:
How many distinct Unruly boards are there?

P.S. We could also stack the gardens into "pebble cubes", and continue to "pebble tesseracts", and continue to... $N$ dimensional unique pebble structures? But given the follow up has zero progress posed there as of this moment, this is perhaps still an overreach.
Comment: For the first problem, your counts are incorrect. Looking at your pastebin for n=3, you have 100011 and 110001 counted as distinct, but they are isomorphic with respect to a flip. For n>=3, your counts seem to be off by exactly one each time. Using the corrected numbers, you can find your first sequence in the OEIS at http://oeis.org/A045723.
Comment: @JeremyDover That was a terribly missed error in my quick code. Thanks for noticing. I've corrected both sequences now.
Answer: For  starters   we  verify  the   formula  that  is  given   at  OEIS
A045723  which treats  the problem  without
adjacency  constraints. We  solve the  case  of $n$  instances of  $k$
colors for both $n\times k$ even and  odd. What we have here is a case
of Power  Group Enumeration with the  slot permutations consisting
of the identity  and the reflection. We represent the  color scheme by
by a  sequence of $k$ blocks  of $n$ identical colors,  $n\times k$ in
total. The object permutation group acting on these is obtained by the
simultaneous action  of the symmetric  group $S_k$ on the  $k$ blocks,
which encodes the fact that the  colors are swappable, and a vector of
$k$ permutations $\gamma_1,\ldots, \gamma_k$  from $S_n$ acting on the
constituents  of  the blocks,  which  encode  the  fact that  the  $n$
instances  of   the  $k$  colors   are  the  same.   Denote   this  by
$Z(F_{n,k}).$
For Power Group Enumeration we require the cycle index of the slot
permutation group which is
$$Z(Q_{n,k}) = \frac{1}{2} (a_1^{nk} + a_2^{nk/2})$$
when $n\times k$ is even and
$$Z(Q_{n,k}) = \frac{1}{2} (a_1^{nk} + a_1 a_2^{(nk-1)/2})$$
when $n\times  k$ is odd.   We must cover  these two with  cycles from
permutations from  $Z(F_{n,k})$ where we  are using a set  cover, i.e.
all colors  must be present.  Now  for the first one  there clearly is
only one possibility,  coverings using fixed points  from the identity
permutation.   Since   there  are  $k!\times  n!^k$   permutations  in
$Z(F_{n,k})$ we get a contribution of
$$\frac{(nk)!}{k! \times n!^k}.$$
The power of  $a_2$ requires more work and must  be simplified to make
for a  feasible computation.  Note  once more that  in a set  cover we
must use all cycles from the  permutation being sourced for the cover.
This clearly  requires for  the two permutations  to have  exactly the
same  cycle  structure.   Therefore we  are  extracting  $[a_2^{nk/2}]
Z(F_{n,k})$  and  $[a_1  a_2^{(nk-1)/2}] Z(F_{n,k}).$  Supposing  that
$\beta$  is the  permutation from  $S_k$  we see  that it  must be  an
involution, consisting of fixed points and two-cycles only, since this
is  the structure  of the  coefficient being  extracted and  we cannot
return to the  starting point of a cycle without  having made at least
one turn. Now  if $\beta$ fixes a certain block  then the contribution
from  that block  (permutation  $\gamma$) to  the  cycle index  enters
identically and hence it must be an involution as well.  One the other
hand if two blocks are on  a two-cycle the cycles where their elements
reside must have  even length wich implies they  are two-cycles.  This
means that  the corresponding  permutations $\gamma_a$  and $\gamma_b$
are inverses  of each other and  the joint action with  $\beta$ splits
everything into two-cycles. Using the exponential formula we introduce
$$Z(S_{q,\mid m}) =
[w^q] \exp\left(\sum_{d|m} a_d \frac{w^d}{d}\right)$$
we thus obtain
$$[a_2^{nk/2}] Z(F_{n,k}) =
[a_2^{nk/2}] Z(S_{k,\mid 2})
\left(Z(S_{n,\mid 2}), \frac{1}{n!} a_2^n\right)$$
and similar  for $n\times k$  odd. Here  a cycle index  evaluated with
arguments signifies  substitution into $a_1,  a_2$ etc.  It remains to
observe that we have two choices  for each cycle being covered when we
cover the  two-cycles and  any permutation of  the source  cycles from
$Z(F_{n,k})$ is  valid.  We  finally get for  the desired  closed form
when $n\times k$ is even
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{2} \left(\frac{(nk)!}{k! \times n!^k}
+ (nk/2)! \times 2^{nk/2} \times
[a_2^{nk/2}] Z(S_{k,\mid 2})
\left(Z(S_{n,\mid 2}), \frac{a_2^n}{n!}\right) \right)}$$
and
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{2} \left(\frac{(nk)!}{k! \times n!^k}
+ ((nk-1)/2)! \times 2^{(nk-1)/2} \times
[a_1 a_2^{(nk-1)/2}] Z(S_{k,\mid 2})
\left(Z(S_{n,\mid 2}), \frac{a_2^n}{n!}\right) \right)}$$
otherwise. We can compute these values with the following Maple code.

with(numtheory);
with(combinat);

pet_cycleind_symm :=
proc(n)
option remember;

    if n=0 then return 1; fi;

    expand(1/n*add(a[l]*pet_cycleind_symm(n-l), l=1..n));
end;

pet_cycleind_symm_nk_div2 :=
proc(n, k)
option remember;
local idx_col, idx_slot, res;

    if n=1 and k=1 then return a[1] fi;

    if n=1 or k=1 then
        return pet_cycleind_symm(n*k);
    fi;

    idx_col := coeftayl(exp(a[1]*z+a[2]/2*z^2), z=0, k);
    idx_slot := coeftayl(exp(a[1]*z+a[2]/2*z^2), z=0, n);

    res :=
    subs({a[1]=idx_slot, a[2]=a[2]^n/n!},
         idx_col);

    expand(res);
end;

EXA :=
proc(n, k)
option remember;
local idx;

    if n=1 or k=1 then return 1 fi;

    idx := pet_cycleind_symm_nk_div2(n, k);

    if type(n*k, even) then
        1/2*((n*k)!*coeff(idx, a[1], n*k) +
             ((n*k)/2)!*2^(n*k/2)*
             coeff(idx, a[2], n*k/2));
    else
        1/2*((n*k)!*coeff(idx, a[1], n*k) +
             ((n*k-1)/2)!*2^((n*k-1)/2)*
             coeff(coeff(idx, a[2], (n*k-1)/2), a[1], 1));
    fi;
end;

EXB :=
proc(n, k)
option remember;
local idx;

    if n=1 or k=1 then return 1 fi;

    idx := pet_cycleind_symm_nk_div2(n, k);

    if type(n*k, even) then
        1/2*((n*k)!/k!/n!^k +
             ((n*k)/2)!*2^(n*k/2)*
             coeff(idx, a[2], n*k/2));
    else
        1/2*((n*k)!/k!/n!^k +
             ((n*k-1)/2)!*2^((n*k-1)/2)*
             coeff(coeff(idx, a[2], (n*k-1)/2), a[1], 1));
    fi;
end;

We get for two swappable colors the sequence
$$1, 3, 7, 23, 71, 252, 890, 3299, 12283, 46508,
\\ 176870, 677294, 2602198, \ldots $$
which matches  the data from  the OP.  With three swappable  colors we
find
$$1, 11, 148, 2955, 63231, 1430912, 33259920,
\\ 788827215, 18989544145, 462583897776, \ldots $$
and with four the data are
$$1, 65, 7780, 1315825, 244448316, 48099214856,
\\ 9844135755168, 2074189508907945, \ldots $$
The  initial segments  of these  may  be verified  with the  following
enumeration routine.

#! /usr/bin/perl -w
#

sub recurse {
    my ($n, $k, $kf, $rest, $sofar, $orbits) = @_;

    if(scalar(@$sofar) == $n*$k){
        my $sofar_rev = [ reverse(@$sofar) ];

        my @orbit;

        for(my $idx = 0; $idx < $kf; $idx++){
            my @permcols = ( 0 .. ($k-1) );

            for(my ($d, $ind) = ($k, $idx);
                $d > 1; $d--){
                my $pos = $ind % $d;

                if($pos != $d-1){
                    my $tmp = $permcols[$pos];
                    $permcols[$pos] = $permcols[$d-1];
                    $permcols[$d-1] = $tmp;
                }

                $ind = ($ind - $pos) / $d;
            }

            my $conf = join '',  map {
                chr(ord('A') + $permcols[$_])
            } @$sofar;

            push @orbit, $conf;

            $conf = join '',  map {
                chr(ord('A') + $permcols[$_])
            } @$sofar_rev;

            push @orbit, $conf;
        }

        my @sorted = sort(@orbit);
        $orbits->{$sorted[0]} = 1;
        return;
    }

    for(my $col = 0; $col < $k; $col++){
        if($rest->[$col] > 0){
            $rest->[$col]--;
            push @$sofar, $col;

            recurse($n, $k, $kf, $rest, $sofar, $orbits);

            pop @$sofar;
            $rest->[$col]++;
        }
    }
}

MAIN : {
    my $mx = shift || 5;
    my $k = shift || 2;

    my $kf = 1;
    for(my $f=2; $f <= $k; $f++){
        $kf *= $f;
    }

    $| = 1;

    for(my $n=1; $n <= $mx; $n++){
        my $orbits = {};

        recurse($n, $k, $kf, [($n) x $k],
                [], $orbits);

        print " " if $n > 1;
        print scalar(keys(%$orbits));
    }

    print "\n";
}

There  is   another  example   of  PGE   at  the   following  MSE
link.


Where is the "thread" of a river?

Question: Lawyers speak of the "thread" of a river.  When the boundary between two counties or states is a river, it is usually the "thread" of the river, a path running along the center of the river.  (In England, I suspect this has applied primarily to boundaries between counties.)  If a line is drawn from a point on one bank to a corresponding point on the opposite bank, one can take the midpoint to be a point on the "thread", but which point on the opposite bank is the corresponding point when the river meanders erratically, as they all do (but some more than others)?  I am inclined to doubt that lawyers have clearly answered this, and to suspect that some substantial components of any reasonable answer can be contributed only by mathematicians.
Exceptions include:

The northern boundary of Kentucky.  The whole of the Ohio River is in Kentucky; the states north of it, Ohio, Indiana, and Illinois, begin at the north bank.  I think this goes back to an act of Parliament after the Seven Years' War in 1763, declaring the Ohio to be the southern boundary of Canada, which became an English colony at that time.  (This is alluded to in the language about a "fit instrument" in the Declaration of Independence.)
The boundary between Delaware and New Jersey, which puts the Delaware River entirely in Delaware, so that New Jersey begins at the west bank.
The boundary between Vermont and New Hampshire (surely the most colorful story of weird politics in the history of the U.S.A., if not of the Universe).  The Connecticut River is in New Hampshire; Vermont begins at the west bank.  On July 20, 1764, King George III decreed this after a scandalously ex-parte hearing, with the later result that the half of the Constitution of Vermont before its amendment-in-its-entirety in 1793 was a list of grievances against the government of New York, and the further later result that in a lawsuit that lasted from 1915 through 1933, a federal court ended up upholding the King's decision.

But dozens of boundaries between states in the U.S.A. follow the "thread" of a river, if I'm not mistaken.
Comment: I'm not precisely sure about how to formalize this, or whether it yields a curve, but maybe something like imagining both banks puff out (i.e. draw circles of the same radius about each point on the banks, take their union) at some rate and then, wherever the two banks "first meet" is the thread.
Comment: The [medial axis](https://en.wikipedia.org/wiki/Medial_axis) of the region enclosed by the banks might be a reasonable definition. (This seems to be what @Meelo is getting at.)
Comment: Maybe it is the locus of midpoints of normals drawn from one bank?
Comment: @AvZ : Which one?  Perhaps one could say the left bank or the right bank.  But which?
Comment: How about we choose the thread to be the set of points which have the same minimum distance from both banks.

In formal terms, let $Y$ be the set of points on one bank, and $Z$ be the set of points on the other bank. $x$ is now one with the thread if and only if $$\min\limits_{y\in Y}d(x,y)=\min\limits_{z\in Z}d(x,z)$$
Comment: @AvZ : It's not clear how to average them.  If you have two points, you can find their average.  But which two points?  Which point on one curve corresponds to which on the other?
Comment: @MichaelHardy, That's the problem, you will get different locus from each bank... Average them maybe?
Comment: @PeterWoolfitt: Yup that's pretty much the gist of the answer I just wrote up with some conditions needed for nice properties.
Comment: @user86418: But using the medial axis would mean that you lose information about which bank the closest points are from, which also means you get funny isolated points in all the small cavities of the banks, which is surely not reasonable for a boundary. Also, the definition I gave is part of the medial axis that excludes those irrelevant points.
Comment: @user21820 : Your comment definitely calls for an example.
Comment: Say we have banks in 2d, both being halfplanes with parallel boundaries except one has a tiny triangle cut out of it. Then a part of one of the angle bisectors of the triangle will be on the medial axis simply because those points are equidistant to multiple points on that bank, but what you want is to be equidistant to **both** banks, hence my definition.
Answer: Notation
Let $d(x,y)$ be the distance between $x$ and $y$ for any $x,y \in \mathbb{R}^3$.
Let $d(x,S) = \inf_{y \in S} d(x,y)$ for any $x \in \mathbb{R}^3$ and $S \subseteq \mathbb{R}^3$.
Let $d(S,T) = \inf_{(x,y) \in S \times T} d(x,y)$ for any $S,T \subseteq \mathbb{R}^3$.
A possible definition of a river's thread
Take any non-empty closed disjoint sets $A,B \in \mathbb{R}^3$ [corresponding to the two banks].
Let $T = \{ x : d(x,A) = d(x,B) \}$ for any $r \in [0,1]$.
Then $T$ can be considered the middle boundary between $A$ and $B$.
Properties of this thread
Regions
Let $A' = \{ x : d(x,A) < d(x,B) \}$.
Let $B' = \{ x : d(x,B) < d(x,A) \}$.
Then $A',B'$ are clearly open since $d$ is continuous and hence $T$ is closed.
Closest-Point
For any $x \in \mathbb{R}^3$:
  $d(x,A) = d(x,y)$ for some $y \in A$ because:
    Let $(y_n)$ be a sequence in $A$ such that $d(x,y_n) \to d(x,A)$ as $n \to \infty$.
    Then $(y_n)$ is bounded and has some cluster point $y$ [by Bolzano-Weierstrass].
    Thus $y \in A$ [because $A$ is closed].
  [This means that there is a point in $A$ closest to $x$. Similarly for $B$.]
Disjoint-Separation
$T,A',B'$ are clearly disjoint.
$A \subseteq A'$ because:
  For any $x \in A$:
    If $d(x,B) = 0$:
      Let $y \in B$ such that $d(x,y) = d(x,B)$ [by Closest-Point].
      Then $x = y \in B$.
      Contradiction.
    Therefore $d(x,B) > 0 = d(x,A)$ and hence $x \in A'$.
Similarly $B \subseteq B'$ and hence $T$ is disjoint from both $A$ and $B$.
No-holes
For any topological sphere $C \subseteq A'$ having no point of $B$ in its interior:
  Let $D$ be the topological ball corresponding to $C$.
  For any $x \in D$:
    Let $y \in B$ such that $d(x,y) = d(x,B)$ [by Closest-Point].
    Let $L$ be the line segment from $x$ to $y$.
    Let $z = L \cap C$ [which exists because $B$ is outside $C$].
    Then $d(x,A) \le d(x,z) + d(z,A) < d(x,z) + d(z,B) \le d(x,z) + d(z,y) = d(x,y)$
    $= d(x,B)$.
  Therefore $D \subseteq A'$.
Connected-Separation
If $A$ is connected, then $A'$ is path-connected because:
  For any $x \in A'$:
    Let $y \in A$ such that $d(x,y) = d(x,A)$ [by Closest-Point].
    Let $L$ be the line segment from $x$ to $y$.
    If $z \in B'$ for some $z \in L$:
      $d(x,B) \le d(x,z) \le d(x,y) = d(x,A)$.
      Contradiction.
    Therefore $L \subseteq A'$.
    Thus $L \cup A$ is connected.
  Therefore $A'$ is connected and hence path-connected because $A'$ is a open subset of $\mathbb{R}^3$.
Therefore if $A,B$ are both connected, then $A',B'$ will be both path-connected [and the whole space $\mathbb{R}^3$ will be divided into exactly two 'pieces' separated by $T$]. I believe but cannot prove that $T$ will in this case be connected. It is not necessarily path-connected; $T$ can be the Koch snowflake if $A,B$ are the inside and outside of it, in which case no two points in $T$ are path-connected.
Comments
$x \mapsto \dfrac{d(x,A)}{d(x,A)+d(x,B)}$ is a continuous function that is $0$ on exactly $A$ and $1$ on exactly $B$ and $\frac{1}{2}$ on exactly $T$. See Urysohn function for a generalization.
If either $A$ or $B$ is bounded, then $d(A,B) > 0$. Otherwise it is possible that $d(A,B) = 0$ despite $A,B$ being closed and disjoint. But this has nothing to do with the river thread so it belongs in this section.
Whether this definition is 'used' in real life I do not not know.
Comment: @MichaelHardy: http://math.stackexchange.com/q/170337/21820 seems to be exactly what I hypothesized and an answer purports to prove it via rather advanced methods (I didn't check it).

Where is the "thread" of a river?


Allowing resizing window pyGame

Question: I am trying to allow resizing for this app, I put the RESIZABLE flag, but when I try to resize, it messes up! Try my code.
It is a grid program, when the window resizes I want the grid to also resize/shrink.
import pygame,math
from pygame.locals import *
# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

# This sets the width and height of each grid location
width=50
height=20
size=[500,500]
# This sets the margin between each cell
margin=1

# Initialize pygame
pygame.init()

# Set the height and width of the screen

screen=pygame.display.set_mode(size,RESIZABLE)

# Set title of screen
pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done=False

# Used to manage how fast the screen updates
clock=pygame.time.Clock()

# -------- Main Program Loop -----------
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
        if event.type == pygame.MOUSEBUTTONDOWN:
            height+=10

    # Set the screen background
    screen.fill(black)

    # Draw the grid
    for row in range(int(math.ceil(size[1]/height))+1):
        for column in range(int(math.ceil(size[0]/width))+1):
            color = white
            pygame.draw.rect(screen,color,[(margin+width)*column+margin,(margin+height)*row+margin,width,height])

    # Limit to 20 frames per second
    clock.tick(20)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()

Please tell me whats wrong, thanks.
Answer: The answer for this problem (allow the Pygame window and the surface inside it to resize) is simply to recreate the resizable window with an updated size, when the user changes its dimensions (done on pygame.VIDEORESIZE events).
>>> import pygame
>>> help(pygame.display.set_mode)
Help on built-in function set_mode in module pygame.display:

set_mode(...)
    set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface
    Initialize a window or screen for display
>>>

This removes all previous content on the window surface, so below
there's a process to continue with the current window content.
Some example code:
import pygame, sys

pygame.init()
# Create the window, saving it to a variable.
surface = pygame.display.set_mode((350, 250), pygame.RESIZABLE)
pygame.display.set_caption("Example resizable window")

while True:
    surface.fill((255,255,255))

    # Draw a red rectangle that resizes with the window.
    pygame.draw.rect(surface, (200,0,0), (surface.get_width()/3,
      surface.get_height()/3, surface.get_width()/3,
      surface.get_height()/3))

    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

        if event.type == pygame.VIDEORESIZE:
            # There's some code to add back window content here.
            surface = pygame.display.set_mode((event.w, event.h),
                                              pygame.RESIZABLE)

How to continue with the current window content:
Here's some steps to add back the previous window content:

make a second variable, set to the value of the old window surface variable.
create the new window, storing it as the old variable.
draw the second surface onto the first one (old variable) - use the blit function.
use this variable and delete the new variable (optional, use del) to not use extra memory.

Some example code for the above steps (replaces pygame.VIDEORESIZE event if statement):
        if event.type == pygame.VIDEORESIZE:
            old_surface_saved = surface
            surface = pygame.display.set_mode((event.w, event.h),
                                              pygame.RESIZABLE)
            # On the next line, if only part of the window
            # needs to be copied, there's some other options.
            surface.blit(old_surface_saved, (0,0))
            del old_surface_saved

Comment: I found [this](https://github.com/pygame/pygame/issues/201) open pygame bug. Shortly: sending VIDEORESIZE event works with resizing by moving edges, but fails after trying to move corners.
Comment: When I run the example above after first second window stops correctly draw resized rectangle in the center.
Answer: You are not updating your width, height, or size when the window changes.
From the docs: http://www.pygame.org/docs/ref/display.html

If the display is set with the pygame.RESIZABLE flag,
  pygame.VIDEORESIZE events will be sent when the user adjusts the
  window dimensions.

You can get the new size, w, h from the event VIDEORESIZE http://www.pygame.org/docs/ref/event.html
Answer: A simple Hello World window that is resizable, plus I was playing around with classes.
Broken down into two files, one for defining the colour constants.
import pygame, sys
from pygame.locals import *
from colors import *

# Data Definition
class helloWorld:
    '''Create a resizable hello world window'''
    def __init__(self):
        pygame.init()
        self.width = 300
        self.height = 300
        DISPLAYSURF = pygame.display.set_mode((self.width,self.height), RESIZABLE)
        DISPLAYSURF.fill(WHITE)

    def run(self):
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == VIDEORESIZE:
                    self.CreateWindow(event.w,event.h)
            pygame.display.update()

    def CreateWindow(self,width,height):
        '''Updates the window width and height '''
        pygame.display.set_caption("Press ESC to quit")
        DISPLAYSURF = pygame.display.set_mode((width,height),RESIZABLE)
        DISPLAYSURF.fill(WHITE)

if __name__ == '__main__':
    helloWorld().run()

colors.py:
BLACK  = (0, 0,0)
WHITE  = (255, 255, 255)
RED    = (255, 0, 0)
YELLOW = (255, 255, 0)
BLUE   = (0,0,255)

GREEN = (0,255,0)

Comment: Code works, but you should really read PEP 8 style guidelines. Youre breaing a lot of conventions with names such as `CreateWindow` that is not a class, `helloWorld`that *is*, and `DISPLAYSURF` that is not a constant. Also, avoid spamming `from ... import *` everywhere, specially since you're not using them (you're prefixing all `pygame` calls anyway)
Comment: @MestreLion, the `from pygame.locals import *` was there for `QUIT`, `RESIZEABLE`, and `VIDEORESIZE`. The pygame calls aren't part of that import... I've submitted an edit, but it's possible that you were actually looking at an earlier version of this example which was different at the time with how pygame was imported.
Answer: A simple way to do which I found was the following code snippet
# Imports
from vars import *
from pygame.locals import *

# Main init
pygame.init()

# Basic vars
run = True
s_width = 1000
s_height = 600

# Making display screen. Don't forget the last tag!
screen = pygame.display.set_mode((s_width, s_height), RESIZABLE)

# Main loop
while run:
    # event detection
    for event in pygame.event.get():
        if event.type == QUIT:
            run = False
        # The part which matters for our purposes
        if event.type == WINDOWRESIZED:
            s_width, s_height = screen.get_width(), screen.get_height()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                run = False
    # Test line to see if the window resizing works properly
    pygame.draw.line(screen, (255, 255, 255), (int(0.3*s_width), int(0.25*s_height)), (int(0.8*s_width), int(0.25*s_height)))
    # Final flip
    pygame.display.flip()

# Quit
pygame.quit()

What this does is allows the pygame window to be resized. But since you often have the placing and sizes of a lot of elements/sprites depending on the s_width and s_height, it also detects when the window size is changed and adjusts the dimensions accordingly.
Answer: First, You don't detect the new window size before redrawing the screen.
Add the get_size() method at line 45 and it works:
#--------------------------------------------------------------
# Draw the grid
size = pygame.display.get_surface().get_size() // size update
for row in range(int(math.ceil(size[1]/height))+1):
#---------------------------------------------------------

Then you work with a fixed cell size (50, 20) and fill as many cells as possible. If You want to GROW/SHRINK the cells when resizing the window, You will have to define the NUMBER of cells per line/row, then calculate the cell size, then draw them.

Allowing resizing window pyGame


ADT list of integers to test program

Question: Is there anywhere I can find an ADT list of integers I can use to test this program I wrote for an assignment question? Or can someone tell me how to make one or provide one for me, it would be greatly appreciated!
 /**
  * Finds the Max integer from the ADT list of integers
  *
  * @author (Siren P)
  * @version (03/12/2016)
  */
  public class MaxIntegers
  {
    public int maxInt (ListReferenceBased aList)
    {
    //Declare variable for max integer
    int max;

    //Checks every integer in list
    for(int i = 0 ; i <= aList.size(); i++)
    {
        if(i == 0)
        {
            //first element stored as max
            max = aList.get(i);
        }
        else
        {
            if(aList.get(i) > max)
            {
                //if element is bigger than current stored element then it will be overwritten
                max = aList.get(i);
            }
        }
    }
    //Returns the max integer
    return max;
}

}
Answer: You can use an ArrayList:
java.util.List<Integer> aList = new java.util.ArrayList<Integer>();

// add some ints to the list
aList.add(1);
aList.add(2);
aList.add(3);
aList.add(4);

Answer: We need the code for the ListReferenceBase class to construct a list. My guess would be that it is a sort of LinkedList, but I don't know the functions the class offers.
Probably something like that would work (put that in your MaxIntegers class)
public static void main(String[] args) {
    MaxIntegers test = new MaxIntegers();
    ListReferenceBased testlist = new ListReferenceBased();
    testlist.add(5);
    testlist.add(2);
    testlist.add(55);
    System.out.println(maxInt(testlist));
}

Besides that a few side notes:

You should declare the method maxInt as static. This means you don't need an object to invoke the method (in this case there is no reason why you would need one, that's why you should make it static.)
Your code likely won't work. If (and this is very likely) ListReferenceBased starts the index at 0, then the condition of your for loop (i <= list.size()) will go too far. The correct way would be i < list.size().

If there is no implementation of ListReferenceBased and it is just a placeholder, you can swap that out in your class and my example with 'LinkedList' for instance. It also would be possible to write List<Integer> instead, which would you allow to pass all kinds of lists to the method, they just have to implement the java.util.List interface.

ADT list of integers to test program


Editing flagged posts

Question: What happens in the following scenario?
I flag a post because (lets say) it's not an answer.
The OP edits the post and adds some valid data.
I see the edit before a moderator can see and validate/invalidate my flag.
I realize that there is no need for the flag anymore.
(How) can I retract my flag? because I realize there is no need to bother the moderator with this.
(this really happened today).
Answer: Moderators can see the edit history. I wouldn't bother trying to notify, but if you felt very strongly about it, go ahead and leave a comment on the thread or message them directly.
Comment: Seams reasonable. I'm waiting for a confirmation from one of the moderators then I will accept this answer.
Comment: Since there is no moderator opinion so far, I guess I can go with this.
Comment: Message me next time. Either on twitter or skype (id: boy-named-sue).

Editing flagged posts


Can you export and import templates for multi-site use?

Question: Is there a way to take a form built on one site, save it as a template, and use it on another site? Currently all themes and modules are shared so I assumed the Webform Tempaltes would be available on all 3 sites but they are not. Is there a way to do this? This is running on Drupal 8 btw.
Answer: If it's Drupal8 you can:

save webform as a webform template
export/import the source file.
 You can copy it and the paste to the new webform on the other site. It will duplicate an identical webform for you.
Comment: @svsdnb You're welcome, glad to help!
Comment: The Export tab is the top right of the above screenshot is an even a better option because you get the entire webform's configuration file which can be imported via  /admin/config/development/configuration/single/import


Retrieve the ID from the value returned by the stored procedure

Question: I want to retrieve the ID from the value returned by the stored procedure and put it into our DataSet. This is the code in VB how to translate it in C # .
Thanks in advance
<code>oRow("ProductId") = cmdCommand.Parameters.Item("@ProductId").Value
</code>
Comment: `oRow["ProductId"] = cmdCommand.Parameters["@ProductId"].Value` or something?
Comment: Soner Gönül is correct. @Amater90 : you can find a VB from/to C# converter here http://converter.telerik.com/
Answer: Another "easy" way to do it would be to use IL SPY to see the code from the DLL then to display it as C#


Derivation of Fourier transform of Heaviside function

Question: I read some proofs of Fourier transform of Heaviside function on this site but I don't really understand (because I haven't learned about distribution yet). I'm trying to derive it myself based on what I learned so far.
I use the following definitions of Heaviside and Dirac delta function:
$$H(t)= \lim_{a\to 0^{+}} H_a(t) \text {, where } H_a(t) = \begin{cases} e^{-at}, & t \geq 0 \\ 0, & \text{otherwise} \end{cases}$$
$$\delta(v)= \lim_{a\to 0^{+}} \delta_a(v) \text {, where } \delta_a(v)= \begin{cases} \frac {1}{a}, & |v| \leq \frac{a}{2} \\ 0, & \text{otherwise} \end{cases}$$
Now, we have:
$$\mathcal {F}\{H(t)\}=\lim_{a\to 0^{+}}\mathcal {F}\{H_a(t)\}=\lim_{a\to 0^{+}} \int_{0}^{\infty} e^{-at}e^{-2i \pi vt}dt = \lim_{a\to 0^{+}} \frac {1}{a+2i \pi v}$$
$$=\lim_{a\to 0^{+}} \frac {a-2i \pi v}{a^2+4 \pi^2 v^2} =\lim_{a\to 0^{+}} \frac {a}{a^2+4 \pi^2 v^2}+\lim_{a\to 0^{+}} \frac {-2i \pi v}{a^2+4 \pi^2 v^2}$$
The second term corresponds to $\frac {1}{2i \pi v}$. But why does the first term correspond to $\frac {1}{2} \delta(v)$?
Comment: The first important thing about distributions is that they are not functions. They only 'live' under intervals. The definition for your $\delta$ doesn't properly reflect this. Which kind of limit are you using in the definition of your functions? What does the equality for the $\delta$ mean? Why can you exchange the limit and the integration?
Comment: I've just edited the definitions. The $\delta(v)$ is equal $+\infty$ if $v=0$, and $0$, otherwise, so I think it's correct by defining as above. I didn't exchange the limit and the integration, I calculated the integral first, then plugged the limit in.
Comment: Ah I see what you mean by exchanging the limit and the integration. You are correct. I haven't found the reason.
Comment: If you regard $\delta$ as a function, it's almost everywhere zero. Thus, every integral containing it will be zero. This is not the behaviour you're expecting from the $\delta$ functional.
Answer: The second term is one form of a nascent delta function. It is in fact the Poisson kernel in the upper half plane, which converges to the Dirac delta impulse:
$$\delta(x)=\lim_{a\rightarrow 0^+}\frac{1}{\pi}\frac{a}{a^2+x^2}$$


Create an isosceles triangle from only equilateral triangles. Possible or impossible?

Question: My friend recently asked me a question. And I think I have a nice solution but wanted to share this question here to see how you approach this problem and hopefully with a solid proof.
The question is:
Can you create an isosceles triangle with an infinite number of any sizes of only equilateral triangles?
Comment: I've added the `puzzle` tag because you have a solution but are holding it back.
Comment: Would *any* isosceles triangle (that is not equilateral) work?
Answer: Start from the 120-30-30 isosceles triangle. We aim to fill this triangle with equilateral triangles in infinite steps.

Draw an equilateral triangle at one-third of the longest side.

Now the triangle is $\frac13$ filled, with two smaller 120-30-30 isosceles triangles created. Repeat the process:

And now $\frac13 + \frac29$ of the triangle is filled. 3rd iteration below.

Why would the initial triangle be filled in infinite steps? The area filled in $n$ steps is equal to:
$$\sum_{k=1}^n \frac13(\frac23)^{k-1}$$
At infinity, this geometric sum evaluates to
$$\sum_{k=1}^\infty \frac13(\frac23)^{k-1} = \frac {1/3}{1-2/3}=1$$
so the whole triangle will be filled, given that we have infinite equilateral triangles of all sizes.
Or, equivalently, considering the fact that $1/3$ of the remaining area is filled in each iteration, we have the area remaining after the $n$th step is $\dfrac1{3^n}$, which $\to 0$ as $n \to \infty$.
Comment: If you want a slightly nontrivial isosceles triangle, please add it to your question body.
Comment: I meant *one* isosceles triangle only. Meaning, the end result should be  one single isosceles triangle.
Comment: What are the construction rules? Are we simply given an infinite number of equilateral triangles of all sizes, and we just cram them into an isosceles triangle? If so, the answer may become quite fractal.
Comment: Yes exactly so. You are given an infinite numbers of equialteral triangles of all sizes and the task is to figure out if its possible to cram them into one single isosceles triangle
Answer: Okay, I'll bite.  I don't know if the triangles are allowed to overlap, but my argument would work in either case.
Assume that we can choose a triangle formed from equilateral triangles that is isosceles but not equilateral. Then the smallest angle of the isosceles triangle is strictly less than 60 degrees.  Let A be the vertex of that angle.  Among the infinite number of equilateral triangles that cover the triangle, choose one that includes point A.  Let A' be the point on that equilateral triangle that covers A.  Any neighborhood of A' would have to include points B' and C' such that m$\angle B'A'C'\ge60^\circ$. But then either B' or C' would be outside the isosceles triangle, which is a contradiction.
Needless to say, except that this is a puzzle: an equilateral triangle itself is isosceles, and you could construct that from an infinite number of equilateral triangle using the Sierpinski triangle as a guide.
Answer: In any triangle, at least one angle is $\ge 60^{\circ}$.
So starting from the corresponding vertex you can draw an equilateral triangle, inscribed in the starting one , and which leaves out two triangles.
For each  of these remaining triangles you can repeat the process and leave out  four. And so on.
Answer: You can fill the interior of any triangle (or more generally, any plane region) with non-overlapping equilateral triangles.  Consider an equilateral triangular lattice $L$, and start with those lattice triangles that are contained in your region $R$.
Then refine the lattice (adding the midpoints of all edges), and take the triangles of the new lattice that are contained in $R$ but are not already covered.  Repeat ad infinitum.
EDIT: You get something that looks like this


Is it true that $2^n$ is $O(n!)$?

Question: I had a similar problem to this saying:
Is it true that $n!$ is $O(2^n)$?
I got that to be false because if we look at the dominant power of $n!$ it results in $n^n$. So because the base numbers are not the same it is false.
Is it true that $2^n$ is $O(n!)$?
So likewise with the bases, this question should result in false, however it is true. Why? Is the approach I am taking to solve these questions wrong?
Comment: By the way, it may be worth pointing out that $n^n$ is not $O(n!)$ (or, in more natural terms, $n!$ is not $\Omega(n^n)$). You may want to look up Stirling approximation formula for good bounds on the growth of $n!$.
Comment: Clearly state the definition of big-O, then you should see why $2^n \leq 2(n!)$ implies that $2^n$ is $O(n!)$
Comment: When we say that a function $f(x)$ is $\text{O}(g(n))$, this has nothing to do with checking the "base numbers."  Your teacher may have given you a faulty definition of big O notation.  If you want an intuitive explanation of big O notation, I would explain it as a method to order functions based on how "fast" they grow.
Answer: Note that big-O only denotes an upper bound. So anything that grows at the same or lesser rate of $n!$ is $O(n!)$.
Answer: $2^n = 2 \cdot 2 \cdots 2 \le 2 \cdot 2  \cdot 3 \cdots  n = 2 \cdot (n!)$ for $n\ge 2$.
Comment: this is also true for $n=1$
Answer: If $f(n)$ is $O(g(n))$, then there is a constant $C$ such that $f(n) \leq C g(n)$ eventually.
It turns out that $2^n$ is $O(n!)$. Can you find a constant $C$ and prove the inequality? Hint: Choose $C=2$ and try to prove $2^n \leq 2 n!$.
Answer: Another approach:
Consider: $$\sum_{n=1}^{\infty}\frac{2^n}{n!}\tag{1}$$
We have that $\limsup_{n\rightarrow \infty}\sqrt[n]{\frac{2^n}{n!}}=\limsup_{n\rightarrow \infty}\frac{2}{\sqrt[n]{n!}}=0$
Because
$$lim_{n\rightarrow \infty}\sqrt[n]{n!}=lim_{n\rightarrow \infty}(n\cdot (n-1)\cdot (n-2)\dots2\cdot 1)^{\frac{1}{n}}\geq lim_{n\rightarrow \infty} (\frac{n}{2}\cdot \frac{n}{2}\dots \frac{n}{2})^{\frac{1}{n}}\geq lim_{n\rightarrow \infty}(\frac{n}{2})^{\lfloor \frac{n}{2}\rfloor\cdot \frac{1}{n}}=\infty$$
Hence the series in (1) is convergent by the root test. So $\frac{2^n}{n!}$ is a zero-sequence from which the statement follows.
Note that you can replace $2$ by any other number.
Answer: Yes it is true.
$$2\le2$$
$$2\cdot2\le2\cdot 3$$
$$2\cdot2\cdot2\le2\cdot 3\cdot 4$$
$$2\cdot2\cdot2\cdot2\le2\cdot 3\cdot 4\cdot 5$$
$$\cdots$$
$$2\cdot2\cdot2\cdot2\cdots2\le2\cdot 3\cdot 4\cdot 5\cdots\cdot n$$
Answer: There's already another anwer to this effect, but perhaps this example gives some much-needed intuition:
What are the values of the following, for $n=10$?
$2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\cdot2\\
1\cdot2\cdot3\cdot4\cdot5\cdot6\cdot7\cdot8\cdot9\cdot10$
See why?
Answer: The criterion "base numbers are different" is not valid.
The functions $2^n$ and $3^n$ have different bases, yet $2^n$ is $O(3^n)$.
On the other hand, $3^n$ is not $O(2^n)$.
If we have fixed constants $m > k > 1$, then $k^n$ as a function of $n$ is $O(m^n)$.
Notice also that $n^n$ is an exponential with a larger base than $2^n$ whenever $n > 2$,
and in general the order $O(f(n))$ of a function $f(n)$
is concerned with what happens as $n$ gets large.
How "large" does $n$ have to be in order to ensure that $n > 2$?
Taking the original function in question, $n!$, again we have
$2^n$ is $O(n!)$ for much the same reasons.
Once $n \geq 4$, the ratio $\frac{n!}{2^n}$ grows by a factor of $2$ (or more) each time
$n$ increases by adding $1$.

Is it true that $2^n$ is $O(n!)$?


expectation of squared summation

Question: How does the expectation of this:
$$E\Bigg[ \bigg(\sum_{n=1}^{N}  x_n \bigg)^2\Bigg]$$
Equal this:
$$E\Bigg[ \bigg(\sum_{n=1}^{N}  x_n \bigg)^2\Bigg]=N(N\mu^2+\sigma^2)$$
I'm also told that  x is Gaussian and i.i.d:
$$E[x] = \mu$$
$$E[x_n^2] = \mu^2 + \sigma^2I_{ij}$$
$$I_{ij} = \begin{cases}
1 & i=j\\
0 & i\ne j \\
\end{cases}$$
$$\mu_{ML} = \frac{1}{M}\sum_{n=1}^{M}x_n$$
$$\sigma^2_{ML}=\frac{1}{M}\sum_{n=1}^{M}(x_n-\mu)^2$$
Answer: You can write the square of the sum as a double sum.
$$E (\sum_{n=1}^N x_n)^2 = E(\sum_{i=1}^N \sum_{j=1}^N x_i x_j)
= \sum_{i=1}^N \sum_{j=1}^N E[x_i x_j]$$
Then note that
$$E[x_i x_j] = \begin{cases} \mu^2 & i \ne j \\ \mu^2 + \sigma^2 & i = j \end{cases}$$
Comment: Cool!  Then there would be $N^2$ of $\mu^2$, and $N$ of $\sigma^2$.
Answer: Two formulas about i.i.d. sums of variables (Gaussian or not):
$$\newcommand{\E}{\operatorname{E}}\newcommand{\Var}{\operatorname{Var}}
\E\,\!\left(\sum_{k=1}^nx_k\right)=n\E(X)\tag1
$$
$$
\Var\left(\sum_{k=1}^nx_k\right)=n\Var(X)\tag2
$$
The variance is the expectation of the squares minus the square of the expectation:
$$
\Var\left(\sum_{k=1}^nx_k\right)=\E\,\!\left[\left(\sum_{k=1}^nx_k\right)^2\right]-\E\left(\sum_{k=1}^nx_k\right)^2\tag3
$$
Putting these together:
$$
\E\,\!\left[\left(\sum_{k=1}^nx_k\right)^2\right]=n\Var(X)+n^2\E(X)^2\tag4
$$

expectation of squared summation


Would like to convert my powered mixer to a power amp

Question: I have a older Yamaha EMX-660 Mono Powered Mixer with 6 channels, our band has expanded with vocals and percussion. To support the additional instruments I've added a 6 XLR input analog mixer (stereo) and send both output channels to the dual line inputs of one the powered mixer channels with the preamp section set to center. It seems to work OK, but I would like to simplify my setup by going to a single  channel (8 XLR inputs) with internal digital reverb and send to three channels on the powered mixer (the main outs (R & L) and monitor out).
The EMX-660 is 300w per channel and works great so I hate to replace it with a power amp at this time, but it is a hassle trying to control sound on two systems. I'm not technical enough to understand how the 6 channels on the EMX work and if sending a 16 channel signal into two channels would harm the power mixer. I'm thinking this would be OK and would basically just use the 3 channels set at neutral and the output volume and EQ.
The powered mixer works great for small events but is limited for full band gigs. I'll appreciate any information or suggestions.
Analog Mixer I'm looking at: (8 XLR with 4 stereo line inputs)
(

)
EMX 660 manual: (https://usa.yamaha.com/files/download/other_assets/3/318553/EMX660E.pdf)
Comment: Your question is a little confusing. If you are sending in to a 2 channel mixer, then you are only sending 2 channels, not 16. If your question is about whether the power amp can take the signal you plan to send it, then you'll need to read the manual to see what output power your mixer has, and what input your amp is rated to.
Comment: @DoktorMayhem - I don't understand how the 'output power' of a mixer is related to the 'input rating' of an amp. I'd have thought any mixer will plug into any power amp (or mixer amp) and be adjustable enough to work.
Comment: @Tim - agreed, however the OP sounds concerned. I'd rather they checked for line output.
Answer: Mixer into mixer is fine. Use the new one, however many channels, into two of the original Yamaha's inputs. Keep the eq flat - or tweak as desired - and regard the new mixer as just another couple of inputs. There may be a couple of ports between pre and post on the Yamaha, so if you really wanted, it could be used as just a power amp., and you'd plug the new mixer into the power amp inputs, bypassing the mixer section. either way, it ought to work. It depends how much control you want or need. Once set up, it'll only need a touch of fiddling between gigs. Don't try to use both reverb units though.
Comment: Thanks so much, that was my concern - currently having to manage two mixers with one limited to the single channel monitor and effects controls is a hassle. I'm looking for a way to manage all my sound settings from a single mixer and use my powered mixer solely as a power amp.  One thing I saw on another similar post was concerns for phantom power between mixers.  Something I had not considered since we use the PA for live work with dynamic mics.


How to update and check data if exists in PDO

Question: I have this code
and Im trying to update the user and check it first if it is already existed.
and my problem is it also check itself as existed user.
How to prevent checking itself as an existed data before updating in PDO?
try
{
    $stmt = $crud->runQuery("SELECT user_name, user_email FROM tbl_login WHERE user_name=:user_name OR user_email=:user_email");
    $stmt->execute(array(':user_name'=>$user_name, ':user_email'=>$user_email));
    $row=$stmt->fetch(PDO::FETCH_ASSOC);

    if($row['user_name']==$user_name)
    {
        $msg = "

            Error! Username is already taken!

";
    }
    else if($row['user_email']==$user_email)
    {
        $msg = "

                Error! Email is already taken!

";
    }
    else
    {
        if($crud->update($edit_id,$user_name,$user_email))
        {
            $msg = "

                Great! Record was updated successfully Dashboard!

";
        }
        else
        {
            $msg = "

                SORRY! ERROR while updating record !

";
        }
    }
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

Comment: Exclude the current user's id that is editing the value  `SELECT user_name, user_email
    FROM tbl_login
    WHERE user_id != :user_id AND
    (user_name=:user_name OR user_email=:user_email)`
Answer: It is easy as you imagine. I won't give you the exact code but I'll give you the logic. You don't have to check data entries 1 by 1. I know you already knew it.

Get the username
Run a query that will find the username.
Check if the query returned more than 1 row.
It returned more than 1 row?
If yes, the username exists. Update it.
Else, it do not exist. Nothing to update.

Goodluck!
Comment: Excelent idea. I dont have to use long long long code
Comment: Yep! You just call `var.rowCOunt()` and its good. Goodluck on your project!
Comment: It's not me. maybe the other viewers
Comment: No worries mate!


TabControl and borders visual glitch

Question: I have these visual glitches on every tabControls when I am changing its tabPages BackColor and the BackColor of the form, as illustrated on the following images:

At the top of the tabPage, there is an interior one-pixel white border.
At the left of the tabPage, there is an interior three-pixels white border.
At the bottom of the tabPage, there is an interior one-pixel white border and an exterior two-pixels white border.
At the right of the tabPage, there is an interior one-pixel white border and an exterior two-pixels white border.

Is there a way I can get rid of those white borders?
Comment: you have to do it by setting DrawMode to Owner and then paint the tabcontrol
Comment: @Rob: I tried changing the padding and margin of the `tabPage` and the `tabControl`, it doesn't change anything.
Comment: What happens if you set the backcolor for the parent(tabcontrol)?
Comment: @Rob: Unfortunately, a `tabControl` has no BackColor property.
Comment: Oke, you could try to set the margin of the tabpage using css..
margin:-1px -3px -3px -3px; It causes the field to be a little bit bigger and override the whitespace
Comment: @rapsalands: I'd rather not go on this way, because I'd have to completely redraw the tabs, and that doesn't seem a piece of cake to get the tabs just as they appear when `DrawMode` is set at `Normal`.
Comment: Something else must be going on.  I can't reproduce that behavior.
Comment: @LarsTech: You don't have any white borders? I just created a new winform application, added a `tabControl` on `Form1`, changed the `BackColor` of `tabPage1` and the `BackColor` of `Form1` and I clearly have all the white borders I have described: http://i.imgur.com/5ZhVH.png
Comment: Sorry, misunderstood the question.  My fault.  I understood "glitch" to mean it was drawing something wrong.  That's just the TabControl doing it's thing with VisualStyles.
Comment: possible duplicate of [How can I remove the border padding on container controls in WinForms?](http://stackoverflow.com/questions/4968267/how-can-i-remove-the-border-padding-on-container-controls-in-winforms)
Answer: Here's my attempted hack.  I used a NativeWindow to draw over the TabControl to fill in those "white" spaces.  I won't claim it's perfect:
public class TabPadding : NativeWindow {
  private const int WM_PAINT = 0xF;

  private TabControl tabControl;

  public TabPadding(TabControl tc) {
    tabControl = tc;
    tabControl.Selected += new TabControlEventHandler(tabControl_Selected);
    AssignHandle(tc.Handle);
  }

  void tabControl_Selected(object sender, TabControlEventArgs e) {
    tabControl.Invalidate();
  }

  protected override void WndProc(ref Message m) {
    base.WndProc(ref m);

    if (m.Msg == WM_PAINT) {
      using (Graphics g = Graphics.FromHwnd(m.HWnd)) {

        //Replace the outside white borders:
        if (tabControl.Parent != null) {
          g.SetClip(new Rectangle(0, 0, tabControl.Width - 2, tabControl.Height - 1), CombineMode.Exclude);
          using (SolidBrush sb = new SolidBrush(tabControl.Parent.BackColor))
          g.FillRectangle(sb, new Rectangle(0,
                                            tabControl.ItemSize.Height + 2,
                                            tabControl.Width,
                                            tabControl.Height - (tabControl.ItemSize.Height + 2)));
        }

        //Replace the inside white borders:
        if (tabControl.SelectedTab != null) {
          g.ResetClip();
          Rectangle r = tabControl.SelectedTab.Bounds;
          g.SetClip(r, CombineMode.Exclude);
          using (SolidBrush sb = new SolidBrush(tabControl.SelectedTab.BackColor))
            g.FillRectangle(sb, new Rectangle(r.Left - 3,
                                              r.Top - 1,
                                              r.Width + 4,
                                              r.Height + 3));
        }
      }
    }
  }
}

And to hook it up:
public Form1() {
  InitializeComponent();
  var tab = new TabPadding(tabControl1);
}

My end result:
Comment: Wow, thank you for that. Thank you very much! Does exactly what one would expect the TabControl to do (and once again "Microsoft, why?!")
Comment: In addition to your answer, to remove all borders
`using (SolidBrush sb = new SolidBrush(tabControl.SelectedTab.BackColor))
                                g.FillRectangle(sb, new Rectangle(r.Left - 4, r.Top - 1, r.Width + 6, r.Height + 7));`
to leave just a small top line
`r.Top - 2,`
Comment: Looks really smooth. For now, I find it perfect. I will keep you up to date if I find some glitch. Thanks a lot, amazing work!
Comment: I couldn't get this solution to work for me. I copied the code exactly and created a new TabPadding with my existing tabControl - it did nothing.
Comment: @stuzor You would have to show me your code in order for me to help you.
Comment: It's perfect, bravo!
Answer: you can inherit from control
public class TabControlEx : TabControl
{
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x1300 + 40)
        {
            RECT rc = (RECT)m.GetLParam(typeof(RECT));
            rc.Left -= 0;
            rc.Right += 3;
            rc.Top -= 0;
            rc.Bottom += 3;
            Marshal.StructureToPtr(rc, m.LParam, true);
        }
        base.WndProc(ref m);
    }

}
internal struct RECT { public int Left, Top, Right, Bottom; }

Comment: This is the only solution on this page that works for me, however I had to adjust Left to -= 4, Right to += 2, and Top to -= 2. Thanks
Comment: Perhaps the exact numbers differ across platforms. This works well "on my machine" but I need different numbers yet again.
Comment: @DrewNoakes same, i got to use 7 on left right and bottom, but top doesn't work instead of removing the lines it removes the tabheaders :|
Answer: I recently ran into this problem and never found a good simple solution.  That's when I thought about simply adjusting the control's clipping region.  This seemed to work just fine with no noticeable side-effects.  The 2 extra white pixels on the right side and the one extra white pixel at the bottom are no longer visible.
class TabControlEx : TabControl
{
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0005) // WM_SIZE
        {
            int Width = unchecked((short)m.LParam);
            int Height = unchecked((short)((uint)m.LParam >> 16));

            // Remove the annoying white pixels on the outside of the tab control
            // by adjusting the control's clipping region to exclude the 2 pixels
            // on the right and one pixel on the bottom.
            Region = new Region(new Rectangle(0, 0, Width - 2, Height - 1));
        }

        base.WndProc(ref m);
    }
}

Comment: This looks like it's fixing overdraw, where contents spill outside. I think the original question is about tab controls that have padding you can't simply remove in the designer.
Comment: Yes, re-reading the original question after all this time it does appear to be a different scenario.  I was using a tab control with default colours on a form with a custom background.  The Tab control was drawing white borders on two sides and this code eliminates that.

TabControl and borders visual glitch


open node reference links in lightbox/ popup

Question: I want in my node view pages, node reference links open in popup window or lightbox window.
Does anyone have a solution?
Comment: do you want to show bubble info, when hovering the link ? or the whole page ?
Answer: In Views Use this code in "Rewrite the output of this field"
[title]

Note: add  "Node:Path" field before the Rewrite field.
You can also set the width and height of the popup window, see the read-me file in Lightbox2  module folder.
hope you will get idea from the above!!
Comment: I have the same problem and the following code does not work for me - I am using the code below to 'Rewrite the output of a field' in Views.

"[title]"

Any idea what is wrong here?

I have lightbox2 module installed and enabled (D6 Version: 6.22 & lightbox2 Version: 6.x-1.11).
Comment: add the title field and reorder before the rewrite field, if not solved let me know


Is the depth buffer size the same as the view port size?

Question: If I perform
<code>#define SCREEN_SIZE 512
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, SCREEN_SIZE, SCREEN_SIZE);
</code>
Does this make my depth buffer size SCREEN_SIZE x SCREEN_SIZE?
Answer:
Does this make my depth buffer size SCREEN_SIZE x SCREEN_SIZE?

No. The depth buffer is part of the window frame buffer. Usually such a window framebuffer consists of

front color plane
back color plane
depth buffer
stencil buffer

All these planes have the same size, namely the size of the window on which the OpenGL context has been created on. The viewport just defines the subset of the window that will be mapped the [-1, 1] range of normalized device coordinates, i.e. it selects a part of the framebuffer which will be used as projection target. The viewport doesn't even need to clip things "outside" the viewport range. If you need this, you must combine it with a scissor test.
Comment: Just use a frame buffer object of the desired size.
Comment: I guess, the next natural question is: how do I set my depth buffer size? I want to use the depth buffer for computation of surface overlapping from a view point.
Comment: I have had a lot of problem getting a good example of using FBO with QtOpenGL which allows me to do this. Perhaps, you have a link that I can peruse?


Varrer String em Busca de Substrings Ignorando Acentuação e Case e Para Cada Match Executar Uma Ação

Question: Preciso buscar em uma string uma substring específica e para cada ocorrência encontrada, devo executar uma ação de substituir o que foi escrito pela versão em negrito, conforme consta na lista, ignorando acentuação e case.
Exemplo:
Possuo a lista com os itens:

Arroz
Batata ao Cheff
Macarrão ao Molho
Salmão

A cada letra digitada sugestões dos itens da lista irão aparecer para o usuário poder selecionar(typeahead), será ignorada a acentuação e será caso insensitivo.
Caso o usuário digite "ão" ou "ao", os seguintes itens devem ser sugeridos:

Batata ao Cheff
Macarrão ao Molho
Salmão

A lista é retornada conforme as regras, mas o texto em negrito é devido a funcão highlighter, porém quando digito "ao" ele não ignora o acento e deixa em negrito apenas o que for 100% igual ao digitado. No caso "Macarrão ao Molho", fica ou "Macarrão ao Molho" ou "Macarrão ao Molho", preciso que sejam as duas ocorrências.
Eu acredito que preciso varrer a string em busca dessa substring e verificar em todas as possíveis acentuações, caso execute um match eu preciso efetuar o replace do texto ão e ao por ão e ao, porém não consigo chegar em nível de código nessa solução.
Highlighter:
//Item é o texto da lista, ex: "Macarrão ao Molho"
//Query é o que foi digitado pelo usuário
//Match é a porção do texto que é igual ao que foi digitado pelo usuário
    function Highlighter(item) {
            var query = $("#ReasonDescription").val().replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
            return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                return '' + match + '';
            })
        },

Matcher
function Matcher(value) {
    var accented = {
        'A': '[Aa\xaa\xc0-\xc5\xe0-\xe5\u0100-\u0105\u01cd\u01ce\u0200-\u0203\u0226\u0227\u1d2c\u1d43\u1e00\u1e01\u1e9a\u1ea0-\u1ea3\u2090\u2100\u2101\u213b\u249c\u24b6\u24d0\u3371-\u3374\u3380-\u3384\u3388\u3389\u33a9-\u33af\u33c2\u33ca\u33df\u33ff\uff21\uff41]',
        'B': '[Bb\u1d2e\u1d47\u1e02-\u1e07\u212c\u249d\u24b7\u24d1\u3374\u3385-\u3387\u33c3\u33c8\u33d4\u33dd\uff22\uff42]',
        'C': '[Cc\xc7\xe7\u0106-\u010d\u1d9c\u2100\u2102\u2103\u2105\u2106\u212d\u216d\u217d\u249e\u24b8\u24d2\u3376\u3388\u3389\u339d\u33a0\u33a4\u33c4-\u33c7\uff23\uff43]',
        'D': '[Dd\u010e\u010f\u01c4-\u01c6\u01f1-\u01f3\u1d30\u1d48\u1e0a-\u1e13\u2145\u2146\u216e\u217e\u249f\u24b9\u24d3\u32cf\u3372\u3377-\u3379\u3397\u33ad-\u33af\u33c5\u33c8\uff24\uff44]',
        'E': '[Ee\xc8-\xcb\xe8-\xeb\u0112-\u011b\u0204-\u0207\u0228\u0229\u1d31\u1d49\u1e18-\u1e1b\u1eb8-\u1ebd\u2091\u2121\u212f\u2130\u2147\u24a0\u24ba\u24d4\u3250\u32cd\u32ce\uff25\uff45]',
        'F': '[Ff\u1da0\u1e1e\u1e1f\u2109\u2131\u213b\u24a1\u24bb\u24d5\u338a-\u338c\u3399\ufb00-\ufb04\uff26\uff46]',
        'G': '[Gg\u011c-\u0123\u01e6\u01e7\u01f4\u01f5\u1d33\u1d4d\u1e20\u1e21\u210a\u24a2\u24bc\u24d6\u32cc\u32cd\u3387\u338d-\u338f\u3393\u33ac\u33c6\u33c9\u33d2\u33ff\uff27\uff47]',
        'H': '[Hh\u0124\u0125\u021e\u021f\u02b0\u1d34\u1e22-\u1e2b\u1e96\u210b-\u210e\u24a3\u24bd\u24d7\u32cc\u3371\u3390-\u3394\u33ca\u33cb\u33d7\uff28\uff48]',
        'I': '[Ii\xcc-\xcf\xec-\xef\u0128-\u0130\u0132\u0133\u01cf\u01d0\u0208-\u020b\u1d35\u1d62\u1e2c\u1e2d\u1ec8-\u1ecb\u2071\u2110\u2111\u2139\u2148\u2160-\u2163\u2165-\u2168\u216a\u216b\u2170-\u2173\u2175-\u2178\u217a\u217b\u24a4\u24be\u24d8\u337a\u33cc\u33d5\ufb01\ufb03\uff29\uff49]',
        'J': '[Jj\u0132-\u0135\u01c7-\u01cc\u01f0\u02b2\u1d36\u2149\u24a5\u24bf\u24d9\u2c7c\uff2a\uff4a]',
        'K': '[Kk\u0136\u0137\u01e8\u01e9\u1d37\u1d4f\u1e30-\u1e35\u212a\u24a6\u24c0\u24da\u3384\u3385\u3389\u338f\u3391\u3398\u339e\u33a2\u33a6\u33aa\u33b8\u33be\u33c0\u33c6\u33cd-\u33cf\uff2b\uff4b]',
        'L': '[Ll\u0139-\u0140\u01c7-\u01c9\u02e1\u1d38\u1e36\u1e37\u1e3a-\u1e3d\u2112\u2113\u2121\u216c\u217c\u24a7\u24c1\u24db\u32cf\u3388\u3389\u33d0-\u33d3\u33d5\u33d6\u33ff\ufb02\ufb04\uff2c\uff4c]',
        'M': '[Mm\u1d39\u1d50\u1e3e-\u1e43\u2120\u2122\u2133\u216f\u217f\u24a8\u24c2\u24dc\u3377-\u3379\u3383\u3386\u338e\u3392\u3396\u3399-\u33a8\u33ab\u33b3\u33b7\u33b9\u33bd\u33bf\u33c1\u33c2\u33ce\u33d0\u33d4-\u33d6\u33d8\u33d9\u33de\u33df\uff2d\uff4d]',
        'N': '[Nn\xd1\xf1\u0143-\u0149\u01ca-\u01cc\u01f8\u01f9\u1d3a\u1e44-\u1e4b\u207f\u2115\u2116\u24a9\u24c3\u24dd\u3381\u338b\u339a\u33b1\u33b5\u33bb\u33cc\u33d1\uff2e\uff4e]',
        'O': '[Oo\xba\xd2-\xd6\xf2-\xf6\u014c-\u0151\u01a0\u01a1\u01d1\u01d2\u01ea\u01eb\u020c-\u020f\u022e\u022f\u1d3c\u1d52\u1ecc-\u1ecf\u2092\u2105\u2116\u2134\u24aa\u24c4\u24de\u3375\u33c7\u33d2\u33d6\uff2f\uff4f]',
        'P': '[Pp\u1d3e\u1d56\u1e54-\u1e57\u2119\u24ab\u24c5\u24df\u3250\u3371\u3376\u3380\u338a\u33a9-\u33ac\u33b0\u33b4\u33ba\u33cb\u33d7-\u33da\uff30\uff50]',
        'Q': '[Qq\u211a\u24ac\u24c6\u24e0\u33c3\uff31\uff51]',
        'R': '[Rr\u0154-\u0159\u0210-\u0213\u02b3\u1d3f\u1d63\u1e58-\u1e5b\u1e5e\u1e5f\u20a8\u211b-\u211d\u24ad\u24c7\u24e1\u32cd\u3374\u33ad-\u33af\u33da\u33db\uff32\uff52]',
        'S': '[Ss\u015a-\u0161\u017f\u0218\u0219\u02e2\u1e60-\u1e63\u20a8\u2101\u2120\u24ae\u24c8\u24e2\u33a7\u33a8\u33ae-\u33b3\u33db\u33dc\ufb06\uff33\uff53]',
        'T': '[Tt\u0162-\u0165\u021a\u021b\u1d40\u1d57\u1e6a-\u1e71\u1e97\u2121\u2122\u24af\u24c9\u24e3\u3250\u32cf\u3394\u33cf\ufb05\ufb06\uff34\uff54]',
        'U': '[Uu\xd9-\xdc\xf9-\xfc\u0168-\u0173\u01af\u01b0\u01d3\u01d4\u0214-\u0217\u1d41\u1d58\u1d64\u1e72-\u1e77\u1ee4-\u1ee7\u2106\u24b0\u24ca\u24e4\u3373\u337a\uff35\uff55]',
        'V': '[Vv\u1d5b\u1d65\u1e7c-\u1e7f\u2163-\u2167\u2173-\u2177\u24b1\u24cb\u24e5\u2c7d\u32ce\u3375\u33b4-\u33b9\u33dc\u33de\uff36\uff56]',
        'W': '[Ww\u0174\u0175\u02b7\u1d42\u1e80-\u1e89\u1e98\u24b2\u24cc\u24e6\u33ba-\u33bf\u33dd\uff37\uff57]',
        'X': '[Xx\u02e3\u1e8a-\u1e8d\u2093\u213b\u2168-\u216b\u2178-\u217b\u24b3\u24cd\u24e7\u33d3\uff38\uff58]',
        'Y': '[Yy\xdd\xfd\xff\u0176-\u0178\u0232\u0233\u02b8\u1e8e\u1e8f\u1e99\u1ef2-\u1ef9\u24b4\u24ce\u24e8\u33c9\uff39\uff59]',
        'Z': '[Zz\u0179-\u017e\u01f1-\u01f3\u1dbb\u1e90-\u1e95\u2124\u2128\u24b5\u24cf\u24e9\u3390-\u3394\uff3a\uff5a]'
    };

    var pattern = function (query) {
        var words = query.replace(/([|()[{.+*?^$\\])/g, '\\$1').split(/\s+/);

        words.sort(function (a, b) {
            return b.length - a.length;
        });

        for (var i = 0; i < words.length; i++) {
            words[i] = words[i].replace(/\S/g, function (character) {
                return accented[character.toUpperCase()] || character;
            });
        }
        return new RegExp(words.join("|"), 'g');
    };

    return value.match(pattern(value));
}

Comment: Exatamente isso. Preciso chamar o replace para substituir "ão" e "ao" por suas versões em negrito.
Comment: Fiz este pequeno código que quem sabe pode dar alguma ideia: https://jsfiddle.net/h1gpea5v/
Answer: A ideia básica é pegar o que foi digitado e fazer a busca desconsiderando os acentos e as diferenças entre maiúsculas e minúsculas. Depois, para cada ocorrência que for encontrada, você quebra o texto entre antes e depois do trecho buscado, além do próprio trecho (dentro da tag strong).
Segue o código, e mais abaixo, a - longa - explicação:

const itens = [ 'Arroz', 'Batata ao Cheff', 'Macarrão ao Molho', 'Salmão' ];

function buscarItens(e) {
    const res = document.querySelector('#resultado ul');
    res.innerHTML = ''; // limpa os resultados

    const busca = e.target.value.normalize('NFD').replace(/\p{M}/ug, ''); // o que foi digitado e deve ser buscado (removendo os acentos)
    const regex = new RegExp(busca.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'ig');
    for (const item of itens) { // para cada item do menu
        const text = item.normalize('NFD').replace(/\p{M}/ug, '');
        let i = 0;
        const li = document.createElement('li'); // cria o elemento que terá o texto com highlight
        for (const match of text.matchAll(regex)) { // verificar todas as ocorrências da busca
            li.appendChild(document.createTextNode(item.slice(i, match.index))); // texto antes da palavra encontrada

            i = match.index + busca.length;
            let strong = document.createElement('strong');
            strong.appendChild(document.createTextNode(item.slice(match.index, i))); // palavra destacada (a "busca")
            li.appendChild(strong);
        }
        li.appendChild(document.createTextNode(item.slice(i))); // texto depois da palavra
        if (li.childElementCount != 0) { // se encontrou algo, adiciona nos resultados
            res.appendChild(li);
        }
    }
}

// cada vez que digitar algo no input, faz a busca
document.querySelector('#busca').addEventListener('input', buscarItens);
<input type="text" id="busca">

Remover acentos
Primeiro eu pego o que foi digitado e removo os acentos:
const busca = e.target.value.normalize('NFD').replace(/\p{M}/ug, '');

O funcionamento do método normalize é explicado em detalhes aqui, mas para resumir, uma letra acentuada, como o á (letra a com acento agudo), segundo o Unicode, pode ser representada de duas maneiras:

composta - como o code point U+00E1 (LATIN SMALL LETTER A WITH ACUTE) (á)
decomposta - como uma combinação de dois code points (nesta ordem):

a letra "a" (sem acento): U+0061 (LATIN SMALL LETTER A)
o acento agudo: U+0301 (COMBINING ACUTE ACCENT)

E para entender o que é um code point, leia aqui.
A primeira forma é chamada NFC, e a segunda, NFD. Portanto, o código acima primeiro normaliza a string para NFD, "quebrando" os acentos em dois caracteres: a letra sem acento e o próprio acento.
Depois o replace usa o Unicode Property Escape \p{M}, que pega todos os caracteres das categorias "Mark" (são todas que começam com "M" desta lista). Todos os acentos se encaixam nesta categoria, e como eu faço o replace para '' (string vazia), na prática é o mesmo que remover os acentos. Ou seja, se a string for ão, ela se torna ao.
Vale lembrar que para o Unicode Property Escape funcionar, precisa da flag u (é a letra u depois das barras, ver aqui para mais detalhes), e atualmente já possui um bom suporte da maioria dos browsers. Também uso a flag g para que ele substitua todas as ocorrências (sem esta flag, ele só substitui a primeira).

Construir a regex para a busca
No próximo trecho:
const regex = new RegExp(busca.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'ig');

Na string de busca (que já teve os acentos removidos no passo anterior), eu faço replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'). Isso serve para sanitizar a string, já que ela será usada posteriormente para construir uma regex (expressão regular). E como esta regex será construída a partir de algo digitado pelo usuário, deve-se tomar cuidado com os meta-caracteres (caracteres que possuem significado especial e precisam ser escapados com \). Este replace é explicado em mais detalhes aqui (e neste link também tem outros pontos que se aplicam ao seu caso, sobre construir regex a partir de entradas do usuário - sugiro que leia).
Por fim, eu crio a regex usando o construtor de RegExp, que recebe a string com os meta-caracteres escapados e as flags i (case insensitive) e g (procura todas as ocorrências).

A busca
Na busca, eu pego o nome do item e também removo os acentos, da mesma forma feita com a string de busca:
const text = item.normalize('NFD').replace(/\p{M}/ug, '');

Depois eu percorro todos os matches que a regex encontrar (for (const match of text.matchAll(regex))), e para cada trecho encontrado eu pego o texto que está antes dele, o próprio trecho encontrado (colocando-o dentro da tag strong) e o trecho que vem depois.
Vale lembrar que se for encontrada mais de uma ocorrência, todas são colocadas dentro de uma tag strong. Por exemplo:

Repare que eu digitei "ão", e no caso do "Macarrão ao Molho" o resultado ficou "Macarrão ao Molho" (tanto o "ão" quanto o "ao") foram trocados.
Se você só quer trocar uma ocorrência, ficaria diferente. Precisaria retirar a flag g e trocar matchAll por match (e não usar um for, já que o retorno é somente um resultado):

const itens = [ 'Arroz', 'Batata ao Cheff', 'Macarrão ao Molho', 'Salmão' ];

function buscarItens(e) {
    const res = document.querySelector('#resultado ul');
    res.innerHTML = ''; // limpa os resultados

    const busca = e.target.value.normalize('NFD').replace(/\p{M}/ug, ''); // o que foi digitado e deve ser buscado (removendo os acentos)

    // *** Aqui: não tem mais a flag g ***
    const regex = new RegExp(busca.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'i');

    for (const item of itens) { // para cada item do menu
        const text = item.normalize('NFD').replace(/\p{M}/ug, '');
        const li = document.createElement('li'); // cria o elemento que terá o texto com highlight
        // *** Aqui: trocar matchAll por match e não usar for ***
        const match = text.match(regex);
        if (match) {
            li.appendChild(document.createTextNode(item.slice(0, match.index))); // texto antes da palavra encontrada

            const i = match.index + busca.length;
            let strong = document.createElement('strong');
            strong.appendChild(document.createTextNode(item.slice(match.index, i))); // palavra destacada (a "busca")
            li.appendChild(strong);

            li.appendChild(document.createTextNode(item.slice(i))); // texto depois da palavra
            res.appendChild(li);
        }
    }
}

// cada vez que digitar algo no input, faz a busca
document.querySelector('#busca').addEventListener('input', buscarItens);
<input type="text" id="busca">

Outro ponto é que não foi dado detalhes do HTML, então assumi que seria uma lista (ul), por isso cada resultado da busca ficou em um li. De qualquer forma, não é difícil adaptar para outros casos, pois a lógica seria a mesma (texto antes, texto da busca dentro de strong, texto depois).
Answer: A Ideia
Para pegar todas as substring de uma string que respeitam um certo padrão e inserir a tag  entre os índices que aparecem tal padrão, onde padrão não é case sensitive e ignora acentuação, devemos transformar o conteúdo dessa string deixando ela em caixa baixa e tirar sua acentuação, e depois achar os índices que batem com o padrão e então inserir  entre índice e indice+size_padrao.
Como você já conseguiu achar o padrão e inserir a tag , irei explicar como consegui deixar a string em caixa baixa e retirar sua acentuação
Deixando em caixa baixa, e retirando a acentuação
Para transformar uma string em caixa baixa, é simples, apenas temos que usar a função toLowerCase(). Agora só falta retirar a acentuação.
Na língua portuguesa temos acentos nas letras: a, e, i, o, u, c. Logo se criarmos uma expressão regular para achar cada uma dessa letras acentuadas, e substituirmos pela letra sem acento, então teremos a string sem acentuação.
// Regex para pegar acentos
var ACENTO_REGEX = {
  'a': /[\xE0-\xE6]/g,
  'e': /[\xE8-\xEB]/g,
  'i': /[\xEC-\xEF]/g,
  'o': /[\xF2-\xF6]/g,
  'u': /[\xF9-\xFC]/g,
  'c': /\xE7/g
}

// Retira acento e deixa em minúsculo
function padronizaStr(str) {
  // Deixa em minúsculo
  str = str.toLowerCase();

  // Retira os acentos
  for(var re in ACENTO_REGEX) {
    str = str.replace(ACENTO_REGEX[re], re)
  }

  return str;
}

Exemplo
Criei uma lista para demonstrar como seria, mas você pode alterar e colocar da forma que resolva o seu problema usando a mesma ideia.
OBS.: Usei uma variável chamada padrao como se já tivesse o valor do campo nela, apenas como exemplo.

// Regex para pegar acentos
var ACENTO_REGEX = {
  'a': /[\xE0-\xE6]/g,
  'e': /[\xE8-\xEB]/g,
  'i': /[\xEC-\xEF]/g,
  'o': /[\xF2-\xF6]/g,
  'u': /[\xF9-\xFC]/g,
  'c': /\xE7/g
}

// Tamanho de
var TAG_SIZE = ''.length;

// Busca os valores em
, a partir de

function liValues(ulNodes) {
  var liArr = [];

  ulNodes.forEach(function(li) {
    if(li.innerText)
      liArr.push(li.innerText);
  });

  return liArr;
}

// Retira acento e deixa em minúsculo
function padronizaStr(str) {
  // Deixa em minúsculo
  str = str.toLowerCase();

  // Retira os acentos
  for(var re in ACENTO_REGEX) {
    str = str.replace(ACENTO_REGEX[re], re)
  }

  return str;
}

// Altera a lista
function alteraLista(ul, arrLi) {
  // Remove todos os
 de

  ul.empty();

  // Adiciona novos

  arrLi.forEach(function(li) {
    ul.append(`<li>${li}</li>`);
  });
}

function aplicaAlteracao() {
  var ulNodes = $('ul')[0].childNodes;
  var liArr = liValues(ulNodes);

  var padrao = "ao";
  padrao = padronizaStr(padrao);

  liArr = liArr.map(function(str) {
    // Vamos usar li, para não perdermos o valor de str
    li = str;

    // Deixa todos os valores com o padrão
    // Minúsculo e sem acentos
    li = padronizaStr(li);

    // Acha os indices que dão Match com o padrão
    var idxs = [];
    var re = new RegExp('\(' + padrao + ')', 'ig');

    while ((match = re.exec(li)) != null) {
      idxs.push(match.index);
    }

    idxs.forEach(function(val, idx) {
      var arr = str.split('');

      // Inserindo
      arr.splice(val+(idx*TAG_SIZE), 0, '');
      arr.splice(val+padrao.length+1+(idx*TAG_SIZE), 0, '')

      str = arr.join('');
    });

    return str;
  });

  alteraLista($('ul'), liArr)
}

Arroz

Batata ao Cheff

Macarrão ao Molho

Salmão

<button onclick="aplicaAlteracao()">
  Altera!
</button>


Convergence of $a_n=d(u_n,\Bbb{Z})$ where $u_n=\bigl(\frac{1+\sqrt{5}}{2}\bigr)^n$.

Question:
I would like to  study the sequence defined by
  $$
a_n=d(u_n,\Bbb{Z}).
$$
Where $u_n=\bigl(\frac{1+\sqrt{5}}{2}\bigr)^n$ and $d(u_n,\Bbb{Z})=\inf\{d(u_n,x):x\in\Bbb{Z}\}$.

I do not really have ideas, here is some 'though',
$$a_{n+1}-a_n=d(u_{n+1},\Bbb{Z})-d(u_n,\Bbb{Z})=\inf(\{d(u_{n+1},x):x\in\Bbb{Z}\})-\inf(\{d(u_{n},x):x\in\Bbb{Z}\}).$$
Now by theorem I have $\vert d(u_{n+1},\Bbb{Z})-d(u_n,\Bbb{Z})\vert\le\Vert u_{n+1}-u_n\Vert$.
Let us compute $\Vert u_{n+1}-u_n\Vert=\Vert\bigl(\frac{1+\sqrt{5}}{2}\bigr)^{n+1}-\bigl(\frac{1+\sqrt{5}}{2}\bigr)^n\Vert=\Vert\bigl(\frac{1+\sqrt{5}}{2}\bigr)^n\frac{\sqrt{5}-1}2\Vert.$

After that I am not sure what I have to do. Any ideas?
Answer: Hint: Show that
$$\left(\frac{1+\sqrt{5}}{2}\right)^n+\left(\frac{1-\sqrt{5}}{2}\right)^n$$
is an integer. The second term has limit $0$.
Remark: There are many ways to show that our expression $\alpha^n+\beta^n$ is an integer. One way is by induction, using the fact that
$$\alpha^{n+1}+\beta^{n+1}=(\alpha+\beta)(\alpha^n+\beta^n)-\alpha\beta(\alpha^{n-1}+\beta^{n-1}),$$
and $\alpha+\beta$ and $\alpha\beta$ are integers.
Another way is to show that each of $\alpha^n$ and $\beta^n$, and therefore their sum, satisfies the recurrence $x_{n+1}=x_n+x_{n-1}$. Then from the fact that $\alpha^0+\beta^0$ and $\alpha^1+\beta^1$ are integers, we can conclude that $\alpha^n+\beta^n$ is an integer for all $n$. By the way, these are the Lucas numbers, close relatives of the Fibonacci numbers.
Whenever $\frac{1+\sqrt{5}}{2}$ has a problem, its conjugate $\frac{1-\sqrt{5}}{2}$ is ready to pitch in and help.
Comment: Oh great idea, using Binomial theorem I think I got it. So I have to replace that $(\frac{1+\sqrt{5}}{2})^n=k-(\frac{1-\sqrt{5}}{2})^n$?
Comment: The Binomial Theorem will work, but it leads to some complications because of the denominator $2$. You need to prove that the the $n$-th power has shape $\frac{a\pm\sqrt{5}}{2}$, which is not entirely obvious, since the "natural" denominator is $2^n$.  But for the rest, the fact that $\alpha^n+\beta_n$ is an integer $k_n$ shows essentially immediately that the distance from $\alpha^n$ to the nearest integer approaches $0$, indeed fairly fast.
Comment: Right, I concluded too fast. I am reading your remark, thank you for this method.(+1)
Comment: I had typos in the previous comment, wanted has shape $\frac{a\pm b\sqrt{5}}{2}$ where $a$ and $b$ are integers. Also had $\alpha^n+\beta_n$, and $\alpha^n+\beta^n$ was intended.


Variance of total number of customers arriving

Question: Suppose a customer arrival to a gas station follows a non-stationary Poisson process with the following arrival rate per hour:

[6am - 9am] has $\lambda = 20$.
[9am - 3pm] has $\lambda = 8$.
[3pm - 7pm] has $\lambda = 12$.
[7pm - 10pm] has $\lambda = 6$.

Compute the variance of total number of customers that arrive in a single day.
My attempt Let $X = $ total number of customers that arrive in a single day. Then $Var(X) = E(X^2)- [E(X)]^2 = (20^2\times 3+8^2\times 6+12^2\times 4 + 6^2\times 3) -  (20\times 3+8\times 6+12\times 4 + 6\times 3)^2 = 2268-174^2 = -28008$
However, this number is negative, so it does not make sense in the context of this problem. But I could not see why it's wrong though, considering the way to compute $E(X)$ is actually correct. Could someone please point out the mistake for $E(X^2)$?
Comment: Your method might suggest that a Poisson distribution with $\lambda=20$ had $E(X^2)=20^2$ and so its variance would be $20^2-(20)^2=0$
Comment: Your expressions for $E(X^2)$ contain an error, though I think one of the numbers you have written down is the answer
Comment: @Henry: really? Why $[E(X)]^2$ is wrong? Could you elaborate on your thought?
Comment: Originally you forgot to square $E(X)$.  Your subsequent edit corrected that.
Comment: But then why $E(X^2)$ has error then? I could not see:p could you be clearer please?
Comment: I see. So maybe I would have to use conditional variance formula then?
Comment: No - the variance of a Poisson distribution is $\lambda$ so it has $E(X^2)=\lambda+\lambda^2$
Answer: You have a Poisson process $N(t)$ on the probability space $(\Omega, \mathcal{F}, P)$. Let X=N(16), i.e. the total number of customers in a single 16-hour day.
You want to use that $Y_1=N(3)-N(0)$, $Y_2=N(9)-N(3)$, $Y_3=N(13)-N(9)$ and $Y_4=N(16)-N(13)$ are independent and each $\text{Poisson}(\lambda_i)$-distributed, where
$\lambda_1 = 3\cdot 20=60, \lambda_2 = 6 \cdot 8 = 48, \lambda_3 = 4 \cdot 12 = 48, \lambda_4 = 3 \cdot 6 = 18$.
For a Poisson-distributed random variable $M$ with parameter $\lambda_M$, $\text{Var}(M)=\mathbb{E}[M]=\lambda_M$.
Now $\mathbb{E}[X]=\mathbb{E}[Y_1+Y_2+Y_3+Y_4]=\sum_{i=1}^4 \mathbb{E}[Y_i]=\sum_{i=1}^4 \lambda_i$, and due to independence,
$\text{Var}(X)=\text{Var}(Y_1+Y_2+Y_3+Y_4)=\sum_{i=1}^4 \text{Var}(Y_i) = \sum_{i=1}^4 \mathbb{E}[Y_i] = \mathbb{E}[X]$.
Comment: Wonderful! The result might at first seem counter-intuitive - shouldn't different periods with different arrival rates yield a higher variance than a constant arrival rate throughout the whole day, one could ask. But that is where the independent increments of the Poisson process come into play. Therefore I think the  problem you stated here is excellent to keep in mind if one is considering to build some model using the Poisson process.
Comment: I know, that I did not directly answer your question. I think the important part of the problem is the idea of splitting it into different periods - so I tried to point you in that direction instead.
Comment: Excellent help! Many thanks, Furrer. I see what I got wrong now:)
Answer: Two key points:

A Poisson distribution with parameter $\lambda$ (i.e. its mean and variance) has $E(X^2)=\lambda+\lambda^2$: this is the error in your calculation as you were using $E(X^2)=\lambda^2$
The sum of two independent Poisson distributions with parameters  $\lambda$ and $\mu$ is another Poisson distribution with parameter  $\lambda+\mu$

So you have $16$ independent Poisson distributions and their sum is another Poisson distribution with parameter  $20\times 3+8\times 6+12\times 4 + 6\times 3 =174$. This is therefore the variance of the sum as well as being its mean.
Comment: many thanks man! My key problem was I did not realize the final process is Poisson:) Could you also give this problem a try? http://math.stackexchange.com/questions/1929973/probability-of-cars-being-blocked-during-red-light


Validação required com if ViewModel

Question: Estou tentando fazer a validação de campos com a ViewModel
Desta forma não está funcionando:
 [Display(Name = "Insc. Estadual")]
public string InscricaoEstadual { get; set; }

[Display(Name = "Inscrição Isento")]
public bool InscricaoIsento { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (InscricaoIsento == false && string.IsNullOrEmpty(InscricaoEstadual))
    {
        yield return new ValidationResult("O campo Insc. Estadual é obrigatorio.");
     }
}

Se o campo InscricaoIsento for false e InscricaoEstadual for vazio, ele informa que o campo é obrigatório.
Esta função não está funcionando, não consigo entender porque, está na ViewModel.
Comment: Isso já não foi respondido aqui https://pt.stackoverflow.com/questions/331767/condi%C3%A7%C3%A3o-if-com-required-viewmodel/331806#331806 ? **Senão**, coloque mais informações nessa pergunta, como o código completo do Model e a Action da Controller para que possamos ajudar.
Comment: @Renan ele não está funcionando.
Comment: Coloque mais informações nessa pergunta, como o código completo do Model e a Action da Controller para que possamos ajudar.
Comment: Eu só preciso da validação do campo, porém como if como descrito, desta forma não está validando.
Comment: Se usar a notação de [Required] pode ser que lhe atenda.
Comment: Se o campo InscricaoIsento for false e InscricaoEstadual for vazio, ele informa que o campo é obrigatório. Mas se o campo InscricaoIsento for true, o InscricaoEstadual não precisa ser preenchido Infelizmente não atend.e
Answer: Amigo, tente fazer assim:
[Display(Name = "Insc. Estadual")]
[Required]
public string InscricaoEstadual { get; set; }

[Display(Name = "Inscrição Isento")]
[Required]
public bool InscricaoIsento { get; set; }

Incluindo o [Required] nos seus campos.
Comment: Se o campo InscricaoIsento for false e InscricaoEstadual for vazio, ele informa que o campo é obrigatório.  Mas se o campo InscricaoIsento for true, o InscricaoEstadual não precisa ser preenchido.
Comment: Ah, ok! Tebte fazer via javascript. Chamando uma validacao no evento OnClick
Answer: Seu view model está herdando do IValidatableObject?
Tente assim:
public class Empresa : IValidatableObject

Comment: Eu fiz, mesmo assim não funcionou.
Comment: Em seu controller, você fez a validação do ModelState.ValidationState?
Comment: Ele faz a validação `ModelState.IsValid`
Comment: A fim de teste, experimenta colocar os campos afetados na validação no construtor, dessa maneira: yield return new ValidationResult("O campo Insc. Estadual é obrigatorio.", new[] { "InscricaoIsento "});
Comment: Já está assim, conforme na pergunta.
Comment: Me desculpe, mas, na pergunta está utilizando um construtor com apenas um parâmetro, sendo este a mensagem de erro, o que eu sugeri é utilizar o construtor de dois parâmetros, informando a mensagem de erro e a lista de variáveis afetadas.
Comment: É pq quando vi o comentário ainda estava igual, fiz o teste e mesmo assim não funcionou.

Validação required com if ViewModel


Are stack based arrays possible in C#?

Question: Let's say, hypothetically (read: I don't think I actually need this, but I am curious as the idea popped into my head), one wanted an array of memory set aside locally on the stack, not on the heap. For instance, something like this:
private void someFunction()
{
    int[20] stackArray; //C style; I know the size and it's set in stone
}

I'm guessing the answer is no. All I've been able to find is heap based arrays. If someone were to need this, would there be any workarounds? Is there any way to set aside a certain amount of sequential memory in a "value type" way? Or are structs with named parameters the only way (like the way the Matrix struct in XNA has 16 named parameters (M11-M44))?
Answer: What you want is stackalloc; unfortunately, you can only use this in unsafe code, which means it won't run in a limited permissions context.
You could also create a struct with the necessary number of variables in it for each element type, but you would need a new type for each size of 'array' you wanted to use
Comment: `Nullable` is still a struct, so it wont work. Think about it - when you declare a recursive struct, you're basically asking the CLR to allocate space for an infinite list of structs.
Comment: Hm, what about a primitive LinkedList? On your struct set previous / next struct of same type...you don't get ICollection semantics, but it could be enough for IEnumerable...
Comment: Thanks for the reply. Yes, are struct based LinkedLists possible? And do you have an idea why there isn't a Safe stack based array option in .NET?
Comment: @Frank: You can't do this - when I try to compile a recursive struct, I get a 'CS0523: Struct member  causes a cycle in the struct layout'
Comment: @thecoop What if you make your node nullable?
Comment: Thanks for the help. I don't know why a stack based array isn't possible in safe code though. I can't see how an array is much different than a struct or why this isn't possible...but that's another matter altogether I guess
Comment: Thanks for checking out...it does make sense as you explain it. Clever compiler!
Comment: Stack based arrays would be unsafe to use, because a reference to the array might outlive the array (which will get destroyed as soon as the function quits). A new array type with different behavior would be needed for such an array.
Answer: The closest thing I can think of to a stack-based array would be a manually-nested structure; for an array of size N^M, the code size would be O(MN) and the access time O(M); one could scale M and N as convenient (e.g. one could handle a 4096-element array as six-deep nested 4-element structures, four-deep nested 8-element structures or three-deep nested 16-element structures, two-deep nested 64-element structures, etc.)  If one wanted to do three-deep nesting of 16-element arrays (probably the most practical trade-off) one would define a 16-element structure with fields f0 through f15, and an access method using switch/case to select an element.  One could then define a 16-element structure of those, a 16-element structure of those, etc.
In general, using a standard Array is apt to be better than using value-type structures to mimic arrays, but there are times when having an array-ish thing as a value type would be advantageous.  The advantages of value type arrays would tend to be limited in .net, however, by some limitations in its handling of manipulating value types by reference.  While it would be nice if one could simply access element 0x123 from an array described as above by writing "MyArrayishThing[1][2][3]", that would be inefficient for reading and ineffective for writing (since the subexpression MyArrayishThing[1] would make a copy of structures holding 256 elements of the array).  Instead, what's necessary is to pass MyArrayishThing[1] by reference to a routine that can access element 2 of that and pass it by reference to a routine to access element 3 of that.  It's possible to do that efficiently, but the code ends up looking rather nasty.

Are stack based arrays possible in C#?


SQL Server - encrypting data in a database table's column

Question: I've got a problem scenario w.r.t data cyphering or encryption/decryption in SQL Server 2005.
Scenario:

There is a specific table in the database
The table has a column, let's say "Credit Card"
The requirements is that the content or data in this column should be encrypted

Required (plausible) solution:

Data that is inserted in this table's column should be encrypted, i.e., is unreadable to people running direct queries on the database and/or table; or only by using a specific decryption logic, which requires a KEY of some sort
While reading the data in any application, the method-of-decryption should be easy, maybe KEY based
The process or methodology should be easy to use
But difficult to break

Please give me some suggestions or solution in this regards.
Thank you.
Comment: Does the data only need to be encrypted while in storage, or is the requirement that the unencrypted data should be inaccessible on the database level? (Should the encryption be done in the database layer or in a higher layer; DAL or application?)
Answer:
you encrypt data with a symmetric key
you encrypt the symmetric key with a certificate
you encrypt the certificate with a password
periodically you generate a new symmetric key to encrypt new data
priodically you rotate the certificate and re-encrypt the symmetric keys with the new certifictae, dropping the old certificate

Application requests password from the user and opens the certificate in the session. It then uses DECRYPTKEYBYAUTOCERT to encrypt the data. This is the general industry standard. It protects data rest and guards against accidental media loss as well as access from a person not knowing the password.
You will find a lot of bad advise ont his topic. Any scheme that is 'automated' and does not requests the user for a a decryption password is wrong. If you want 'automated' encryption or decryption you should look into Transparent Data Encryption which protects agains accidental media loss. TDE does not protect against other users browsing the data, if they have access priviledges.
Comment: @SteveGreene 2014 yes. 2016 adds new features, like [Always Encrypted](https://msdn.microsoft.com/en-us/library/mt163865.aspx)
Comment: Remus, is this still the way to go with SQL 2014?
Answer: Try looking into the DecryptByKey function.


Cadastra N pra 1 e N pra N?

Question: Como posso fazer para cadastrar em um relacionamento 1 pra N e de N pra M, estou fazendo desta maneira, mas não está legal:
$endereco = new endereco;
$endereco->complemento = $request->complemento;
$endereco->logradouro = $request->logradouro;
$endereco->bairro = $request->bairro;
$endereco->cidade = $request->cidade;
$endereco->estado = $request->estado;
$endereco->cep = $request->cep;
$endereco->save();

$civil = new civil;
$civil->nome = $request->nome;
$civil->cpf = $request->cpf;
$civil->matricula = $request->matricula;
$civil->data_nascimento = $request->data_nascimento;
$civil->pai = $request->pai;
$civil->mae = $request->mae;
$civil->situacao = $request->situacao;
$civil->sexo = $request->sexo;
$civil->matricula = $request->matricula;
$civil->estado_civil = $request->estado_civil;
$endereco->civil()->save($civil);

Comment: O que seria legal?
Comment: https://pt.stackoverflow.com/questions/236486/insert-many-to-many-laravel-5-4/236600#236600 um exemplo
Comment: Já percebi que você tem algumas perguntas, mas, não interage com a comunidade, porque?
Comment: Desculpa.
É que não sei como devo fazer. Se for seguir esse padrão o código vai ficar muito grande. sem falar que não consigo fazer a relação de muitos pra muitos no laravel. Se puder me ajudar serei muito grato.
Comment: você precisa disponibilizar as duas classes! para que eu possa ver, não me parece dificil resolver, mas, eu não sei o que você fez nas classes model! e você tem perguntas em aberto, é bom interagir e creditar se resolver seus problemas, ajuda e muito outras pessoas
Answer: Se nao estou em erro, a chave do endereço fica do lado do civil. A sequencia das entidades está corecta, mas vejo um problema na linha: $endereco->civil()->save($civil);.
Se deseja "setar" o codigo do endereço deve vir algo como $civil->endereco_id = $endereco->id; e por fim $civil->save();
Aconselho a veres sobre Eloquent Relationships em https://laravel.com/docs/5.5/eloquent-relationships

Cadastra N pra 1 e N pra N?


Google Apps Script Copy Range If Condition Met

Question: I have two spreadsheets, source and destination. In source I have data sheet and in destination I have archive sheet. In data sheet J column contains percentages. I am trying to workout a script which automatically copies the range (A:I) of the rows that has greater than 10% in the J cell to append in the archive sheet.
I'm stuck at this point:
function CopyRange() {
  var sourcespread = SpreadsheetApp.openById('aaa'); //replace with source ID
  var sourcesheet = sourcespread.getSheetByName('bbb'); //replace with source Sheet tab name
  var destspread = SpreadsheetApp.openById('ccc'); //replace with destination ID
  var destsheet = destspread.getSheetByName('ddd'); //replace with destination Sheet tab name
  var testrange = sourcesheet.getRange('J:J');
  var testvalue = (testrange.setNumberFormat("0.00").getValues());
  var data = [];
  var j =[];
  //Condition to check in J:J, if true, copy the same row to data array
  for (i=0;i<testvalue.length;i++) {
    if (testvalue[i] >= 10) {
    data.push.apply(data,sourcesheet.getRange(i+1,1,1,3).getValues());
  //Copy matched ROW numbers to j
    j.push(i);
}
}
  //Copy data array to destination sheet
  destsheet.getRange(destsheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}

I'm getting error:

TypeError: Cannot read property 'length' of undefined (line 19, file "cp3")
Comment: @Marios attached the screenshot, kindly take a look
Comment: then `1.8>10` will evaluate to **false**.  This is why you are getting the error.
Comment: @Marios that's the first row... there are many rows that are above 10
Comment: true.. Is this the source sheet ? (`bbb`) or the destination sheet (`ddd`) ?
Answer: Issue:
if (testvalue[i] >= 10)

This condition is never satisfied, therefore data is a 1D array (=[]) and not a 2D array. Therefore,

data=[]
data[0] =undefined(has no value in index 0)
data[0].length => Throws:

TypeError: Cannot read property 'length' of undefined (line 19, file "cp3")

The reason the  condition is never satisfied is because

In data sheet J column contains percentages

The value of 10% is 0.1(10/100) and NOT 10.
Solution:

Use 0.1 instead of 10

In addition, As the previous answer mentions , testValue is a 2D array.  Although implicit conversion to number will take place, it is preferable to use proper index:
if (testvalue[i][0] >= 0.1)

To read:

What does the range method getValues() return and setValues() accept?

Best practices
Answer: Issue:

testvalue is a 2D array of values, therefore in the if condition
you are comparing a row with a value, instead of a value vs
value. Therefore, you should flat the array: var testvalue = testrange.setNumberFormat("0.00").getValues().flat();

Solution:
function CopyRange() {
  var sourcespread = SpreadsheetApp.openById('aaa'); //replace with source ID
  var sourcesheet = sourcespread.getSheetByName('bbb'); //replace with source Sheet tab name
  var destspread = SpreadsheetApp.openById('ccc'); //replace with destination ID
  var destsheet = destspread.getSheetByName('ddd'); //replace with destination Sheet tab name
  var testrange = sourcesheet.getRange('J:J');
  var testvalue = testrange.getValues().flat();
  var data = [];
  var j =[];
  //Condition to check in J:J, if true, copy the same row to data array
  for (i=0;i<testvalue.length;i++) {
    if (testvalue[i] >= 10) {
    data.push.apply(data,sh.getRange(i+1,1,1,3).getValues());
  //Copy matched ROW numbers to j
    j.push(i);
}
}
  //Copy data array to destination sheet
if(data.length!=0){destsheet.getRange(destsheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);}
}

Comment: @TheMaster yes I noticed my mistake. Sorry for that :) I voted up your answer :)
Comment: I was the one  who [wrote the original script](https://stackoverflow.com/a/48691791). Over time, I've seen various copy pastes on this site itself. All without even  attempting to remove my signature comment: `//Copy matched ROW numbers to j`. So, I know `push.apply` works. It was one of my first attempts to `flat`(Those days We didn't have `flat` :)).
Comment: @TheMaster please don't take it offensive... Thank you for the script, I tried multiple threads to find a way... but didn't see that, I'll credit the original post from next time...  if I plainly ask what I want, ppl say I didn't even try... I'm trying to learn by example and also by the hard way. Hope you'd understand
Comment: @Nix It's ok. But if I may ask, where did you find the script?
Comment: @TheMaster https://stackoverflow.com/questions/56261647/google-apps-script-copy-rows-from-one-sheet-containing-todays-date-into-anoth
Comment: @Marios I changed it accordingly but the error comes... J:J contained formula and I made the change (*100) so it comes as desired but still I'm getting the same error
Comment: @Nix could you please share a screenshot of J column? It would really help us identify the issue.