text:
Q: Split array into chunks Let's say that I have an Javascript array looking as following:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?

A: I tested the different answers into jsperf.com. The result is available there: https://web.archive.org/web/20150909134228/https://jsperf.com/chunk-mtds
And the fastest function (and that works from IE8) is this one:
function chunk(arr, chunkSize) {
  if (chunkSize <= 0) throw "Invalid chunk size";
  var R = [];
  for (var i=0,len=arr.length; i<len; i+=chunkSize)
    R.push(arr.slice(i,i+chunkSize));
  return R;
}

A: Splice version using ES6

let  [list,chunkSize] = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], 6];
list = [...Array(Math.ceil(list.length / chunkSize))].map(_ => list.splice(0,chunkSize))
console.log(list);

A: If you use EcmaScript version >= 5.1, you can implement a functional version of chunk() using array.reduce() that has O(N) complexity:

function chunk(chunkSize, array) {
    return array.reduce(function(previous, current) {
        var chunk;
        if (previous.length === 0 ||
                previous[previous.length -1].length === chunkSize) {
            chunk = [];   // 1
            previous.push(chunk);   // 2
        }
        else {
            chunk = previous[previous.length -1];   // 3
        }
        chunk.push(current);   // 4
        return previous;   // 5
    }, []);   // 6
}

console.log(chunk(2, ['a', 'b', 'c', 'd', 'e']));
// prints [ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e' ] ]

Explanation of each // nbr above:

*

*Create a new chunk if the previous value, i.e. the previously returned array of chunks, is empty or if the last previous chunk has chunkSize items

*Add the new chunk to the array of existing chunks

*Otherwise, the current chunk is the last chunk in the array of chunks

*Add the current value to the chunk

*Return the modified array of chunks

*Initialize the reduction by passing an empty array

Currying based on chunkSize:
var chunk3 = function(array) {
    return chunk(3, array);
};

console.log(chunk3(['a', 'b', 'c', 'd', 'e']));
// prints [ [ 'a', 'b', 'c' ], [ 'd', 'e' ] ]

You can add the chunk() function to the global Array object:

Object.defineProperty(Array.prototype, 'chunk', {
    value: function(chunkSize) {
        return this.reduce(function(previous, current) {
            var chunk;
            if (previous.length === 0 ||
                    previous[previous.length -1].length === chunkSize) {
                chunk = [];
                previous.push(chunk);
            }
            else {
                chunk = previous[previous.length -1];
            }
            chunk.push(current);
            return previous;
        }, []);
    }
});

console.log(['a', 'b', 'c', 'd', 'e'].chunk(4));
// prints [ [ 'a', 'b', 'c' 'd' ], [ 'e' ] ]

A: The following ES2015 approach works without having to define a function and directly on anonymous arrays (example with chunk size 2):
[11,22,33,44,55].map((_, i, all) => all.slice(2*i, 2*i+2)).filter(x=>x.length)

If you want to define a function for this, you could do it as follows (improving on K._'s comment on Blazemonger's answer):
const array_chunks = (array, chunk_size) => array
    .map((_, i, all) => all.slice(i*chunk_size, (i+1)*chunk_size))
    .filter(x => x.length)

A: Use chunk from lodash
lodash.chunk(arr,<size>).forEach(chunk=>{
  console.log(chunk);
})

A: js

function splitToBulks(arr, bulkSize = 20) {
    const bulks = [];
    for (let i = 0; i < Math.ceil(arr.length / bulkSize); i++) {
        bulks.push(arr.slice(i * bulkSize, (i + 1) * bulkSize));
    }
    return bulks;
}

console.log(splitToBulks([1, 2, 3, 4, 5, 6, 7], 3));

typescript
function splitToBulks<T>(arr: T[], bulkSize: number = 20): T[][] {
    const bulks: T[][] = [];
    for (let i = 0; i < Math.ceil(arr.length / bulkSize); i++) {
        bulks.push(arr.slice(i * bulkSize, (i + 1) * bulkSize));
    }
    return bulks;
}

A: results = []
chunk_size = 10
while(array.length > 0){
   results.push(array.splice(0, chunk_size))
}

A: Here is an example where I split an array into chunks of 2 elements, simply by splicing chunks out of the array until the original array is empty.

    const array = [86,133,87,133,88,133,89,133,90,133];
    const new_array = [];

    const chunksize = 2;
    while (array.length) {
        const chunk = array.splice(0,chunksize);
        new_array.push(chunk);
    }

    console.log(new_array)

A: The one line in pure javascript:

function chunks(array, size) {
  return Array.apply(0,{length: Math.ceil(array.length / size)}).map((_, index) => array.slice(index*size, (index+1)*size))
}

// The following will group letters of the alphabet by 4
console.log(chunks([...Array(26)].map((x,i)=>String.fromCharCode(i + 97)), 4))

A: You can use the Array.prototype.reduce function to do this in one line.

let arr = [1,2,3,4];
function chunk(arr, size)
{
    let result = arr.reduce((rows, key, index) => (index % size == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []);
    return result;
}

console.log(chunk(arr,2));

A:

const array = ['a', 'b', 'c', 'd', 'e'];
const size = 2;
const chunks = [];
while (array.length) {
    chunks.push(array.splice(0, size));
}
console.log(chunks);

A: in coffeescript:

b = (a.splice(0, len) while a.length)

demo
a = [1, 2, 3, 4, 5, 6, 7]

b = (a.splice(0, 2) while a.length)
[ [ 1, 2 ],
  [ 3, 4 ],
  [ 5, 6 ],
  [ 7 ] ]

A: And this would be my contribution to this topic. I guess .reduce() is the best way.

var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                    : (r.push([e]), r), []),
        arr = Array.from({length: 31}).map((_,i) => i+1);
        res = segment(arr,7);
console.log(JSON.stringify(res));

But the above implementation is not very efficient since .reduce() runs through all arr function. A more efficient approach (very close to the fastest imperative solution) would be, iterating over the reduced (to be chunked) array since we can calculate it's size in advance by Math.ceil(arr/n);. Once we have the empty result array like Array(Math.ceil(arr.length/n)).fill(); the rest is to map slices of the arr array into it.

function chunk(arr,n){
  var r = Array(Math.ceil(arr.length/n)).fill();
  return r.map((e,i) => arr.slice(i*n, i*n+n));
}

arr = Array.from({length: 31},(_,i) => i+1);
res = chunk(arr,7);
console.log(JSON.stringify(res));

So far so good but we can still simplify the above snipet further.

var chunk = (a,n) => Array.from({length: Math.ceil(a.length/n)}, (_,i) => a.slice(i*n, i*n+n)),
    arr   = Array.from({length: 31},(_,i) => i+1),
    res   = chunk(arr,7);

console.log(JSON.stringify(res));

A: ES6 Generator version
function* chunkArray(array,size=1){
    var clone = array.slice(0);
    while (clone.length>0)
      yield clone.splice(0,size);
};
var a = new Array(100).fill().map((x,index)=>index);
for(const c of chunkArray(a,10))
    console.log(c);

A: ES6 spreads functional #ohmy #ftw

const chunk =
  (size, xs) =>
    xs.reduce(
      (segments, _, index) =>
        index % size === 0
          ? [...segments, xs.slice(index, index + size)]
          : segments,
      []
    );

console.log( chunk(3, [1, 2, 3, 4, 5, 6, 7, 8]) );

A: Here's a recursive solution that is tail call optimize.

const splitEvery = (n, xs, y=[]) =>
  xs.length===0 ? y : splitEvery(n, xs.slice(n), y.concat([xs.slice(0, n)]))

console.log(splitEvery(2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

A: If you are using Underscore JS, just use :
var result = _.chunk(arr,elements_per_chunk)

Most projects already use underscore as a dependency, anyways.

A: You can take this ES6 chunk function, which is easy to use:

const chunk = (array, size) =>
  Array.from({length: Math.ceil(array.length / size)}, (value, index) => array.slice(index * size, index * size + size));

const itemsPerChunk = 3;
const inputArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

const newArray = chunk(inputArray, itemsPerChunk);
console.log(newArray.length); // 3,

document.write(JSON.stringify(newArray)); //  [ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g' ] ]

A: For a functional solution, using Ramda:
Where popularProducts is your input array, 5 is the chunk size

import splitEvery from 'ramda/src/splitEvery'

splitEvery(5, popularProducts).map((chunk, i) => {
// do something with chunk

})

A: I'd prefer to use splice method:
var chunks = function(array, size) {
  var results = [];
  while (array.length) {
    results.push(array.splice(0, size));
  }
  return results;
};

A: Nowadays you can use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!

A: ES6 one-line approach based on Array.prototype reduce and push methods:
const doChunk = (list, size) => list.reduce((r, v) =>
  (!r.length || r[r.length - 1].length === size ?
    r.push([v]) : r[r.length - 1].push(v)) && r
, []);

console.log(doChunk([0,1,2,3,4,5,6,7,8,9,10,11,12], 5));
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]

A: This is the most efficient and straight-forward solution I could think of:
function chunk(array, chunkSize) {
    let chunkCount = Math.ceil(array.length / chunkSize);
    let chunks = new Array(chunkCount);
    for(let i = 0, j = 0, k = chunkSize; i < chunkCount; ++i) {
        chunks[i] = array.slice(j, k);
        j = k;
        k += chunkSize;
    }
    return chunks;
}

A: This is what i use, it might not be super fast, but it is compact and simple:

let chunksplit = (stream, size) => stream.reduce((chunks, item, idx, arr) => (idx % size == 0) ? [...chunks, arr.slice(idx, idx + size)] : chunks, []);
//if the index is a multiple of the chunksize, add new array

let testArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];

document.write(JSON.stringify( chunksplit(testArray, 5) ));
//using JSON.stringify for the nested arrays to be shown

A: example with
unchanged source array
and not making all the chunks at once. (memory saver!)
const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];

const chunkSize = 4
for (var i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    console.log('chunk=',chunk)
    // do whatever
}
console.log('src array didnt changed. array=',array)

A: With mutation of the source array:
let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], aa = [], x
while((x = a.splice(0, 2)).length) aa.push(x)

// aa == [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
// a == []

Without mutating the source array:
let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], aa = []
for(let i = 0; i < a.length; i += 2) aa.push(a.slice(i, i + 2))

// aa == [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
// a == [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

A: Old question: New answer! I actually was working with an answer from this question and had a friend improve on it! So here it is:
Array.prototype.chunk = function ( n ) {
    if ( !this.length ) {
        return [];
    }
    return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};

[1,2,3,4,5,6,7,8,9,0].chunk(3);
> [[1,2,3],[4,5,6],[7,8,9],[0]]

A: One more solution using Array.prototype.reduce():

const chunk = (array, size) =>
  array.reduce((acc, _, i) => {
    if (i % size === 0) acc.push(array.slice(i, i + size))
    return acc
  }, [])

// Usage:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunked = chunk(numbers, 3)
console.log(chunked)

This solution is very similar to the solution by Steve Holgado. However, because this solution doesn't utilize array spreading and doesn't create new arrays in the reducer function, it's faster (see jsPerf test) and subjectively more readable (simpler syntax) than the other solution.
At every nth iteration (where n = size; starting at the first iteration), the accumulator array (acc) is appended with a chunk of the array (array.slice(i, i + size)) and then returned. At other iterations, the accumulator array is returned as-is.
If size is zero, the method returns an empty array. If size is negative, the method returns broken results. So, if needed in your case, you may want to do something about negative or non-positive size values.

If speed is important in your case, a simple for loop would be faster than using reduce() (see the jsPerf test), and some may find this style more readable as well:
function chunk(array, size) {
  // This prevents infinite loops
  if (size < 1) throw new Error('Size must be positive')

  const result = []
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size))
  }
  return result
}

A: EDIT: @mblase75 added more concise code to the earlier answer while I was writing mine, so I recommend going with his solution.
You could use code like this:
var longArray = ["Element 1","Element 2","Element 3", /*...*/];
var smallerArrays = []; // will contain the sub-arrays of 10 elements each
var arraySize = 10;
for (var i=0;i<Math.ceil(longArray.length/arraySize);i++) {
    smallerArrays.push(longArray.slice(i*arraySize,i*arraySize+arraySize));
}

Change the value of arraySize to change the maximum length of the smaller arrays.

A: Here is a non-mutating solution using only recursion and slice().
const splitToChunks = (arr, chunkSize, acc = []) => (
    arr.length > chunkSize ?
        splitToChunks(
            arr.slice(chunkSize),
            chunkSize,
            [...acc, arr.slice(0, chunkSize)]
        ) :
        [...acc, arr]
);

Then simply use it like splitToChunks([1, 2, 3, 4, 5], 3) to get [[1, 2, 3], [4, 5]].
Here is a fiddle for you to try out: https://jsfiddle.net/6wtrbx6k/2/

A: I tried a recursive function…
const chunk = (arr, n) =>
    arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

…which is nice and short, but seems to take about 256× as long as @AymKdn's answer for 1,000 elements, and 1,058× as long for 10,000 elements!

A: Here's a ES6 version using reduce

const perChunk = 2 // items per chunk

const inputArray = ['a','b','c','d','e']

const result = inputArray.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index/perChunk)

  if(!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  return resultArray
}, [])

console.log(result); // result: [['a','b'], ['c','d'], ['e']]

And you're ready to chain further map/reduce transformations.
Your input array is left intact

If you prefer a shorter but less readable version, you can sprinkle some concat into the mix for the same end result:
inputArray.reduce((all,one,i) => {
   const ch = Math.floor(i/perChunk);
   all[ch] = [].concat((all[ch]||[]),one);
   return all
}, [])

You can use remainder operator to put consecutive items into different chunks:
const ch = (i % perChunk);

A: There have been many answers but this is what I use:
const chunk = (arr, size) =>
  arr
    .reduce((acc, _, i) =>
      (i % size)
        ? acc
        : [...acc, arr.slice(i, i + size)]
    , [])

// USAGE
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk(numbers, 3)

// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

First, check for a remainder when dividing the index by the chunk size.
If there is a remainder then just return the accumulator array.
If there is no remainder then the index is divisible by the chunk size, so take a slice from the original array (starting at the current index) and add it to the accumulator array.
So, the returned accumulator array for each iteration of reduce looks something like this:
// 0: [[1, 2, 3]]
// 1: [[1, 2, 3]]
// 2: [[1, 2, 3]]
// 3: [[1, 2, 3], [4, 5, 6]]
// 4: [[1, 2, 3], [4, 5, 6]]
// 5: [[1, 2, 3], [4, 5, 6]]
// 6: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// 7: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// 8: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// 9: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

A: I think this a nice recursive solution with ES6 syntax:

const chunk = function(array, size) {
  if (!array.length) {
    return [];
  }
  const head = array.slice(0, size);
  const tail = array.slice(size);

  return [head, ...chunk(tail, size)];
};

console.log(chunk([1,2,3], 2));

A: ONE-LINER
const chunk = (a,n)=>[...Array(Math.ceil(a.length/n))].map((_,i)=>a.slice(n*i,n+n*i));

For TypeScript
const chunk = <T>(arr: T[], size: number): T[][] =>
  [...Array(Math.ceil(arr.length / size))].map((_, i) =>
    arr.slice(size * i, size + size * i)
  );

DEMO

const chunk = (a,n)=>[...Array(Math.ceil(a.length/n))].map((_,i)=>a.slice(n*i,n+n*i));
document.write(JSON.stringify(chunk([1, 2, 3, 4], 2)));

Chunk By Number Of Groups
const part=(a,n)=>[...Array(n)].map((_,i)=>a.slice(i*Math.ceil(a.length/n),(i+1)*Math.ceil(a.length/n)));

For TypeScript
const part = <T>(a: T[], n: number): T[][] => {
  const b = Math.ceil(a.length / n);
  return [...Array(n)].map((_, i) => a.slice(i * b, (i + 1) * b));
};

DEMO

const part = (a, n) => {
    const b = Math.ceil(a.length / n);
    return [...Array(n)].map((_, i) => a.slice(i * b, (i + 1) * b));
};

document.write(JSON.stringify(part([1, 2, 3, 4, 5, 6], 2))+'<br/>');
document.write(JSON.stringify(part([1, 2, 3, 4, 5, 6, 7], 2)));

A: Here's my approach using Coffeescript list comprehension. A great article detailing comprehensions in Coffeescript can be found here.
chunk: (arr, size) ->
    chunks = (arr.slice(index, index+size) for item, index in arr by size)
    return chunks

A: Here is neat & optimised implemention of chunk() function. Assuming default chunk size is 10.
var chunk = function(list, chunkSize) {
  if (!list.length) {
    return [];
  }
  if (typeof chunkSize === undefined) {
    chunkSize = 10;
  }

  var i, j, t, chunks = [];
  for (i = 0, j = list.length; i < j; i += chunkSize) {
    t = list.slice(i, i + chunkSize);
    chunks.push(t);
  }

  return chunks;
};

//calling function
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var chunks = chunk(list);

A: This should be straightforward answer without many mathematical complications.
function chunkArray(array, sizeOfTheChunkedArray) {
  const chunked = [];

  for (let element of array) {
    const last = chunked[chunked.length - 1];

    if(!last || last.length === sizeOfTheChunkedArray) {
      chunked.push([element])
    } else {
      last.push(element);
    }
  }
  return chunked;
}

A: The most efficient way is to treat the array as Iterable, and do lazy pagination. That way, it will produce data only when requested. The code below uses operator page from iter-ops library:
import {pipe, page} from 'iter-ops';

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // some input data

const i = pipe(arr, page(2)); //=> Iterable<number>

console.log(...i); //=> [ 1, 2 ] [ 3, 4 ] [ 5, 6 ] [ 7, 8 ] [ 9 ]

Works the same way for any Iterable or AsyncIterable.

P.S I'm the author of the library.

A: Ok, let's start with a fairly tight one:
function chunk(arr, n) {
    return arr.slice(0,(arr.length+n-1)/n|0).
           map(function(c,i) { return arr.slice(n*i,n*i+n); });
}

Which is used like this:
chunk([1,2,3,4,5,6,7], 2);

Then we have this tight reducer function:
function chunker(p, c, i) {
    (p[i/this|0] = p[i/this|0] || []).push(c);
    return p;
}

Which is used like this:
[1,2,3,4,5,6,7].reduce(chunker.bind(3),[]);

Since a kitten dies when we bind this to a number, we can do manual currying like this instead:
// Fluent alternative API without prototype hacks.
function chunker(n) {
   return function(p, c, i) {
       (p[i/n|0] = p[i/n|0] || []).push(c);
       return p;
   };
}

Which is used like this:
[1,2,3,4,5,6,7].reduce(chunker(3),[]);

Then the still pretty tight function which does it all in one go:
function chunk(arr, n) {
    return arr.reduce(function(p, cur, i) {
        (p[i/n|0] = p[i/n|0] || []).push(cur);
        return p;
    },[]);
}

chunk([1,2,3,4,5,6,7], 3);

A: Modified from an answer by dbaseman: https://stackoverflow.com/a/10456344/711085

Object.defineProperty(Array.prototype, 'chunk_inefficient', {
  value: function(chunkSize) {
    var array = this;
    return [].concat.apply([],
      array.map(function(elem, i) {
        return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
      })
    );
  }
});

console.log(
  [1, 2, 3, 4, 5, 6, 7].chunk_inefficient(3)
)
// [[1, 2, 3], [4, 5, 6], [7]]

minor addendum:
I should point out that the above is a not-that-elegant (in my mind) workaround to use Array.map. It basically does the following, where ~ is concatenation:
[[1,2,3]]~[]~[]~[] ~ [[4,5,6]]~[]~[]~[] ~ [[7]]

It has the same asymptotic running time as the method below, but perhaps a worse constant factor due to building empty lists. One could rewrite this as follows (mostly the same as Blazemonger's method, which is why I did not originally submit this answer):
More efficient method:

// refresh page if experimenting and you already defined Array.prototype.chunk

Object.defineProperty(Array.prototype, 'chunk', {
  value: function(chunkSize) {
    var R = [];
    for (var i = 0; i < this.length; i += chunkSize)
      R.push(this.slice(i, i + chunkSize));
    return R;
  }
});

console.log(
  [1, 2, 3, 4, 5, 6, 7].chunk(3)
)

My preferred way nowadays is the above, or one of the following:
Array.range = function(n) {
  // Array.range(5) --> [0,1,2,3,4]
  return Array.apply(null,Array(n)).map((x,i) => i)
};

Object.defineProperty(Array.prototype, 'chunk', {
  value: function(n) {

    // ACTUAL CODE FOR CHUNKING ARRAY:
    return Array.range(Math.ceil(this.length/n)).map((x,i) => this.slice(i*n,i*n+n));

  }
});

Demo:
> JSON.stringify( Array.range(10).chunk(3) );
[[1,2,3],[4,5,6],[7,8,9],[10]]

Or if you don't want an Array.range function, it's actually just a one-liner (excluding the fluff):
var ceil = Math.ceil;

Object.defineProperty(Array.prototype, 'chunk', {value: function(n) {
    return Array(ceil(this.length/n)).fill().map((_,i) => this.slice(i*n,i*n+n));
}});

or
Object.defineProperty(Array.prototype, 'chunk', {value: function(n) {
    return Array.from(Array(ceil(this.length/n)), (_,i)=>this.slice(i*n,i*n+n));
}});

A: Try to avoid mucking with native prototypes, including Array.prototype, if you don't know who will be consuming your code (3rd parties, coworkers, yourself at a later date, etc.).
There are ways to safely extend prototypes (but not in all browsers) and there are ways to safely consume objects created from extended prototypes, but a better rule of thumb is to follow the Principle of Least Surprise and avoid these practices altogether.
If you have some time, watch Andrew Dupont's JSConf 2011 talk, "Everything is Permitted: Extending Built-ins", for a good discussion about this topic.
But back to the question, while the solutions above will work, they are overly complex and requiring unnecessary computational overhead. Here is my solution:
function chunk (arr, len) {

  var chunks = [],
      i = 0,
      n = arr.length;

  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }

  return chunks;
}

// Optionally, you can do the following to avoid cluttering the global namespace:
Array.chunk = chunk;

A: Using generators

function* chunks(arr, n) {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

let someArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log([...chunks(someArray, 2)]) // [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]

Can be typed with Typescript like so:

function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

A: I aimed at creating a simple non-mutating solution in pure ES6. Peculiarities in javascript make it necessary to fill the empty array before mapping :-(
function chunk(a, l) {
    return new Array(Math.ceil(a.length / l)).fill(0)
        .map((_, n) => a.slice(n*l, n*l + l));
}

This version with recursion seem simpler and more compelling:
function chunk(a, l) {
    if (a.length == 0) return [];
    else return [a.slice(0, l)].concat(chunk(a.slice(l), l));
}

The ridiculously weak array functions of ES6 makes for good puzzles :-)

A: The array.slice() method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.
const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2.
Note that a chunkSize of 0 will cause an infinite loop.

A: Created a npm package for this https://www.npmjs.com/package/array.chunk
var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.slice(i, size + i));
}
return result;

When using a TypedArray
var result = [];

for (var i = 0; i < arr.length; i += size) {
  result.push(arr.subarray(i, size + i));
}
return result;

A: Using Array.prototype.splice() and splice it until the array has element.

Array.prototype.chunk = function(size) {
    let result = [];

    while(this.length) {
        result.push(this.splice(0, size));
    }

    return result;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.chunk(2));

Update
Array.prototype.splice() populates the original array and after performing the chunk() the original array (arr) becomes [].
So if you want to keep the original array untouched, then copy and keep the arr data into another array and do the same thing.

Array.prototype.chunk = function(size) {
  let data = [...this];
  let result = [];

    while(data.length) {
        result.push(data.splice(0, size));
    }

    return result;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log('chunked:', arr.chunk(2));
console.log('original', arr);

P.S: Thanks to @mts-knn for mentioning the matter.

A: I recommend using lodash. Chunking is one of many useful functions there.
Instructions:
npm i --save lodash

Include in your project:
import * as _ from 'lodash';

Usage:
const arrayOfElements = ["Element 1","Element 2","Element 3", "Element 4", "Element 5","Element 6","Element 7","Element 8","Element 9","Element 10","Element 11","Element 12"]
const chunkedElements = _.chunk(arrayOfElements, 10)

You can find my sample here:
https://playcode.io/659171/

A: I created the following JSFiddle to demonstrate my approach to your question.

(function() {
  // Sample arrays
  var //elements = ["0", "1", "2", "3", "4", "5", "6", "7"],
      elements = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43"];

  var splitElements = [],
      delimiter = 10; // Change this value as needed

  // parameters: array, number of elements to split the array by
  if(elements.length > delimiter){
   splitElements = splitArray(elements, delimiter);
  }
  else {
   // No need to do anything if the array's length is less than the delimiter
   splitElements = elements;
  }

  //Displaying result in console
  for(element in splitElements){
   if(splitElements.hasOwnProperty(element)){
     console.log(element + " | " + splitElements[element]);
    }
  }
})();

function splitArray(elements, delimiter) {
  var elements_length = elements.length;

  if (elements_length > delimiter) {
    var myArrays = [], // parent array, used to store each sub array
      first = 0, // used to capture the first element in each sub array
      index = 0; // used to set the index of each sub array

    for (var i = 0; i < elements_length; ++i) {
      if (i % delimiter === 0) {
       // Capture the first element of each sub array from the original array, when i is a modulus factor of the delimiter.
        first = i;
      } else if (delimiter - (i % delimiter) === 1) {
      // Build each sub array, from the original array, sliced every time the i one minus the modulus factor of the delimiter.
        index = (i + 1) / delimiter - 1;
        myArrays[index] = elements.slice(first, i + 1);
      }
      else if(i + 1 === elements_length){
       // Build the last sub array which contain delimiter number or less elements
       myArrays[index + 1] = elements.slice(first, i + 1);
      }
    }
    // Returned is an array of arrays
    return myArrays;
  }
}

First of all, I have two examples: an array with less than eight elements, another with an array with more than eight elements (comment whichever one you do not want to use).
I then check for the size of the array, simple but essential to avoid extra computation. From here if the array meets the criteria (array size > delimiter) we move into the splitArray function.
The splitArray function takes in the delimiter (meaning 8, since that is what you want to split by), and the array itself. Since we are re-using the array length a lot, I am caching it in a variable, as well as the first and last.
first represents the position of the first element in an array. This array is an array made of 8 elements. So in order to determine the first element we use the modulus operator.
myArrays is the array of arrays. In it we will store at each index, any sub array of size 8 or below. This is the key strategy in the algorithm below.
index represents the index for the myArrays variable. Every time a sub array of 8 elements or less is to be stored, it needs to be stored in the corresponding index. So if we have 27 elements, that means 4 arrays. The first, second and third array will have 8 elements each. The last will have 3 elements only. So index will be 0, 1, 2, and 3 respectively.
The tricky part is simply figuring out the math and optimizing it as best as possible. For example else if (delimiter - (i % delimiter) === 1) this is to find the last element that should go in the array, when an array will be full (example: contain 10 elements).
This code works for every single scenario, you can even change the delimiter to match any array size you'd like to get. Pretty sweet right :-)
Any questions? Feel free to ask in the comments below.

A: I just wrote this with the help of a groupBy function.

// utils
const group = (source) => ({
  by: (grouping) => {
    const groups = source.reduce((accumulator, item) => {
      const name = JSON.stringify(grouping(item));
      accumulator[name] = accumulator[name] || [];
      accumulator[name].push(item);
      return accumulator;
    }, {});

    return Object.keys(groups).map(key => groups[key]);
  }
});

const chunk = (source, size) => group(source.map((item, index) => ({ item, index })))
.by(x => Math.floor(x.index / size))
.map(x => x.map(v => v.item));

// 103 items
const arr = [6,2,6,6,0,7,4,9,3,1,9,6,1,2,7,8,3,3,4,6,8,7,6,9,3,6,3,5,0,9,3,7,0,4,1,9,7,5,7,4,3,4,8,9,0,5,1,0,0,8,0,5,8,3,2,5,6,9,0,0,1,5,1,7,0,6,1,6,8,4,9,8,9,1,6,5,4,9,1,6,6,1,8,3,5,5,7,0,8,3,1,7,1,1,7,6,4,9,7,0,5,1,0];

const chunks = chunk(arr, 10);

console.log(JSON.stringify(chunks));

A: Hi try this -
 function split(arr, howMany) {
        var newArr = []; start = 0; end = howMany;
        for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
            newArr.push(arr.slice(start, end));
            start = start + howMany;
            end = end + howMany
        }
        console.log(newArr)
    }
    split([1,2,3,4,55,6,7,8,8,9],3)

A: Here's a version with tail recursion and array destructuring.
Far from the fastest performance, but I'm just amused that js can do this now. Even if it isn't optimized for it :(
const getChunks = (arr, chunk_size, acc = []) => {
    if (arr.length === 0) { return acc }
    const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
    return getChunks(tl, chunk_size, acc.concat([hd]))
}

// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]

A: There could be many solution to this problem.
one of my fav is:

function chunk(array, size) {
    const chunked = [];

    for (element of array){
        let last = chunked[chunked.length - 1];

        if(last && last.length != size){
            last.push(element)
        }else{
            chunked.push([element])
        }
    }

    return chunked;
}

function chunk1(array, size) {
    const chunked = [];

    let index = 0;

    while(index < array.length){
        chunked.push(array.slice(index,index+ size))
        index += size;
    }
    return chunked;
}

console.log('chunk without slice:',chunk([1,2,3,4,5,5],2));
console.log('chunk with use of slice funtion',chunk1([1,2,3,4,5,6],2))

A: In case this is useful to anyone, this can be done very simply in RxJS 6:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
from(arr).pipe(bufferCount(3)).subscribe(chunk => console.log(chunk));

Outputs: [1, 2, 3] [4, 5, 6] [7, 8, 9] [10, 11, 12] [13, 14, 15] [16]

A: Late, here's my two cents. Like many said, I first would think of something like
chunker = (a,n) => [...Array(Math.ceil(a.length/n))].map((v,i) => a.slice(i*n, (i+1)*n))

But what I like better and haven't seen here is this:
chunker = (n) => (r,v,i) => (c = Math.floor(i/n), (r[c] = r[c] || []).push(v), r)

console.log(arr.reduce(chunker(3), []))

with longer variant
chunker = (a, n) => a.reduce((r,v,i) => {
  c = Math.floor(i/n); // which chunk it belongs to
  (r[c] = r[c] || []).push(v)
  return r
}, [])

console.log(chunker(arr, 3))

Explanations

*

*The common answer will first determine the number of chunks and then get slices of the original array based on what chunk is at and the size of each chunks

*The chunker reducer function will go through each element and put it in the according evaluated chunk's array.
The performance is almost the same, the reduce method being 4% slower on average for what I could see.
PS: reduce(ing) has the advantage of easily change grouping criteria. In the question and examples the criteria is adjacent cells (and mapping uses slice for that). But you could want to do it in "cycles" for example, using mod (% operator), or any other math formulas
Re-reading it made me see that the formula could be a parameter too, leading to a more general solution and requiring 2 functions to achieve the answer:
splitter = (a, f) => a.reduce((r,v,i) => { // math formula and/or function
  c = f(v, i) || 0; // custom formula, receiving each value and index
  (r[c] = r[c] || []).push(v)
  return r
}, [])

chunker = (a, n) => splitter(a, (v,i) => Math.floor(i/n))

console.log(chunker(arr, 3))
console.log(splitter(arr, (v,i) => v % 2))  // is it even or odd?

With little changes splitter could also be used for making named-arrays aka objects, with function returning strings instead of numbers :)

A: An efficient solution is to join solution with slice and push by indexChunk, the solution split into chunks:

function splitChunks(sourceArray, chunkSize) {
  if(chunkSize <= 0)
    throw "chunkSize must be greater than 0";
  let result = [];
  for (var i = 0; i < sourceArray.length; i += chunkSize) {
    result[i / chunkSize] = sourceArray.slice(i, i + chunkSize);
  }
  return result;
}

let ar1 = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
];

console.log("Split in chunks with 4 size", splitChunks(ar1, 4));
console.log("Split in chunks with 7 size", splitChunks(ar1, 7));

A: # in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays

newAr = []
chunk = 10
for i in [0... ar.length] by chunk
   newAr.push ar[i... i+chunk]

# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
   console.log ar[i... i+chunk].join ' '

A: I changed BlazeMonger's slightly to use for a jQuery object..
var $list = $('li'),
    $listRows = [];

for (var i = 0, len = $list.length, chunk = 4, n = 0; i < len; i += chunk, n++) {
   $listRows[n] = $list.slice(i, i + chunk);
}

A: Here's a solution using ImmutableJS, where items is an Immutable List and size is the required grouping size.
const partition = ((items, size) => {
  return items.groupBy((items, i) => Math.floor(i/size))
})

A: Her is a simple solution using @Blazemonger solution
function array_chunk(arr, size){
    // initialize vars
    var i,
    j = arr.length,
    tempArray = [];
    // loop through and jump based on size
    for (i=0; i<j; i+=size) {
        // slice chunk of arr and push to tempArray
        tempArray.push(arr.slice(i,i+size));
    }
    // return temp array (chunck)
    return tempArray
}

This got the pipline flowing for me, hope this helps someone else out there. :)

A: Here's another solution with the reduce() method, though slightly different from other examples. Hopefully my explanation is a bit clearer as well.

var arr = [0, 1, 2, 3, 4, 5, 6, 7];
var chunkSize = 3;

arr = arr.reduce((acc, item, idx) => {
  let group = acc.pop();
  if (group.length == chunkSize) {
    acc.push(group);
    group = [];
  }
  group.push(item);
  acc.push(group);
  return acc;
}, [[]]);

console.log(arr); //Prints [[0, 1, 2], [3, 4, 5], [6, 7]]

Explanation
We call a reducer which, for each item in the array, gets the last item of the accumulator with pop(). Remember that this item is an array which groups up to chunkSize number of items (3 in this example).
If, and only if, this group has the array length equal to chunksize we need to re-insert the group back into the accumulator and create a new group.
We then push the current item into our group array (which may already contain 0, 1 or 2 items from the previous steps). With the current item inserted into the group, we need to re-insert the group back into the larger collection.
The process will repeat until we've iterated through all items in arr.
Note that we have also provided the reducer with the starting value of an empty array inside an array with [[]].

A: Try this :

var oldArray =  ["Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango"];

var newArray = [];

while(oldArray.length){
    let start = 0;
    let end = 10;
    newArray.push(oldArray.slice(start, end));
    oldArray.splice(start, end);
 }

 console.log(newArray);

A: I prefer to use the splice method instead of slice.
This solution uses the array length and chunk size to create a loop count and then loops over the array which gets smaller after every operation due to splicing in each step.
    function chunk(array, size) {
      let resultArray = [];
      let chunkSize = array.length/size;
      for(i=0; i<chunkSize; i++) {
        resultArray.push(array.splice(0, size));
      }
    return console.log(resultArray);
    }
    chunk([1,2,3,4,5,6,7,8], 2);

If you dont want to mutate the original array, you can clone the original array using the spread operator and then use that array to solve the problem.
    let clonedArray = [...OriginalArray]

A: my trick is to use parseInt(i/chunkSize) and parseInt(i%chunkSize) and then filling the array

// filling items
let array = [];
for(let i = 0; i< 543; i++)
  array.push(i);

 // printing the splitted array
 console.log(getSplittedArray(array, 50));

 // get the splitted array
 function getSplittedArray(array, chunkSize){
  let chunkedArray = [];
  for(let i = 0; i<array.length; i++){
    try{
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];
    }catch(e){
      chunkedArray[parseInt(i/chunkSize)] = [];
      chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i];
    }
  }
  return chunkedArray;
 }

A: I solved it like this:
const chunks = [];
const chunkSize = 10;
for (let i = 0; i < arrayToSplit.length; i += chunkSize) {
  const tempArray = arrayToSplit.slice(i, i + chunkSize);
  chunks.push(tempArray);
}

A: Super late to the party but I solved a similar problem with the approach of using .join("") to convert the array to one giant string, then using regex to .match(/.{1,7}/) it into arrays of substrings of max length 7.
const arr = ['abc', 'def', 'gh', 'ijkl', 'm', 'nopq', 'rs', 'tuvwx', 'yz'];
const arrayOfSevens = arr.join("").match(/.{1,7}/g);
// ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]

Would be interesting to see how this performs in a speed test against other methods

A: TypeScript version. Demonstrated is 101 random uid's split into groups of 10
const idArrayLengthLimit = 10;
const randomOneHundredOneIdArray = Array
    .from(Array(101).keys())
    .map(() => generateUid(5));

function generateUid(length: number) {
  const uidString: string[] = [];
  const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    uidString
      .push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
  }
  return uidString.join('');
}

for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
 if(i % idArrayLengthLimit === 0){
     const result = randomOneHundredOneIdArray
       .filter((_,id) => id >= i && id < i + idArrayLengthLimit);
    // Observe result
    console.log(result);
 }
}

A: Here's a more specific case that someone might find valuable. I haven't seen it mentioned here yet.
What if you don't want constant/even chunk sizes, and instead want to specify the indices where the array is split. In that case, you can use this:
const splitArray = (array = [], splits = []) => {
  array = [...array]; // make shallow copy to avoid mutating original
  const chunks = []; // collect chunks
  for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
  chunks.push(array); // add last remaining chunk (at beginning of array)
  return chunks.reverse(); // restore chunk order
};

Then:
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6])
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]

Note that this will do funny things if you give it non-ascending/duplicate/negative/non-integer/etc split indices. You could add checks for these edge cases (e.g. Array.from(new Set(array)) to de-duplicate.

A: My favorite is the generator generateChunks with the additional function getChunks to execute the generator.
function* generateChunks(array, size) {
    let start = 0;
    while (start < array.length) {
        yield array.slice(start, start + size);
        start += size;
    }
}

function getChunks(array, size) {
    return [...generateChunks(array, size)];
}

console.log(getChunks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9 ] ]

As an addition here the generator generatePartitions with the further function getPartitions to get n arrays of equal size.
function generatePartitions(array, count) {
    return generateChunks(array, Math.ceil(array.length / count));
}

function getPartitions(array, count) {
    return [...generatePartitions(array, count)];
}

console.log(getPartitions([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9 ] ]

An advantage of the generator compared to many other solutions is that not multiple unnecessary arrays are created.

A: In JS,
const splitInChunks = (arr,n) => {
  let chunksArr = [];
  if(arr !=null && arr!= undefined){
      for(i=0; i<arr.length;i+=n){
      if(arr.length-i>=n)
          chunksArr.push(arr.slice(i,i+n))
      else
           chunksArr.push(arr.slice(i,arr.length))
  }
  return chunksArr
  }
}

A: The problem with the current top answers is that they produce lopsided chunks. For example, the currently accepted answer will distribute a 101-element array into 10 chunks of size 10, followed by 1 chunk of size 1.
Using some modular arithmetic can create uniform chunk sizes that never differ by more than 1:

function split_array(a, nparts) {
  const quot = Math.floor(a.length / nparts)
  const rem = a.length % nparts
  var parts = []
  for (var i = 0; i < nparts; ++i) {
    const begin = i * quot + Math.min(rem, i)
    const end = begin + quot + (i < rem)
    parts.push(a.slice(begin, end))
  }
  return parts
}

var chunks = split_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
console.log(JSON.stringify(chunks))

Output:
[[1,2,3,4],[5,6,7],[8,9,10]]

(Copied from a related answer.)

A: Well, a nice function for this would be:
function chunk(arr,times){
    if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
   var tempArray = Array() //Array to be populated with chunks
    for(i=0;i<arr.length/times;i++){
     tempArray[i] = Array() //Sub-Arrays        //Repeats for each chunk
   for(j=0;j<times;j++){
        if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub-  Arrays with chunks
    }
     else{
       j = times //Stop loop
       i = arr.length/times //Stop loop
  }
    }
     }
   return tempArray //Return the populated and chunked array
   }

Usage would be:
chunk(array,sizeOfChunks)

I commented it so you could understand what was going on.
(The formatting is a bit off, I programmed this on mobile)

A: Neat and clean easy to understand
 let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 let len = nums.length ;

    const chunkArr = (arr, chunkNo) => {
      let newArr = [];
      for(let i = 0; i < len; i++){
        if(nums[0] !== "" && nums[0] !== undefined ){
          let a = nums.splice(0,chunkNo) ;
          newArr.push(a);
        }
      }
       return newArr ;
    }
    console.log(chunkArr(nums, 5));


text:
Q: What is statistical meaning of testing of machine learning model on new data? Any machine learning model, normally, is applied on new data for testing. If the accuracy of the model is below a certain threshold, the model is rejected. But why? This is just a random sample, the result may not represent the performance of the model on the whole population. What is the statistical meaning of this operation?

A: Ah - fresh to statistics. If you have a test set of data from say $10.000.000$ customers, their postal addresses, their annual purchase in your webshop and a few other variables - then the randomness of such a large sample is neglectable. If, on the other hand, you have $50$ customers in your test set, then the randomness so much more is present.
The confidence intervals of your model predictions become narrower with more test data. These test data must come from the same underlying distribution as the training data used to build your model. Otherwise, the test set will be biased in relation to your training set.
The minimal threshold for an acceptable model accuracy, that depends on the application domain.

A: I think, the reasoning is like this. If training set and/or test set has distribution randomly different from the distribution of general population, then, most likely, distributions on training and test data will be different from each other. In this case, the performance of the model on the test data will be poor. If the performance of the model on the test data is good, it signals that distributions of training and tests set are similar (as far as the model is concerned). And this, in turn, would imply that they both are close to the distribution on the general population, and the test results can be used to predict performance on the general population.
I doubt somebody proved it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Describe the real elements of a Cyclotomic Extension under an Embedding Set-up: Let $\mathbb{Q}(\zeta)$ be an extension of $\mathbb{Q}$ where $\zeta$ is the 5-th root of $1$ and define $\psi:\mathbb{Q}(\zeta)\to\mathbb{C}$, $\zeta^{x}\mapsto1/\zeta^{x}$.
Aim: I need to describe the subfield of real elements in $\psi(\mathbb{Q}(\zeta))$ (which I'll label $R$), show that it is a simple extension, and then find the generator.
My Attempt:
So far I have that $\mathbb{Q}(\zeta)/\mathbb{Q}$ is Galois and $\text{Gal}(\mathbb{Q}(\zeta)/\mathbb{Q})=\mathbb{Z}/4\mathbb{Z}$. I also have that $\psi$ is an injective mapping.
As far as I can work out, $R$ is everything in $\mathbb{Q}(\zeta)$ which is mapped to the real line under $\psi$. But isn't it that only $\zeta^{5y}=1$ are mapped to the real line? Clearly, this makes no real sense for the question so I'm guessing not.
To show it is a simple extension I just need to show that it has only one generator - how do I do that?

A: You know from Galois theory that there if you call $K$ your cyclotomic extension it is true that $[K: K \cap \mathbb{R}]=[K\mathbb{R}:\mathbb{R}]=2$ so that your real subextension has degree $2$ over the rational.(This is a general trick to be sure of the degree of your real subextension). Note also that $\mathbb{Q}(\zeta+\zeta^{-1})$ is a real subextension of $K$ and that it has degree $2$ over $\mathbb{Q}$. To prove the its degree it's actually $2$ there are lots of ways. Maybe try to prove this.


text:
Q: How can I get the pixel of the covered window? I am using Visual Studio 2008 on Windows XP and studying C++.
I am curious about the getting pixel from desktop.
Can I get the screen pixel with GetPixel function in the case that the window is covered with another window?  In the status of my window being covered, I was trying to call the GetPixel:
GetPixel(hdc, x, y);

But this call dosen't retrieve the pixel of the original window but the covering window or other color one.
How can I get the pixel of the covered window?
I add my code as the following ...
VOID GetDisplay(HWND& hwnd, RECT& area, COLORREF (*display)[1000]) {
    HDC hdc=GetDC(hwnd);
    for(INT x=area.left;x<=area.right;x++) {
        for(int y=area.top;y<=area.bottom;y++) {
            display[x][y]=GetPixel(hdc, x, y);
        }
    }
    ReleaseDC(hwnd, hdc);
}

...

SetWindowPos(hwnd, HWND_TOPMOST, 300, 300, 500, 350, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
SetForegroundWindow(hwnd);
SetActiveWindow(hwnd);
//EnableWindow(hwnd, TRUE);
SetFocus(hwnd);

GetDisplay(hwnd, within_wall, display);//trouble

The problem is causing on the GetPixel in GetDisplay.  GetPixel is returning the pixel color of the covering window.

A: There's no 100% way to do it, as windows are not required to, and generally don't, draw obscured areas. You will not be able to make the desktop a foreground window of course. And focus has no effect on visibility, as someone has mentioned SetFocus. That would be ineffective.
I have seen proposals to use WM_PRINT to access obscured pixels. Again this is not guaranteed, but the desktop window is pretty specific so if you get that to work, I guess it'll be somewhat reliable.
For more on this, see: PrintWindow.
For what it's worth, GetPixel is extremely slow. You'll probably notice a performance problem in your code. You'll get much better performance by using methods like GetDIBits.


text:
Q: Update the field by form id in jquery I have multiple forms with same name but unique form id for each form. Each form has same elements with same name and id.
Now how can I tell jquery to update the field on when there is some action on the same form ?
       $('select[name="locationName"]').change(
            function() {
                $('select[name="flavorDefs"]').prop("disabled", true);
                $.getJSON('flavorDefinitions.wss', {
                    location : $(this).val(),
                    ajax : 'true'
                }, function(data) {
                    $('select[name="flavorDefs"]').prop("disabled", false);
                    var html = '';
                    var len = data.length;
                    for ( var i = 0; i < len; i++) {
                    html += '<option value="' + data[i].id+ '" id="'+data[i].id+'">'
                                + data[i].cpus+' CPU '+data[i].ram+' MB RAM '+data[i].disk+' GB DISK '+ '</option>';
                    }

                    $('select[name="flavorDefs"]').html(html);
                });
            });
});
</script>

And the form will be like
    <form action="provisionserver.wss" name="submitForm" method="POST" id= "formid193.0">
        <select name="locationName" id="locationId"/>
    <select name="flavorDefs" id="flavorDefs"/>
</form>

        <form action="provisionserver.wss" name="submitForm" method="POST" id= "formid194.0">
        <select name="locationName" id="locationId"/>
    <select name="flavorDefs" id="flavorDefs"/>
</form>

A: Try this code:
   $('select[name="locationName"]').change(
        function() {
            var flavorDefs = $(this).parents('form:first').find('select[name="flavorDefs"]');
            flavorDefs.prop("disabled", true);
            $.getJSON('flavorDefinitions.wss', {
                location : $(this).val(),
                ajax : 'true'
            }, function(data) {
                flavorDefs.prop("disabled", false);
                var html = '';
                var len = data.length;
                for ( var i = 0; i < len; i++) {
                html += '<option value="' + data[i].id+ '" id="'+data[i].id+'">'
                            + data[i].cpus+' CPU '+data[i].ram+' MB RAM '+data[i].disk+' GB DISK '+ '</option>';
                }

                flavorDefs.html(html);
            });
        });
    });

You need to get the form parent, and then, find the select with the name you want.


text:
Q: Is "rewirings" a word? Is "rewirings" a word? I recently found myself at need for its use and every location I search says it's spelled incorrectly / doesn't exist, yet I'm fairly certain this would be the correct word to express multiples rewires.

A: I'm thinking that you haven't asked quite the right question here, but I'm trying to figure out a better way to ask it.  The bottom line is that of course it's a word, and to my mind also the right word to use here.
As for something or someone telling you it wasn't, I have to ask:

*

*Did an actual human being tell you it's not a word, and was this person a lexicographer or linguist?
Unless the answer to both those questions is yes, then you have no reason to believe them.
You're simply applying basic rules of morphology and derivation here, and any human being who knows the business would vet this application in an instant.
It's just sub-clued programmers of little learning who don't know how to write a reasonable computer algorithm writing prescriptively uninspired programs that screws people up.  Don't trust a computer to have had a professionally educated human behind its algorithm, and therefore do not trust it.


text:
Q: He has come to see if I was/were ok - indicative or subjunctive? I know that the subjunctive is used in formal English in some imaginary situations, such as conditions, wishes (after "to wish", but strangely not after "to hope"), assumptions (eg after "to suppose"), suggestions, statements of necessity, etc. Examples:

*

*If I were rich, ...

*I wish the computer were working.

*Suppose that I were there now.

*I suggest that he implement a budget cut in March.

*It is essential that she be present.

Does this apply to a condition related to a verb? Which one of the following sentences is correct?

*

*He has come to see if I was ok. (indicative mood)

*He has come to see if I were ok.  (subjunctive mood)


text:
Q: Is it okay to have only one significant variable as a result of a logistic regression? I am running a logistic regression where the dependent variable is the adaptation decision. With that I am considering 5 independent and continuous variables such as

*

*age

*income

*educational attainment (expressed in years)

*farm size

*farming experience,

and another 4 independent dummy variables, namely:

*

*tenurial status

*access to credit

*access to info

*access to extension services.

A: There is no arbitrary number of variables that "should" or need to be significant for a logistic regression model (or indeed any model) to be correct or valid. Significance is a function of your data, and if there are no associations in your data, that is your result.
My Masters degree involved a model with no significant variables at the end of the day.


text:
Q: Is it necessary to house or enclose magnetic hard drives when they are running? I'm building a DIY NAS, and I'm looking for a solution to physically arrange the hard drives together. I've seen products like this, and I'm wondering if they are actually suitable for long term operation.

I know you're not supposed to run a magnetic hard drive just placed on a desk, or something, because the motion generated by the rotations might be problematic if it's directly absorbed back into the drive. Another thing a traditional case provides is shielding from dust from the environment; but I think hard drives are fairly shielded anyway.

A: Let's start with the question:

Is it necessary to house or enclose magnetic hard drives when they are running?

No, it is not neccesary.  The drives will work as long as they as provided with power and with a data connection to the disk controller.

I'm building a DIY NAS, and I'm looking for a solution to physically arrange hard drives together. I've seen products like this, and I'm wondering if they are actually suitable for long term operation.
I know you're not suppose to run a magnetic hard drive just placed on a desk or something because the motion generated by the rotations might be problematic if it's directly absorbed back into the drive. Another thing a traditional case provides is shielding from dust from the environment; but I think hard drives are fairly shielded anyway.

According to this wikipedia article, high temperatures were not well correlated with disk failures in a large sampling.  In addition, dust is common in almost all applications since, if the inlets are filtered, they are rarely done so with a filter that will filter fine particles.
So, I would say pick whatever enclosure (in no particular order):

*

*Looks good (we like our custom builds to look nice)

*Is easy to get the drives in and out of.

*Provides a clean way to wire the drives.

*Fits with your other components.


text:
Q: How do I remove flickering line when using css tranform:scale? I've been trying to remove this ugly flicker when hovering over the images. I've tried adding -webkit-backface-visibility: hidden; to the hover element along with the :hover itself but can't seem to shake it. Seems the promblem is only on Chrome and Safari.
website: http://best-law-firm-sites.com/lawpromo12/

.col-sm-4 {
    width: 33.3333%;
    float: left;
}
.panel-wrap {
    height: 100% !important;
}
.panel-wrap .col-sm-4 {
    padding: 0;
}
.hovereffect {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
    cursor: default;
}
.hovereffect .overlay {
    width: 100%;
    height: 100%;
    position: absolute;
    overflow: hidden;
    top: 0;
    left: 0;
    -webkit-transition: all 0.4s ease-in-out;
    -moz-transition: all 0.4s ease-in-out;
    -o-transition: all 0.4s ease-in-out;
    transition: all 0.4s ease-in-out;
}
.hovereffect h2,
.hovereffect img {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}
.hovereffect img {
    display: block;
    position: relative;
    -webkit-transform:  scale(1.001);
    -ms-transform:  scale(1.001);
    -moz-transform:  scale(1.001);
    -o-transform:  scale(1.001);
    transform:  scale(1.001);
}
.hovereffect:hover img {
    -webkit-transform: scale(1.17);
    -ms-transform: scale(1.17);
    -moz-transform: scale(1.17);
    -o-transform: scale(1.17);
    transform: scale(1.17);
}
.hovereffect h2 {
    bottom: 10%;
    color: #fff;
    font-size: 30px;
    font-weight: 700;
    padding: 10px 10px 10px 17px;
    position: absolute;
    text-align: left;
    text-shadow: 2px 3px 6px rgba(0, 0, 0, 1);
    text-transform: uppercase;
}
.hovereffect h2::after {
    display: block;
    content: "";
    height: 4px;
    width: 75px;
    background: #BCA474;
    margin: 20px 0 0;
    box-shadow: 2px 3px 6px rgba(0, 0, 0, 0.6);
}
.hovereffect a.info {
    display: inline-block;
    text-decoration: none;
    padding: 7px 14px;
    text-transform: uppercase;
    color: #fff;
    margin: 50px 0 0 0;
    background-color: transparent;
    -webkit-transform: scale(1.5);
    -ms-transform: scale(1.5);
    transform: scale(1.5);
    -webkit-transition: all 0.4s ease-in-out;
    transition: all 0.4s ease-in-out;
    font-weight: normal;
    height: 100%;
    width: 85%;
    position: absolute;
    top: 0;
    left: 0;
    padding: 70px;
}
.hovereffect:hover a.info {
    -webkit-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
}

Family Law

Estate Planning

Wills & Trusts

A: I have encountered similarly strange behavior in the past when using the backface visibility hack to trick the browser into using the 3d pipeline. There are other ways to 'trick' the browser into using the 3d pipeline like:
.class{
    transform: translate3d(0,0,1);
}

A: You can resolve this problem by increasing the transform scale property to 1.001:
.hovereffect img{transform: scale(1.001);}


text:
Q: Fastest way to update an attribute in all products I'm trying to update the price to a lot of products (more than 10.000). The way I am doing that right now is extremely time-consuming. Which is the best way to loop through all the products and update most of them?
Thanks

A: 10k products, use SQL. EAV just muddies the waters. Per question is Fastest way.
Find attribute_id
SELECT * FROM eav_attribute where entity_type_id = 4 and attribute_code = 'YOUR_ATTRIBUTE_CODE_HERE'

Update with found attribute_id from above query.
UPDATE catalog_product_entity_int SET value = 1 WHERE attribute_id = FOUND_ATTRIBUTE_ID

I suppose you could do a subselect with update but for simplicities sake two SQL queries is easiest to grasp.
NOTE: entity_type_id = 4 is most always the product EAV entries. In case you are needing to mass update category or customer attributes this will differ as well as the table that is updated based on what type of attribute it is your updating. Also if you have multi-store setup be sure and note and condition store_id

A: Further to Fabian's answer above, you can update multiple fields at a time. The example below has just 2 (in stock, stock status), but you can use as many as you want.
    $product_ids = Mage::getModel('catalog/product')
        ->getCollection()
        ->addAttributeToFilter('status', array('eq' => 2)) //only disabled
        ->getAllIds();

    $attrData = [
        ['attribute_one' => 1],
        ['attribute_two' => 1]
    ];

    $storeId = 0;
    Mage::getSingleton('catalog/resource_product_action')
       ->updateAttributes($product_ids, $attrData, $storeId);

A: Hi Magento  provide an attribute by below code
$product->setAttributeCode($newValue)
$ProductObject->getResource()->saveAttribute($product, 'attribute_Code');

Example:
$product=Mage::getModel('catalog/product')->load($id);
$product->setSpecialFromDate('2010-10-28');
// below code use for time format
$product->setSpecialFromDateIsFormated(true);
$product->getResource()->saveAttribute($product, 'special_from_date');

Using Product Collection:
$productIds = array(1,3,2);
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productIds));

foreach($products as $product)
{
    $product->setSpecialFromDate('2010-10-28');
    // below code use for time format
    $product->setSpecialFromDateIsFormated(true);
    $product->getResource()->saveAttribute($product, 'special_from_date');

}

A: Write an SQL Query.
Second best way (and the one I recommend): \Mage_Catalog_Model_Resource_Product_Action::updateAttributes
Code example by u_maxx:
$allProductIds = Mage::getModel('catalog/product')->getCollection()->getAllIds();
$attributeCode = 'some_eav_attribute';
$attributeValue = NULL;
$attrData = array( $attributeCode => $attributeValue );
$storeId = 0;
// no reindex:<
Mage::getSingleton('catalog/resource_product_action')->updateAttributes($allProductIds, $attrData, $storeId);
// reindex:
Mage::getModel('catalog/product_action')->updateAttributes($allProductIds, $attrData, $storeId);

How would this work with multiselect values? Does it 'add' the value or overwrite other pre-selected values

Multiselects are normally saved as comma seperated integers, like 27,42,4711. Therefore if you change the value to say 1, the other values are lost. But what you can do is something like CONCAT(value, ',1') means adding the new value to the end, seperated by a comma. I think even if you add a value two times, this is no problem, because Magento filters it the next time the item is saved and ignores the second value.


text:
Q: Having an issue with deleting items in to do list project I'm having an issue with the delete function. I'm at the point where I can remove only one line before pushing the submit button again. It seems that I can remove only the first paragraph that was submitted. It feels like eventListener applies only for the first line. Do I need a loop here?
Here is some of my code:

// Manipulation with DOM

const submitButton = document.getElementById('submit-btn');
const inputText = document.getElementById('input-text');
const showcaseUlList = document.getElementById('showcase-ul-list');
const showcaseLilist = document.getElementById('showcase-li-list');

// Submit event listener

submitButton.addEventListener('click', submitAddToDo);

// Submit function

function submitAddToDo(){
    // Checking if the input is not empty
    if(inputText.value === ''){
        alert("You've must fill the input field");
        return;
    }

    // Create div
    const divToDo = document.createElement('div');
    divToDo.classList.add('showcase-li-list');

    // Create li
    const liToDo = document.createElement('li');

    // Create button(check)
    const checkToDo = document.createElement('button');
    checkToDo.innerHTML = '';

    // Create paragraph
    const pToDo = document.createElement('p');
    let inputValue = inputText.value;
    pToDo.innerHTML = inputValue;

    // Create i(trash)
    const trashToDo = document.createElement('button');
    trashToDo.classList.add('trash');
    trashToDo.innerHTML = ''

    // All childs appends
    showcaseUlList.appendChild(divToDo);
    divToDo.appendChild(liToDo);
    liToDo.appendChild(checkToDo);
    liToDo.appendChild(pToDo);
    liToDo.appendChild(trashToDo);

    // Clear input field and delete show line
    inputText.value = '';
    showcaseLilist.remove();

    // Remove task
    const trashDelete = document.getElementById('trash-delete');
    trashDelete.addEventListener('click', removeTask);
    const removeParent = trashDelete.parentElement.parentElement.parentElement;
    function removeTask(){
        removeParent.remove();
    }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />

Welcome,

Here you can make your own task manager

feel free to try it out!

Fill your task manager with tasks:

            <input type="text" id="input-text" class="input-text">
            <button class="btn-lg" id="submit-btn">Submit</button>

                        <button></button>

Fill your task manager

                        <button class="trash"></button>

A: Use trashToDo.addEventListener instead of trashDelete.addEventListener. Also you do not need to get removeParent. Use divToDo.remove(); inside removeTask.
Issue with your code is due to document.getElementById('trash-delete'). getElementById will always find first element with id trash-delete. And you are assigning event to that first element only. So it always deletes first one for you.
// Remove task
// const trashDelete = document.getElementById('trash-delete'); <-- Remove this line
trashToDo.addEventListener('click', removeTask);
// Remove below line.
// const removeParent = trashDelete.parentElement.parentElement.parentElement;
function removeTask() {
    divToDo.remove();
}


text:
Q: html5 и использование onplaying Передо мной стоит следующая задача.
Понять, воспроизводится ли видео html5 в данный момент
Что есть:
//находим с помощью XPATH наше видео
let xpath_video = document.evaluate('//div[@id="player"]//video', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
//На паузе?
let isPaused = xpath_video.singleNodeValue.paused;

Но есть ещё такая ситуация, когда видео просто не подгружается, поэтому я хотел бы использовать onplaying, но xpath_video.singleNodeValue.onplaying; отдаёт null.
Как вырулить в данной ситуации?


text:
Q: Edit Item in Angular 4 Can anyone help me in my editing function. I am confused on how to make this work. I've done my best on my codes below but i can't get it. I already loaded the items in the input but i can't update a new one. I mean i don't know how to override the items that is selected

user-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../user.model';
import { UserService } from '../user.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

    user: User;
    id: number;

  constructor(private userService: UserService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
      this.route.params
      .subscribe(
        (params: Params) => {
          this.id = +params['id'];
          this.user = this.userService.getUser(this.id);
          }
        )
  }

  onEditDetail(){
    this.router.navigate(['/user/user-list/edit', this.id]);
  }

}

user.edit.component.ts

import { Component, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { User } from '../user.model';
import { UserService } from '../user.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.css']
})
export class UserEditComponent implements OnInit {
  @ViewChild('f') editForm: NgForm;
  user: User;
  id: number;
  editedItem: User;

  constructor(private userService: UserService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
      this.route.params
      .subscribe(
        (params: Params) => {
          this.id = +params['id'];
          this.user = this.userService.getUser(this.id);
        }
      )
  }

  onUpdateDetails(){
      this.editForm.setValue({
          f_name: this.editedItem.f_name,
          l_name: this.editedItem.l_name,
          contact_no: this.editedItem.contact_no
      })
  }

}

user.edit.component.html

EDIT USER

          <form>

              First Name
              <input type="text" class="form-control" value="{{user.f_name}}">

              Last Name
              <input type="text" class="form-control" value="{{user.l_name}}">

              Contact Number
              <input type="number" class="form-control" value="{{user.contact_no}}">

             UPDATE
          </form>

user.service.ts

import { User } from './user.model';
import { Subject } from 'rxjs/Subject';
export class UserService {

usersChanged = new Subject<User[]>();

  private users: User[]= [
    new User('Harry', 'James', 99999889),
    new User('Thomas', 'Baker', 99638798)
  ];

  getUsers() {
    return this.users.slice();
  }

  getUser(index: number) {
    return this.users[index];
  }

  addUser(user: User){
    this.users.push(user);
    this.usersChanged.next(this.users.slice());
  }

  deleteUser(index: number){
    this.users.splice(index, 1);
    this.usersChanged.next(this.users.slice());
  }

}

A: you can use Reactive Forms to handeling forms:
import { FormGroup, FormBuilder } from '@angular/forms';

export class UserEditComponent implements OnInit {
  editForm: FormGroup;

  constructor(formBuilder: FormBuilder, ...) {
      // Building Form
      this.editForm = formBuilder.group({
          'f_name': [''],
          ...
      })

  }

    onUpdateDetails(){

      // Updating form value
      this.editForm.patchValue({
          'f_name': this.editedItem.f_name,
          ...
      });
      this.editForm.updateValueAndValidity();
    }

.
 // Using reactive form in template
<form [formGroup]="editForm">

      First Name
      <input type="text" formControlName="f_name" class="form-control" />

 ...


text:
Q: Uncaught TypeError accordion is not a function in jQuery? I have try to active accordion to top smooth scroll but shown error is accordion is not function. I have already add jquery min (version:3.3.1) file.
<script>

$(function() {
        $("#accordionEx").accordion({
            autoHeight: false,
            collapsible: true,
            heightStyle: "content",
            active: 0,
            animate: 300
        });
        $('#accordionEx h2').bind('click',function(){
            var self = this;
            setTimeout(function() {
                theOffset = $(self).offset();
                $('body,html').animate({ scrollTop: theOffset.top - 100 });
            }, 310);
        });
 });

</script>

A: Please add exactly after the jquery library
// After your jquery library
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

This will help you.
For more details about accordion, refer to this link: accordion


text:
Q: Comment on the Methodology of Primary Research investigating "The Effect of Hardware Variances on the Performance of the Merge Sort Algorithm" I am a highschool student and am conducting primary research on "To what extent do variances in the performance of CPU, RAM, and storage affect the performance of the merge sort algorithm when it is run on large data sets?"
Methodology
The research question will be investigated by running the merge sort algorithm on various hardware components (CPU, RAM, and primary drive) and evaluating which hardware component is the most effective at increasing the efficiency of the algorithm. The performance of hardware components is going to be changed by underclocking and overclocking the CPU and RAM, whilst storing the program running the algorithm on SSD vs. HDD and recording the time it takes for the algorithm to sort 500 randomly generated integers in an array. A small data set was used in comparison to the Big Data used by major companies, to avoid taxing the limited available resources by constantly reaching the limits of the hardware through bottlenecks or by causing a burnout. To truly understand the efficacy of the merge sort algorthim on a big data set, the size of the data set should ideally be around billion data elements, but that would require superior CPU, RAM, storage, and cooling solutions to protect the hardware and keep up with processing large amounts of data.
To reiterate the merge sort algorithm is very popular in large corporations to easily locate items in large lists and thus it is likely that in reality the merge sort algorithm has been modified to be more efficient and to better handle billions of data elements.
Before conducting this experiment, it is important to control various extraneous variables which could skew the accuracy of the results presented in this essay. Firstly, it is important that the operating system on which the algorithm is run is the same during all trials so that the way the OS allocates and prioritizes memory is the same during all tests. Additionally, all the hardware components such as the CPU, RAM, graphics, motherboard, and the cooling solution must be the same for all tests to avoid any manufacturing differences in protocols or specifications such as the available cache, latency, number of cores, or multithreading performance. All of these differences can directly improve or deteriorate the performance of the merge sort algorithm and thus lead to distortions in the results. Lastly, no other programs must be open during the testing process to avoid other programs to use memory or processing power that was intended for sorting purposes.
Here is the algorithm I am going to be running:
import java.util.Random;
public class Merge_Sort {

    private int[] arr;

    public void main() {
        double startTime = System.nanoTime();
        createArray();
        mergeSort(0, arr.length - 1);
        double endTime = System.nanoTime();
        double totalTime = endTime - startTime;
        System.out.println("Total Time to run the algo: " +
                totalTime / 1000000000);
    }

    public void createArray() {
        arr = new int[500];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = randomFill();
        }
    }

    public int randomFill() {
        Random rand = new Random();
        int randomNum = rand.nextInt();
        return randomNum;
    }

    public void merge(int l, int m, int r) {
        int i, j, k;
        int n1 = m - l + 1;
        int n2 = r - m;

        /* create temp arrays */
        int[] L = new int[n1];
        int[] R = new int[n2];

        /* Copy data to temp arrays L[] and R[] */
        for (i = 0; i < n1; i++) {
            L[i] = arr[l + i];
        }
        for (j = 0; j < n2; j++) {
            R[j] = arr[m + 1 + j];
        }
        /* Merge the temp arrays back into arr[l..r]*/
        i = 0; // Initial index of first subarray
        j = 0; // Initial index of second subarray
        k = l; // Initial index of merged subarray
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            } else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

      /* Copy the remaining elements of L[], if there
      are any */
        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

      /* Copy the remaining elements of R[], if there
      are any */
        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    /* l is for left index and r is right index of the
    sub-array of arr to be sorted */
    public void mergeSort(int l, int r) {
        if (l < r) {
            // large l and h
            int m = (l + r) / 2;
            // Sort first and second halves
            mergeSort(l, m);
            mergeSort(m + 1, r);

            merge(l, m, r);
        }
    }

    public void printArray(int A[]) {
        int i;
        for (i = 0; i < A.length; i++) {
            System.out.println(A[i]);
        }
        System.out.println("\n");
    }
}

Any comments on the methodology would be greatly appreciated, specifically whether my reasoning of using a small data set(500) is accurate or not.
Thanks a lot!

A: *

*To benchmark Java code, you should use a proper benchmarking framework like JMH. JMH makes sure to warm up the JVM and to run your code enough times to get consistent results. Without it, you might be simply measuring the performance of JVM startup and compilation, not the sorting. This means that you'll be measuring something completely different from what you meant to measure - the results will be just noise, no signal.

*500 integers is a ridiculously low number. If every integer is 4 bytes long, that's only 2000 bytes of data. This means a few things:

*

*The entire "dataset" will be sorted in a very short time - we're talking microseconds here. This will be very difficult to measure accurately. On the whole, general purpose operating systems aren't great for accuracies below 10-20ms, which is probably x100 - x1000 the time it'll take to sort 500 ints. So you'll need to sort those numbers a whole bunch of times (say 1000), see how long that takes, and then divide by 1000 to see how long a single run took. This brings us to the next problem:

*The entire "dataset" will probably fit into a single memory page. Moreover, it'll fit into the CPU cache in its entirety. Heck, it can all fit into L1, the smallest (and fastest) of the CPU caches. This means that during sorting, everything will be done within the CPU, so no memory accesses, no disk access. The size and clock speed of RAM will therefore impact only the initial loading of the 500 integers, and even then, the impact will be negligible. And since you'll need to run the test thousands of times for a single benchmark, you won't even see any loading times in your result, since the data will only be loaded once for all those runs.
In other words using 500 ins, is like comparing different types of engine oil by measuring the speed of a car over a distance of one meter (3.3 feet, if you're from that side of the ocean).
For any meaningful result, you need to vastly increase the amount of data you're sorting, and of course use JMH. I'd also use different data sizes and throw in some additional sorting algorithms to compare against. It would be interesting to show how the size of the input and the different hardware choices affect the results.


text:
Q: Open sets are $\mu*$-measurable in a metric space with a given condition I have a homework problem that I'm very stuck on.  The problem statement is as follows:
"Suppose that $X$ is a metric space, and that for any sets $E,F \subseteq X$, if dist$(E,F) > 0$ then $\mu^*(E \cup F) = \mu^*(E) + \mu^*(F)$.  Prove that every open set is a splitting set.  (Recall that the distance between subsets $E$ and $F$ of a metric space is defined to be dist$(E,F) = \inf \{ d(x,y) : x \in E, y \in F \}$.)"
Our professor defines a "splitting set" as follows: Let $\mu^*$ be an outer measure on a nonempty set $X$.  A set $A \subseteq X$ is called a splitting set if, for all $E \subseteq X$, $\mu^*(E) = \mu^*(E \cap A) + \mu^*(E \cap A^c)$, where $A^c = X \backslash A$.  (This is what Folland's Real Analysis calls a $\mu^*$-measurable set.)
Here are a couple of my (failed) attempts:
My first try was to let $U$ be an arbitrary open set in $X$, let $G \subseteq X$ be arbitrary, and define $E = G \cap U$, $F = G \cap U^c$.  If I could somehow show that dist$(E,F) > 0$ in this case, then the result would follow, but in general, this is not true (take $\mathbb{R}$ with the standard metric, let $G = [0,1]$, $U = (-1/2,1/2)$).
My next attempt was by contradiction: suppose there is an open set $U$ such that $U$ is not a splitting set.  Then there is some $E \subseteq X$ such that $\mu^*(E) \neq \mu^*(E \cap U) + \mu^*(E \cap U^c)$...  and by monotonicity this means that $\mu^*(E) < \mu^*(E \cap U) + \mu^*(E \cap U^c)$.  But then I only have one set to work with, and with the assumptions, I need two sets $E,F$ to work with in order to get anywhere.
I also tried exploring what I could do with closed sets, since if dist$(E,F) > 0$,  then the closures of $E$ and $F$ respectively are disjoint.  But I'm still stuck.  Any hints would be appreciated!!!  Thanks in advance.

A: Felt like I should come back and add the correct answer.  Let $U$ be an open set in $X$ and consider $U^c$.  For each $n$, let $U_n = \{ x \in U : d(x,y) > 1/n \; \forall y \in U^c \}$.  Then $\mu^*(E \cap (U_n \cup U^c)) = \mu^*(E \cap U_n) + \mu^*(E \cap U^c)$.  Then taking the limit of both sides, continuity from below of the outer measure gives the result.

A: Here's a strategy for making your second attempt work: since $E = (E\cap U) \cup (E \cap U^c)$, you can conclude that $d(E\cap U, E \cap U^c)=0$. Now you should be able to shrink $U$ just a little, yielding $U'$ so that $d(E \cap U', E \cap U^c)>0$ but still $\mu^{*}(E)<\mu^{*}(E\cap U')+ \mu^{*}(E\cap U^c)$.


text:
Q: Parsing config to IOptions fails in Azure I'm using the IOptions pattern to parse my config file into a strongly typed class.
I'm doing this in ConfigureServices:
services.AddOptions();
services.Configure<StorageSettings>(Configuration.GetSection("StorageSettings"));

The StorageSettings class looks like this:
public class StorageSettings
{
    public ConnectionStrings ConnectionStrings { get; set; }
}

public class ConnectionStrings
{
    public TableStorageConnectionStrings TableStorage { get; set; }

    public EventHubConnectionStrings EventHubs { get; set; }

    public ServiceBusConnectionStrings ServiceBus { get; set; }
}

public class TableStorageConnectionStrings
{
    public string LogEntriesByAccount { get; set; }
}

public class EventHubConnectionStrings
{
    public string EventHubName { get; set; }

    public string IngestionQueue { get; set; }

    public string AccessKeyName { get; set; }

    public string AccessKeyToken { get; set; }

    public string ServiceNameSpace { get; set; }
}

public class ServiceBusConnectionStrings
{
    public string GlobalQueue { get; set; }
}

And my JSON configuration file looks like this:
{
    "SecuritySettings": {
        "SystemToken": "123"
    },
    "StorageSettings": {
        "ConnectionStrings": {
            "TableStorage": {
                "LogEntriesByAccount": "DefaultEndpointsProtocol=https;AccountName=account;AccountKey=key=="
            },
            "EventHubs": {
                "EventHubName": "myhub",
                "AccessKeyName": "key",
                "AccessKeyToken": "token",
                "ServiceNameSpace": "ns",
                "IngestionQueue": ""
            },
            "ServiceBus": {
                "GlobalQueue": "DISABLED"
            }
        }
    },
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Warning",
            "Microsoft": "Warning"
        }
    }
}

It works when running locally, and the config sections and properties are parsed just fine. But when running i Azure I get this error:
[13:54:40 INF] Starting up API in Production
Application startup exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Failed to convert '@{LogEntriesByAccount=DefaultEndpointsProtocol=https;AccountName=mystore001;AccountKey=KEY====000}' to type 'MyApp.Storage.Configuration.TableStorageConnectionStrings'. ---> System.NotSupportedException: TypeConverter cannot convert from System.String.
   at System.ComponentModel.TypeConverter.GetConvertFromException(Object value)
   at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.ConvertValue(Type type, String value)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Configuration.ConfigurationBinder.ConvertValue(Type type, String value)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindProperty(PropertyInfo property, Object instance, IConfiguration config)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindNonScalar(IConfiguration configuration, Object instance)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindProperty(PropertyInfo property, Object instance, IConfiguration config)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindNonScalar(IConfiguration configuration, Object instance)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration configuration, Object instance)
   at Microsoft.Extensions.Options.ConfigureFromConfigurationOptions`1.<>c__DisplayClass0_0.<.ctor>b__0(TOptions options)
   at Microsoft.Extensions.Options.ConfigureOptions`1.Configure(TOptions options)
   at Microsoft.Extensions.Options.OptionsCache`1.CreateOptions()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at System.Threading.LazyInitializer.EnsureInitialized[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
   at Microsoft.Extensions.Options.OptionsCache`1.get_Value()
   at Microsoft.Extensions.Options.OptionsManager`1.get_Value()
   at MyApp.Storage.Azure.EventHubAMQPIngestionQueue..ctor(IOptions`1 options, ILoggerFactory loggerFactory) in C:\Workspace\Dev\MyApp\src\MyApp.Storage\Azure\EventHubAMQPIngestionQueue.cs:line 29
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at MyApp.API.Startup.ConfigureServices(IServiceCollection services) in C:\Workspace\Dev\MyApp\src\MyApp.API\Startup.cs:line 124
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection exportServices)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.<>c__DisplayClass4_0.<Build>b__0(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:23758
Application started. Press Ctrl+C to shut down.

A: I decided to create a test project to see if I could re-produce the issue in a small and more isolated project. I could not.
It turns out that my Azure App Service (Web App) instance that I'd used for a long time were the culprit - in desperation I deployed the project that failed in Azure to a new App Service instance and it started working.
I tried to delete a lot of folders using Kudu but it didn't work.
I also compared all Application Settings and verified they were the same.
I ended up deleting the App Service instance I was using in favor of a newly created one.
The test project I used is this one: https://github.com/martinnormark/ConfigOptionsTest


text:
Q: Custom divider - counter row number in Result Set I have an important issue. I will explain my scenario.
I'm building an stored procedure that receives a parameter called '@rowcountdivider' and it's INTEGER.
My Result Set has data like this:
iStore  |  vCode  | iQty
----------------------------
9       |  00001  |   1
9       |  00001  |   1
9       |  00001  |   1
9       |  00001  |   1
9       |  00001  |   1
9       |  00002  |   1
9       |  00003  |   1
9       |  00003  |   1
9       |  00003  |   1

Now, i need 'sum-count' this rows with my input parameter (EXAMPLE: @rowcountdivider = 4). Something like this:
iStore  |  vCode  | iQty  |  MasterCounter
-------------------------------------------
9       |  00001  |   1   |    1
9       |  00001  |   1   |    1
9       |  00001  |   1   |    1
9       |  00001  |   1   |    1 -- Their row number sum '@rowcountdivider' value (4) and MasterCounter increments in 1
9       |  00001  |   1   |    2
9       |  00002  |   1   |    2
9       |  00003  |   1   |    2
9       |  00003  |   1   |    2 -- Their row number sum the '@rowcountdivider' value (4) and MasterCounter increments in 1
9       |  00003  |   1   |    3 -- Their row number don't sum '@rowcountdivider' value (4) but i need assign them a value.

Also, the table would have N registers and '@rowcountdivider' would be any integer to 'divide' the rows just like in the example.
Any ideas?

A: I think this is what you are looking for? You're almost there with the comment about 'dividing the rows' you just need to add a row number and integer divide it by your @rowcountdivider (with a slight adjustment to account for the starting index)
SELECT * INTO #Demo FROM (VALUES
 (9,'00001',1),
 (9,'00001',1),
 (9,'00001',1),
 (9,'00001',1),
 (9,'00001',1),
 (9,'00002',1),
 (9,'00003',1),
 (9,'00003',1),
 (9,'00003',1)
 ) A (iStore,vCode,iQty);

DECLARE @rowcountdivider INT = 4;
SELECT
    iStore
    ,vCode
    ,iQty
    ,((ROW_NUMBER() OVER (ORDER BY vCode) - 1) / @rowcountdivider) + 1 MasterCounter
FROM #Demo;

iStore      vCode iQty        MasterCounter
----------- ----- ----------- --------------------
9           00001 1           1
9           00001 1           1
9           00001 1           1
9           00001 1           1
9           00001 1           2
9           00002 1           2
9           00003 1           2
9           00003 1           2
9           00003 1           3


text:
Q: Check if entry is available in database I have generated a 10 digit number, added it to a database after purchase.
Now I want to make a php page to give users an input box, ask them to enter the 10 digit number, and click submit. After you click submit it should return if the pin is used or has not been used it. (Used if its not available - Not used if its in the table)
I got the following code:
<?php
require_once 'db.php';
function validated_pin($pin)
{

    $pin = mysql_real_escape_string($pin);  // SECURITY!
    $result = mysql_query("SELECT pins FROM pins WHERE pin='$pin' LIMIT 1");
    if (mysql_fetch_row($result)) {
    return 'This pin has already been used';
    } else {
    return 'This pin is available for use';
}
}

echo '
<form action="' . $_SERVER['SCRIPT_NAME'] . '" method="post">

PIN*:	<input type="text" name="pin" value="" class="bginput"/>

	<input type="submit" id ="submit" name="submit1" value="Check Pin>>" class="button">

';
                echo validated_pin($pin);
echo '';
?>

And PHPmyAdmin looks like this:
http://gyazo.com/67c3df7171c83c677cb221c04d644ed7.png
It's located in _donation and in table name pins
I don't know whats going on tried looking everywhere
The current code will return this error
Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home/website/public_html/directory/example.php on line 8

A: Your query is-
  $result = mysql_query("SELECT pins FROM pins WHERE pin='$pin' LIMIT 1");

shouldn't it be
  $result = mysql_query("SELECT pin FROM pins WHERE pin='$pin' LIMIT 1");

pin is the column name right? not pins
 if (mysql_fetch_row($result)) {

   if(mysql_num_rows($result)>0)
    return 'This pin has already been used';
    else
    return 'This pin is available for use';

}

A: Your query is failing to fetch data, resulting in false returned.
Firstly - you should catch this false value and not assume $result has data.
Secondly - var_dump() the query you are running, run that in PhpMyAdmin

A: This seemed to have solved it:
$pin = $_POST["pin"];

function validated_pin($pin)
{

    $pin = mysql_real_escape_string($pin);  // SECURITY!
    $result = mysql_query("SELECT pin FROM pins WHERE pin='$pin' LIMIT 1");

    if(mysql_num_rows($result) == 0) {
        return 'This pin has already been used';
            } else {
        return 'This pin is available for use';
             }
}

Still facing the issue of it saying "Already been used" before I execute any code.


text:
Q: for loop logic several values within an array - Javascript and JQuery Having a problem. The below works great at populating a jquery datatable. The arrays dataX are short strings of arrays (each one like 7 elements). Seemed like a good way to do the table! and worked okay at the time.
My problem is I want to check the 4th element within each of the dataX arrays and if it's "fail" then precede the text with "Test". I've tried this a number of times but seem to have not succeeded. Is there an eloquent way of doing this check? Will I have to separate the for loop into two as it uses the index variable in two ways? I've tried using two variables instead of index twice, and feel i'm making headway, but can't sort the logic mentally.
 for (var index = 0; index < 7; index++) {
    //if (index != 4) {
        $(row1cells[index + 1]).html(data1[index]);
        $(row2cells[index + 1]).html(data2[index]);
        $(row3cells[index + 1]).html(data3[index]);
        $(row4cells[index + 1]).html(data4[index]);
        $(row5cells[index + 1]).html(data5[index]);
        $(row6cells[index + 1]).html(data6[index]);
        $(row7cells[index + 1]).html(data7[index]);
    }

 })

A: I'm not sure I understood but try that:
var format = function(index, data) {
        var value = data[index];

        if (index === 4 && value === 'fail') {
            return 'Test' + value;
        }

        return value;
    }
;

for (var index = 0; index < 7; index++) {
    $(row1cells[index + 1]).html(format(index, data1));
    $(row2cells[index + 1]).html(format(index, data2));
    $(row3cells[index + 1]).html(format(index, data3));
    $(row4cells[index + 1]).html(format(index, data4));
    $(row5cells[index + 1]).html(format(index, data5));
    $(row6cells[index + 1]).html(format(index, data6));
    $(row7cells[index + 1]).html(format(index, data7));
}


text:
Q: using require() in karma tests I'm using Karma 0.12.28, Karma-Requirejs 0.2.2 (and Karam-jasmine) to run tests.
Config is almost identical to one from docs (test files in requirejs deps and window.__ karma __.start as callback).
Everything works just fine for basic tests. The problem starts when I use require() instead of define() or try to change context. Basically something like this:
var ctx = require.config({
  context: 'my-context'
});
ctx(['dep1'], function(){
  //....
});

The problem is dep1 fails to load. In DevTools I can see <script/> is created and I can see request in network tab with proper URL but status is canceled. I can open this URL using context menu so I'm sure it is correct but the question remains - why can't I use require() in karma tests?