Regarding

Bubble sort: visualization

  <button onclick=CreateBarPlot()>Generate data</button>
  <button onclick=bubble_sort()>Sort</button>

It's not a good idea to use inline event handlers in modern Javascript, because they require global pollution and can have some very strange behavior. Leave the HTML markup to be the actual content of the site - keep the styling and Javascript to their own self-contained sections instead, preferably. To attach event listeners to an element, use addEventListener.

In the Javascript, you have some places where you assign to different .style properties of an element. Consider adding CSS rules instead. Here, the bars are children of the #bar_plot, so all you need is the #bar_plot > div selector - you don't even need to add a class to the elements. Of course, when the property you want is dynamically calculated in the JS, like div.style.width = (value * 10) + 'px', you need to use JS, but otherwise, better to use CSS rules.

You use div.innerHTML = value;. Unless you're deliberately inserting HTML markup, it's faster, safer, and more predictable if you use the textContent property instead, if you want to put text inside an element. (Even if you're already sure value is plain text, and doesn't contain HTML markup, other readers of the code may not be as sure as you on casual inspection, which may cause worries and double-checks) Same thing for when retrieving element content - unless you need to retrieve HTML markup, use textContent.

You declare a bar element with:

const div = document.createElement("div");

const is ES2015 syntax. ES2015 syntax is great - it often makes code more readable and concise. I'd highly recommend using it everywhere. If you need compatibility with completely obsolete browsers (like IE), the professional thing to do is to use Babel to transpile your clean ES2015+ code into ES5 syntax.

But whatever you decide, make sure to have a consistent style. If you really want to write in ES5 for some reason, then best to do so everywhere - otherwise, use ES2015+. (Don't mix var and const / let).

Either way, also make sure to declare your variables before using them - your numbers variable (and bar1_value, and bar1_width, and more) are not declared, which means that when you assign to it, you're implicitly creating a global variable. Or, if you use strict mode (which you should, it turns potential bugs like these into early errors), an error will be thrown.

Elements with IDs automatically become global variables with the name of the ID. This is weird and can cause bugs and confusion. I'd prefer to avoid IDs when possible, or at least minimize their usage to only absolutely unique elements. Dynamic numeric-indexed IDs definitely should be avoided (especially since they aren't being referenced anywhere else anyway).

The overwhelming majority of professional Javascript uses camelCase for nearly all variable names (including functions). PascalCase is generally reserved for classes and constructor functions, which you aren't using here. You can consider whether you want to conform to the de-facto standard.

You're sometimes putting semicolons at the end of statements, and sometimes you aren't. Omitting semicolons can occasionally result in bugs, especially if you're a beginner - even if you know the rules of ASI, it's best to be consistent with a code style. Consider using a linter like ESLint to automatically prompt you to fix these sorts of inconsistencies and potential bugs.

BARS_DATA is a confusing name. It's declared as an array, and it sounds like it holds data, which I would intuitively think would be the numeric data points, but it actually holds elements. Maybe call it barElements instead. Or, even better, you can avoid the global array there entirely by selecting the rows from the DOM when needed instead.

With bubble sort, after a full initial iteration through the array, the value at the last index will be completely sorted (the final value there). After the second full iteration, the second-last value will be completely sorted, and so on. You can improve your logic by iterating one less element each time, and perhaps make the logic clearer by giving these completely-sorted elements a style change.

Rather than bubbleSort recursively calling itself with index and changed arguments, I think the logic might be clearer if it only ran once instead, and added delays by awaiting a Promise that resolves after a couple seconds.

It's possible to click the sort button more than once, resulting in multiple sorts occurring simultaneously, which doesn't make sense. Perhaps disable the buttons while sorting.

Put it all together, and you get something like:

'use strict';

// you could also put the whole script into an IIFE to avoid globals

function generateNumbers(count = 15) {
  const numbers = [];
  for (let i = 0; i < count; i++) {
    numbers.push(Math.floor(Math.random() * (70 - 1)) + 1);
  }
  return numbers;
}

function createBar(index, value) {
  const div = document.createElement("div");
  div.textContent = value;
  div.style.width = (value * 10) + 'px';
  return div;
}

function createBarPlot() {
  const existingPlot = document.querySelector('.bar-plot');
  if (existingPlot) {
    existingPlot.remove();
  }
  const barPlot = document.body.appendChild(document.createElement("p"));
  barPlot.className = 'bar-plot';
  const numbers = generateNumbers();
  for (let i = 0; i < numbers.length; i++) {
    barPlot.appendChild(createBar(i, numbers[i]));
  }
}

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function bubbleSort() {
  const barElements = [...document.querySelectorAll('.bar-plot > div')];

  // Some helper functions first:
  const getNum = i => Number(barElements[i].textContent);
  const switchBars = (i) => {
    barElements[i].insertAdjacentElement('afterend', barElements[i - 1]);
    // Swap the positions of the bars in the array of elements:
    [barElements[i], barElements[i - 1]] = [barElements[i - 1], barElements[i]];
  };

  for (let cyclesToGo = barElements.length - 1; cyclesToGo >= 0; cyclesToGo--) {
    // Add active class to first element:
    barElements[0].classList.add('active');
    for (let i = 1; i <= cyclesToGo; i++) {
      // Add active class to next element:
      barElements[i].classList.add('active');
      if (getNum(i - 1) > getNum(i)) {
        switchBars(i);
      }
      await delay(50);
      // Remove active class from last element:
      barElements[i - 1].classList.remove('active');
    }
    // Cycle complete; last one iterated over is in its final position
    barElements[cyclesToGo].className = 'done';
  }
  generateBtn.disabled = false;
}

const buttons = document.querySelectorAll('button');
const [generateBtn, sortBtn] = buttons;
const setDisabled = newDisabled => {
  for (const button of buttons) {
    button.disabled = newDisabled;
  }
};
generateBtn.addEventListener('click', () => {
  setDisabled(false);
  createBarPlot();
});
sortBtn.addEventListener('click', () => {
  setDisabled(true);
  bubbleSort();
});
body {
  background: pink;
}
.bar-plot > div {
  color: black;
  text-align: right;
  background: lightblue;
  padding: 2.5px;
  margin: 1px;
}
.bar-plot > div.active {
  background: red;
}
.bar-plot > div.done {
  background: yellow;
}

Bubble sort: visualization

<button>Generate data</button>
<button>Sort</button>


In addition to what @dfhwze has said, I wanted to give some suggestions on general ruby best practice and readibility:

Multiline Blocks

In PriceCalculator#start_billing, PriceCalculator#count_items and in a couple other methods you use muliline blocks like so:

foobar.each { |*args|
  # do stuff
  # more stuff
}

The use of {} is really only intended for single line blocks -- when you have more than one line inside of the block, it's best to use do ... end. This will make your code a bit easier to read. From my example:

foobar.each do |*args|
  # do stuff
  # more stuff
end

Method Definitions

In ruby, while it's valid syntax to define methods like def some_method argument, it's really easy to misread that as def some_method_argument, and so it's considered better practice to put parentheses around your method definitions, like so: def some_method(argument).

Other

I just wanted to take a look at this method:

def calculate_bill quantity
  price = {}
  quantity.each { |item,value|
    if SaleItems.all[item].nil?
      price[item] = quantity[item]*Items.all[item]
    else
      price[item] = (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])
    end
    }
    price
end

Specifically, in the if statement, you could take advantage of a common ruby idiom for generating hashes, and instead of generating a price hash just return the hash you want:

def calculate_bill quantity
  quantity.map { |item,value| [item, SalesItems.all[item].nil? ? quantity[item]*Items.all[item] : (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])] }.to_h
end

(note how I used the {} for a one line block). If you wanted to expand this to make it a bit more readable:

def calculate_bill quantity
  quantity.map do |item,value|
    v = if SalesItems.all[item].nil?
      quantity[item]*Items.all[item]
    else
      (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])
    end
    [item, v]
  end.to_h
end

I'd also recommend breaking up that massive formula into some smaller pieces with better variable names to make it easier to tweak it later if you need to.


Function to insert a tag into a database

Use a transaction, so you won't need all the manual delete queries
Use shorter PDO syntax.
Log errors
Use prepared statements

In the end it should be like

public function insertTag(Tag\Tag $tag)
{
    try{
        //Names
        $name = new Common\Name();

        $pdo->beginTransaction();

        //Insert into main table
        $this->connection->query("INSERT INTO tag VALUES(null)");

        //Get main table id
        $tagId = $this->connection->lastInsertId();

        //Insert into audit tag table
        $sql = "INSERT INTO tag_audit(behaviour,action_peformed,state,tag_id) VALUES(?,'insert','P',?)";
        $this->connection->prepare($sql)->execute([$tag->getBehaviour(), $tagId]);

        //Insert into names
        // you should be using prepared statements here
        $sql = "INSERT INTO tag_name_audit(name,language,action_peformed,state,tag) VALUES (?,?,?,?,?)";
        $statement = $this->connection->prepare($sql);
        foreach (whatever function supplies the name as $name) {
            $statement->execute([$name]);
        }
        $response = ['status'=>200,'Message'=>'Successfully inserted.'];

        $pdo->commit();
    }catch(\Exception $e){

         $pdo->rollback();
         error_log($e);
         $response = ['status'=>409,'Message'=>'Error '.$e->getCode()];
    }
    $tag->setResponse($response);
}


I've refactored your code below to add some of the repetitive items into functions and tried to improve your variable names a little.
The new variable names and function names should clearly indicate their intended purpose/data.
A rule of thumb worth remembering is the concept of DRY (Do not Repeat Yourself).

const createArraywithJsonData = function(count, data) {
    let array = [];

    for (let i = count; i < data.length; i += count) {
        array.push(data.slice(i, i + count));
    }

    return array;
}

const editTableId = function(selector, counter) {
    $(`#d-page-${(counter+1)}`).find(`#${selector}-0`, "table").prop("id", `${selector}-${(counter+1)}`);
}

const appendDataToTable = function(array, property, selector) {
    for (let x = 0; x < array.length; x++) {
        let k = array[x];

        for (let y = 0; y < k.length; y++) {
            $(`#${selector}-${x}`).append(`<tr><td>${array[x][y][property]}</td></tr>`);
        }
    }
}

let d1 = [
    {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }, {
        a: "1"
    }
];
let d2 = [
    {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }, {
        b: "2"
    }
];

let ar1 = createArraywithJsonData(7, d1);
let ar2 = createArraywithJsonData(21, d2);
let longestArrayLength = ar1.length > ar2.length ? ar1.length : ar2.length;

for (let v = 0; v < longestArrayLength - 1; v++) { //clone div using longest array length
    $("#d-page-0").clone().prop("id", `d-page-${(v + 1)}`).insertAfter(`#d-page-${v}`); //clone div, edit id
    editTableId('e-tbl', v);
    editTableId('w-tbl', v);
}

appendDataToTable(ar1, 'a', 'e-tbl');
appendDataToTable(ar2, 'b', 'w-tbl');

<!DOCTYPE html>

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

tbl1

tbl2


The usual way I approach the problem is by asking: what does change?

self.atFront is flipped: not an issue here, you can simply write self.atFront = !self.atFront.
conditions using atFront vs. !atFront (not an issue: if we factorize everything, we don't need to know what the state is: we just want to change it)
the string in self.trigger
$front vs. $back
removeClass() vs. addClass().

Quite a lot of things change, actually! At this point, we don't know yet if avoiding duplication is worth it: it often leads to more complicated code and it can be longer, too. But let's try it. I took your code, created a flip function, and tried to see what could fit in it. When writing this, I realized that it was simpler to put everything in the flip function, so I tried it:

var TwistPanel = Backbone.View.extend({
  initialize: function() {
    this.$front = this.$el.find('.twist-panel-side-front');
    this.$back = this.$el.find('.twist-panel-side-back');

    this.atFront = true;
    this.isFlipping = false;

    // Fix the height of the twist panel container.
    this.$el.height(this.$front.outerHeight(true));
  },
  flip: function() {
    var self = this;
    var otherSide = ... ? this.$back : this.$front;

    if (this.isFlipping) return;

    this.$el.height(otherSide.outerHeight(true));

    this.$front.afterTransition(function() {
         self.isFlipping = false;
         self.trigger('twist', otherSide.name);
    });

    this.isFlipping = true;
    if (this.$el.hasClass('twist')) {
        this.$el.removeClass('twist')) {
    } else {
        this.$el.addClass('twist');
    }
  }
});

(I don't know about your application, but I guess toFront can never be called when we're already in front. If it's not true, then we need to keep toFront and toBack which will call flip themselves.)

At this point, I have two big issues left: I don't know how to decide what is the other side, and I don't know how to get its name (otherSide.name, used in the self.trigger() call). Since I don't know about this, I decided to resolve another issue, even if it is minor. This issue is that the removeClass/addClass logic looks wrong. It would probably be simpler to use something that is more than a value, and HTML5 data-* attributes are perfect for this since they are key-value and supported by jQuery. You can then replace the last five lines by this single one:

this.$el.data('twist', otherSide.name);

$el will either contain data-twist="front" or data-twist="back": you then need to change your CSS to account for this minor change. What's nice here is that it's now possible to get the string you're interested in (front or back). And it's also easy to assign otherSide. We'll use jQuery data() for this. Here's the final untested code:

var TwistPanel = Backbone.View.extend({
  initialize: function() {
    this.$front = this.$el.find('.twist-panel-side-front');
    this.$back = this.$el.find('.twist-panel-side-back');

    this.isFlipping = false;

    // Fix the height of the twist panel container.
    this.$el.height(this.$front.outerHeight(true));
  },
  flip: function() {
    var self = this;
    var otherSide = this.$el.data('twist') === 'front' ? this.$back : this.$front;
    var otherSideName = this.$el.data('twist') === 'front' ? 'back' : 'front';

    if (this.isFlipping) return;

    this.$el.height(otherSide.outerHeight(true));

    this.$front.afterTransition(function() {
         self.isFlipping = false;
         self.trigger('twist', this.$el.data('twist'));
    });

    this.isFlipping = true;
    this.$el.data('twist', otherSideName);
  }
});


I have one suggestion for your code.

Create a method to check if the current size is invalid, and reuse it (MinHeap#peek and MinHeap#poll methods).

private void assertCurrentSizeIsValid() {
   if (size == 0) {
      throw new IllegalStateException();
   }
}


Transforming XML as it is being generated on a scanner

I'd go with a <xsl:key ...> index, like so (at top level):

<xsl:key name="contains_RETURN" match="Barcode" use="contains(text(), 'RETURN')"/>

and then rewrite your hotspot to:

<xsl:when test="count(key('contains_RETURN', 'true')) > 0">
  ...
</xsl:when>

The idea is to partition Barcode nodes into two sets, the ones that contain 'RETURN' and the ones that don't.  The key function as shown then evaluates to a nodeset that only contains Barcode nodes that contain 'RETURN' and hence count works as expected.


Looks not too bad, it's readable enough.  The use of with is good (except for writeOutput, where it's not used for some reason) and the code is split into separate functions by functionality.  That said:

Stylistic

You should read and follow PEP8 (naming of globals, functions,
variables, whitespace, no need for semicolons).
You don't need those globals, just return values from your functions.
Maybe use docstrings instead of comments if you're describing the
functionality of a function.
Create more functions for common code.  If you copy and paste
something is wrong (usually).  That applies to all the reader functions, as they share the line splitting and accumulation code.
The try/except blocks in joinOrders aren't good.  Exceptions
aren't for control flow (usually) and you're better off using a
different approach for better understanding (where could the exception
be raised from) and maintainability (if you move the block or change
things, does the exception still only apply to the part you originally
wanted too, etc.)

Design

You might be better off using the csv module with custom separators
to read the files.  Even as a beginner it's a good idea to use
libraries to make your life easier.
The double splitting in the read functions looks unnecessary, but I'm
not quite sure.
Why the weird truncate?  It's normal for text files to end with a
newline.
Unless you're not concerned about speed the list concatenation in
joinOrders isn't the best idea.  Creating the set from custInfo,
then calling update on the set would be better to avoid unnecessary
allocations for the list.
Use iter* on dictionaries, lists, etc. for efficiency if you only iterate over the elements.  Here that would be iteritems instead of items.

Overall the split into input and output makes sense and I wouldn't worry too much about efficiency at this point (unless you're processing huge amounts of data that is).


Runge-Kutta 2nd order of differential equations

It is more usual to take a pointer to an already-allocated array, rather than allocate an array within the function itself.  This allows the calling function to choose the best kind of allocation.

When doing this you'd likely also take the number of indexes to fill as an input, deriving the step size from that:

/* resultsize must be >= 2 */
void runge_kutta_2nd_order(double results[], size_t resultsize, double a, double b, double (*x) (double), double upto)
{
    const double stepSize = upto / (resultsize - 1);
    double yt = b;
    size_t index;

    results[0] = b;

    for (index = 1; index < resultsize; index++)
    {
        const double time = index * stepSize;
        const double k1 = x(time) - a * yt;
        const double ystar1 = yt + stepSize * k1;
        const double k2 = x(time + stepSize) - a * ystar1;
        const double ystar2 = yt + (k1 + k2) / 2 * stepSize;
        yt = ystar2;
        results[index] = ystar2;
    }
}

So, for example, in this case you could use automatic allocation in main():

int main(void)
{
    int i;
    double res[1001];

    runge_kutta_2nd_order(res, 1001, -1, 0, &insignal, 10);

    printf("\nRunge Kutta 2nd order approximation of the differential equation:");
    printf("\ny'(t) - y(t) = e^(t/2) * (sin(5t) - 10cos(5t))");
    printf("\ny(0) = 0");
    printf("\n0 <= t <= 10");

    for(i=0; i<1001; i+=100){
        printf("\ni = %f => y = ", 0.01*i);
        printf("%f", res[i]);
    }
    printf("\n");

    return 0;
}


The right way to get formatted node's body field in Drupal 7

The API has the field_view_value() function which essentially does the same thing as your code, except it applies all of the field/instance settings to the value so you won't need to make changes to your code if you change a field setting.

You can use it like this:

$field = field_get_items('node', $node, 'body');

$body = '';
if (isset($field[0]['value'])) {
  $body = field_view_value('node', $node, 'body', $field[0]);
}

Just in case you want the default HTML wrappers included with the field output, you can use field_view_field() instead.


After a lot of digging, I have finally arrived at (what I think) a better solution.

Laravel had a feature in 5.0 called CommandBus with 5.1 they have changed the name & the class structure (slightly) to Jobs.

Jobs are Queuable or you can run them synchronously. The real benefit from using jobs are:

Loosely coupled to the controller
Easier testing
Re-usable

This was a really good feature for me & my project because an application can be submitted in multiple controllers.

After implementation my controller now looks like this:

public function postGuest(Requests\VoucherFormRequest $request)
{
    //return the newly created id
    $company_id     = $this->dispatchFrom('App\Jobs\CreateCompanyJob', $request);

    //set the application to outstanding
    $outstanding_id = $this->dispatch(new SetApplicationToOutstandingJob($company_id));

    //return the user_id this application needs mapping to.
    $userId         = $this->dispatch(new InsertApplicationAnswersJob($request->only('question'), $company_id));

    //finally map the application to the user chosen by our auto delegation.
    $this->dispatch(new MapOutstandingAppToUserJob($outstanding_id, $userId));

    return redirect(route('guest-published'));
}

This is the solution that I have found & seems to be a huge improvement on what I had. Most likely, there will be a better solution so feedbacks always welcome!

Handling Questions

Handling questions was done by putting them in a multidimensional array within my form.

{!! Form::text('question[6]', '', array('class' => 'app-create-input')) !!}

With this approach all I had to do was iterate through the array & handle each parameter within the loop.

foreach ($this->answers as $key => $value) {
    CompanyAnswers::create([
        'company_id'  => $this->company_id,
        'question_id' => $key,
        'answer'      => $value
    ]);
}

Normalisation

In regards to my normalisation, I cannot see any glaring issues. Even after further research. However I don't claim to be a DBA so I could very well be missing something.


I'm wondering if it is the efficiency that resulted in you getting half points:

runPartition is rather an unclear name in itself;
highIndex seems to be inclusive, which is uncommon (the number of elements is now highIndex - lowIndex + 1);
counterOne and counterTwo are not good names for indices - even i and j would have been better;
it is very likely that the localArray as a field name raises some questions; why is it a field in the first place? And why is it called local if it is not local to the method?
it seems to me that you would set the counterOne to the index you want to swap and perform the decrease afterwards (possibly using -- in the call to swapValues);
the braces are at uncommon and uneven positions when it comes to Java / indentation.


Insertion Sort Implementation Using For And While Loop

Thoughts on best practices

  Method signature should be void and should simply return the modified original array. Again, is this behavior better / more-expected? My argument against this is that maybe it could lead to some unexpected behavior if the user does not expected the original array to be modified? Or unexpected behavior down the road if the user forgets that the returned array has been modified. That being said, with proper documentation, this could be avoided.

This is a variant of the Single Responsibility Principle.  Your method is supposed to sort something.  Should it also copy something?  Or only sort?  Note that there is no way to sort in place with your version (except to copy back over the original array).  But with a sort-in-place version, you can easily duplicate your method's functionality:

int[] sorted = unsorted.clone();
InPlaceSorter.sort(sorted);

Now we have unsorted, which is the original array, and sorted, which is a new sorted version of the original array.

Documentation and the fact that saying

int[] sorted = InPlaceSorter.sort(unsorted);

will produce a compiler error should be enough to make clear that the array is being modified.

By contrast, calling

InsertionSorter.sort(unsorted);

without assigning the result will silently not do anything useful.  So I'd find your version riskier, as it doesn't warn when someone tries to do the wrong thing.

If you do stick to your original version, consider changing the name to make it clearer.  E.g. generateSortedCopyOf.  If I read that, I expect it to return a copy without modifying the original.  And I wouldn't try calling it to do a sort-in-place.

  One uses double for-loops vs. a for-loop and a while-loop. Is the double for-loop more readable?

Personally, I don't have a strong feeling about this one way or the other.  All for loops can be written as while loops and sometimes I find it more convenient.

      int j = i - 1;
      int numberToInsert = sorted[i];
      while (j >= 0 && numberToInsert < sorted[j]) {
        sorted[j + 1] = sorted[j];
        sorted[j] = numberToInsert;
        j--;
      }

But this does translate nicely to a for loop.

      int numberToInsert = sorted[i];
      for (int j = i - 1; j >= 0 && numberToInsert < sorted[j]; j--) {
        sorted[j + 1] = sorted[j];
        sorted[j] = numberToInsert;
      }

No gymnastics required to fit it into the for pattern.  I think that I'd vote for this solution as simpler in this case.  But see ahead.

Optimizations

This solution does more assignments than needed.  Consider

      int j = i - 1;
      int numberToInsert = sorted[i];
      for (; j >= 0 && numberToInsert < sorted[j]; j--) {
        sorted[j + 1] = sorted[j];
      }
      j++;

      sorted[j] = numberToInsert;

Now it's not nearly as obvious that this should be a for loop.

      int j = i - 1;
      int numberToInsert = sorted[i];
      while (j >= 0 && numberToInsert < sorted[j]) {
        sorted[j + 1] = sorted[j];
        j--;
      }
      j++;

      sorted[j] = numberToInsert;

Either way though, this could save you a bunch of assignments at the expense of always doing an assignment (we can check that i != j if we want to avoid that useless assignment).  But looking at this, we have another option:

      int j = i - 1;
      int numberToInsert = sorted[i];
      while (j >= 0 && numberToInsert < sorted[j]) {
        j--;
      }
      j++;

      if (j != i) {
        System.arraycopy(sorted, j, sorted, j + 1, i - j);
        sorted[j] = numberToInsert;
      }

Now we allow the Java compiler to do any optimizations that System.arraycopy allows.  At worst this should be the same as the original.

And we might do even better if we take advantage of the sorted portion of the array.

      int numberToInsert = sorted[i];
      int j = Math.abs(1 + Arrays.binarySearch(sorted, 0, i - 1, numberToInsert));

      if (j != i) {
        System.arraycopy(sorted, j, sorted, j + 1, i - j);
        sorted[j] = numberToInsert;
      }

Of course, one of the benefits of an insertion sort is its simplicity.  This replaces two things we originally did in a single loop with two system calls.  That may not be faster in some cases.  In particular, consider the case of an already sorted list.  The original algorithm runs in \$O(n)\$ time in that case, as the inner loop simply doesn't iterate.  This version would run in \$O(n \log n)\$ because binarySearch is a logarithmic operation.

Note:  adding one to the binarySearch result and taking the absolute value always gives the insertion point.  This is because a positive result is the current location of the element, and we want to insert after the current location in case of duplicates (technically we want to insert after the last duplicate, but I didn't add that logic); and a negative result is one less than the insertion point.

Another issue is that the original version might parallelize better.  One core can do comparisons while the other core writes values.  Or maybe the compiler optimizes binarySearch and arraycopy better.  You'd have to test to see, and you might get different results on different platforms.


Since this is labelled TypeScript, I'm going to review it as such. First of all, you aren't using types, which defeats the purpose of using TypeScript. You should define what your objects look like

interface Datum { //not sure what to call it
    continent: string,
    country: string,
    year: string,
    value: number
}

I'm not a TypeScript expert or anything, but even as a beginner, I'd expect something at least like this. With this, we get that the year is apparently a string. Maybe it's not an issue but it's something to note. Before defining the type I just glanced at the object and assumed it was a number.

Which means that your array declaration should now look like this

const array : Array<Datum> = [
  {continent: 'Africa', country:'Algeria', year:'2018', value:10},
  {continent: 'Africa', country:'Algeria', year:'2017', value:15},
  {continent: 'Africa', country:'Algeria', year:'2016', value:2},
  {continent: 'Africa', country:'Egypt', year:'2018', value:20},
  {continent: 'Africa', country:'Egypt', year:'2017', value:1},
  {continent: 'Africa', country:'Egypt', year:'2016', value:20},
]

and the compiler would know what you are working with providing type safety for future operations.

Now, let's take a look at some other declarations

const yearsTemp : Array<string> = Array.from(new Set(dataset.map((datum: Datum) => datum.year)).values())

Assuming dataset has a content similar to array in the beginning, the types we annotate are Datum for each variable. This means that we are mapping each year value and get an array of string. However, calling .values() on the Set is superfluous - Array.from() works fine with just being passed a Set. So, you can drop that.

But what about the next line

const years: Array<string> = yearsTemp.map(year => year.toString())

So, we take an array of strings and produce an array of strings. That's fine normally, but to do that you call .toString() on each value. That's a pointless operation "some value".toString() is the same thing. It's also dangerous, as null.toString() would cause an error. For future reference, a way that wouldn't throw a null pointer exception is to pass the value through the String constructor function but don't use the keyword new.

let numericValue = 42;

let stringValue = String(numericValue);

console.log("typeof stringValue", typeof stringValue);
console.log('stringValue === "42"', stringValue === "42");

//this creates a new object string, not a string primitive
let dontDoThis = new String(numericValue);

console.log("typeof dontDoThis", typeof dontDoThis);
console.log('dontDoThis === "42"', dontDoThis === "42"); //not the same type
console.log('dontDoThis === new String("42")', dontDoThis === new String("42")); //not the same object

Passing the value null or undefined through String will not cause an error but it will produce the string "null" or "undefined" respectively. You can filter those out, if you don't want them

let objectsWithNumericValues = [{year: 2018}, {year: 2019}, {year: 2019}, {year: 2020}, {year: null}];

let extractedYears = objectsWithNumericValues.map(obj => obj.year);
let resultWithNull = Array.from(new Set(extractedYears))
  .map(String); //<-- convert to string

let resultWithoutNull = Array.from(new Set(extractedYears))
  .filter(Boolean) //<-- filter anything falsey
  .map(String);

console.log(resultWithNull);
console.log(resultWithoutNull);

On a separate note, the above code shows how you can avoid temporary variables by chaining operations. It saves some typing and it's clearer by not having clutter like throw-away variable names. But it also depends on the coding style.

Anyway, back on the topic of getting the years and turning them into strings - just drop the line that does toString and rename const yearsTemp to const years

As for the rest it seems OK, as long as you add the types. It's not clear where the continent variable is coming from when you call filter(dataset, { continent: continent, year: year }) but I'd assume you have that in context. The other strange this is dataset[0].continent. I'm not sure if that's correct or not, as it would take the same continent for each new produced value and it's not necessarily going to be the correct one unless dataset[0].continent === continent. But that might be a typo when transcribing the code here. Perhaps the same is true for country: ''

The only change I'd make is separate the functionality instead of put all the processing into .map(). The chaining of array operation makes the separation of intentions clearer and if you need to extract functionality, it's cleaner.

years
    .map(year => filter(dataset, { continent: continent, year: year }))
    .map(filtered => {
        const mean = filtered.reduce((acc, item) => acc + item.value, 0) / filtered.length
        return {
            continent: dataset[0].continent,
            country: '',
            year: year,
            value: mean
        }
    })

this way if you decide that either or both functionalities are reusable, you can separate them and your logic turns into

years
    .map(getResultsWithTheSameYear)
    .map(calculateMean)

and you can use these functions elsewhere. Perhaps you will have some other functionality where you do

countries
    .map(getResultsWithSameCountry)
    .map(calculateMean)


For styling, variable naming etc. conventions, please take a look at PEP-8. Your globals should be UPPERCASED and function names should be snake_cased.

Since you are not at all interested in the rolled list, why store a thousand values in memory?

You should always seed when using a RNG function. For more information on why this practice is favoured, check this SO response.

Instead of using random.randrange, prefer using random.randint.

With those in place, you have:

import random
import operator

random.seed()

ROLLED = {i: 0 for i in range(1, 7)}
ITERATIONS = int(input('How many times would you like to roll the dice? '))

def probability():
    print("Calculation of probability: ")
    for key, count in ROLLED.items():
        print("\t{}: {:.2f}".format(key, count*100./ITERATIONS*1.))

for _ in range(ITERATIONS):
    ROLLED[random.randint(1, 6)] += 1

probability()

To find the most rolled, and least rolled face of the die, you can use a custom operator on ROLLED dictionary:

max(ROLLED.iteritems(), key=operator.itemgetter(1))
min(ROLLED.iteritems(), key=operator.itemgetter(1))


It doesn't really matter.

  My question is: what is better, store end date time as April 1 or March 31?

This is completely up to you based on what you want:

How do you prefer to check your date bounds?

Inclusive? if(myDate <= myFiscalYear.GetFiscalYearEnd())
Exclusive? if(myDate < myFiscalYear.GetFiscalYearEnd())

Is this end date shown to the user? Which date do they prefer seeing?

On a technical level, it doesn't matter which you pick. All that matters is that you handle the value consistently. If you start mixing < and <= checks, you're going to run into problems and bugs regardless of whether you define your date inclusive or exclusive.

Taking it a bit further.

However, as I pointed out, the inconsistent use of < and <= is going to be a possible cause for bugs down the line. Your developers might mistakenly use one instead of the other.

The issue here is that external code will handle the comparison. However, if you wrap this in a class of your own, you can ensure that the evaluation only occurs in one place, which dramatically lowers the chance of developer error.

A simple example class:

public class FiscalYear
{
    private int fiscalYear;

    public DateTime Start => new DateTime(fiscalYear, 4, 1);
    public DateTime End   => new DateTime(fiscalYear+1, 4, 1).AddTicks(-1);

    public FiscalYear(int year)
    {
        this.fiscalYear = year;
    }

    public bool Contains(DateTime date)
    {
        return date >= this.Start && date <= this.End;
    }
}

  Note
  There are other possible variations on this. You could calculate the dates in the constructor, or you could calculate the end date based on the start date. How you define the values is completely up to you.

  Edit remark:
  It's still possible for developers to implement their own evalutation based on the Start/End properties, but that is then considered developer error, they should rely on the logic that already exists instead of reinventing the wheel.
  What you could also do is set Start and End to private. This way, you prevent external code from doing their own evaluation, they can only do new FiscalYear(2018).Contains(myDate), but then you do lose out on using FiscalYear as an easy way for your external callers to find out what the start and end date of a fiscal year are. That's up to you to decide.

External code can then rely on the existing Contains() method; which means that the developers of the external code no longer need to know whether they should use < or <=.


The comparator should work fine, however return Integer.compare(int, int) avoid the re-invention of the wheel.


First, the web request itself will take some time.

To be able to profile it, maybe do some test with opening saved HTML file instead, to make sure that the parsing is your actual bottleneck, maybe even commenting the lines that create the result UI as well.

I haven't used HTML Agility Pack much, but I see you are using an XPATH selector there, and it only uses a CSS Class. I'd assume the path will scan the entire document to check eevery element in it if it has the desired class or not.

So, it may be a good idea to try to add some parents to the selector, so that it only looks for elements inside a given parent, best selected by ID or a tag. Those are general rules for browsers, I don't expect them to work the same with HTML Agility Pack, but they may provide some gain still.
Also, check if there are any options in the library to match a single element, and if so, find that element and go through its children till you find your desired elements. This may improve things. Also, if there are any strict mode or less tolerant parsing options, try turning those on if they don't break the parsing.

If you expect the page to be well structured and HTML valid, and parsing speed isn't getting any better however you enhance the selector, you may consider reverting to classic old Regex matching.

Also, I recommend separating the Windows Forms rendering from the loop. Maybe the bottleneck is the drawing (unlikely, but maybe), try to add all your elements to a list, and then outside the loop, add the list to the windows forms control.


Code reuse

You've asked a few dozen questions about tree algorithms, many of which contain very similar code.  Copy-and-paste programming is an antipattern; copy-and-pasting with modifications here and there is even worse.  By now, you should have developed a library of reusable classes.

That means decomposing your classes to obey the Single Responsibility Principle.  There should be a TreeNode<T> class that acts as a generic node with two child pointers, and possibly a create(List<? extends T>) convenience method.

public class TreeNode<T> {
    public TreeNode<T> left, right;
    public final T item;

    public TreeNode(T item) {
        this.item = item;
    }

    public static <T> TreeNode<T> createTree(List<? extends T> items) {
        TreeNode<T> root = new TreeNode<>(items.get(0));

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(items.get(right));
                    queue.add(current.right);
                }
            }
        }
        return root;
    }
}

There should be a TreePredicate<T> interface for algorithms that test a tree and return a true/false result.

interface TreePredicate<T> {
    boolean test(TreeNode<T> root);
}

Algorithms that implement the TreePredicate<T> interface should be in classes that are named as nouns, as with all Java classes.

Algorithm

Your use of recursion is weird.

The methods are poorly named: refurbish() is unintuitive; recurse() is too generic.  Furthermore, recurse() looks like a helper function that should not have been made public.

You shouldn't use mutation with recursion.  A key advantage of recursion is that immutable stack values make it easy to extend local reasoning to the large scale.  Impure functions with side-effects make such analysis difficult.

It should be clear what the invariants are when you recurse.  See the example JavaDoc below.

public class UniformLeafDepthPredicate<T> implements TreePredicate<T> {

    public boolean test(TreeNode<T> root) {
        return allLeavesDepth(root) >= 0;
    }

    /**
     * Returns the depth of this node, if the paths to all of its descendant
     * leaf nodes are all of the same length, or -1 if the height is
     * non-uniform.  The depth of a leaf node is 1.
     */
    private int allLeavesDepth(TreeNode<T> node) {
        if (node == null) return 0;

        int lDepth = allLeavesDepth(node.left);
        if (lDepth < 0) return -1;          // LHS has non-uniform depth
        int rDepth = allLeavesDepth(node.right);
        if (rDepth < 0) return -1;          // RHS has non-uniform depth

        if (lDepth == 0) return 1 + rDepth; // Only R child; RHS has uniform depth
        if (rDepth == 0) return 1 + lDepth; // Only L child; LHS has uniform depth

        return (lDepth == rDepth) ? 1 + lDepth : -1;
    }
}

By following these guidelines for recursion, the code is greatly simplified.

Unit tests

I don't know why you labelled the root node as "12" in your comments.  It's inconsistent with your actual tests.

I suggest adding one more test, because you currently have no test in which a child node has non-uniform depth.

public class LeafLevelTest {

    private TreePredicate<Integer> tester = new UniformLeafDepthPredicate<>();

    …

    @Test
    public void test4() {
        /*
                   1
                  /
                 5
                / \
               3   9
              /
             4
         */
        TreeNode<Integer> ll4 = TreeNode.createTree(Arrays.asList(1, 5, null, 3, 9, null, null, 4));
        assertFalse(tester.test(ll4));
    }
}


The 'prefer-1' algorithm works by having a current word, shifting out the first bit and then appending a new bit.

Such a current word - which essentially represents the tail of the sequence constructed thus far - could be housed in a machine word (word-sized variable or register) for lengths up to 32 or 64 bits. The new bit that you decide on during each iteration can then be converted to text and appended to the answer, which would obviously have been initialised to the textual representation of the all-0 word before the loop.

Your implementation does not keep such a current word. Instead you reconstruct the current word at each step from the textual representation of the sequence, by looking at its tail.

If you remove this inefficiency then your code ought to be fast enough to beat the generous timeout.

Also, your code can benefit from a bit of refactoring - moving the code for constructing the sequence out of main() into its own function - and from a thorough spring cleaning.

E.g. the expression (1<<n) does not change during the computation but you recompute for every iteration of the outer loop. usedN looks ugly and is not very informative; what about words_found? Or change things around to

for (unsigned words_to_find = 1u << n - n; words_to_find--; )
{
   ...
}

This must work since you find exactly one new word during each iteration. The term is (1 << n) - n because n characters have already been appended to the output sequence; other loop structures are possible but then the loop logic would have to be adapted.

Try to change your code so that it reads more like a description of what you're doing. Including asserts can help clarify things both for you and the reader, and it can help finding mistakes early.

For example, the 'prefer 1' algorithm implies that if the new word with a 1 already exists, then swapping the 1 for a 0 must result in word that does not exist yet. Assuming the current new word to be housed in a variable current_word:

if (used[current_word])
   current_word &= ~1u;  // change the new bit to zero

assert(not used[current_word]);
used[current_word] = true;

ans.push_back('0' + (current_word & 1u));

Or, if you enjoy terse code:

current_word ^= used[current_word];
...

But then you need to be careful about only writing strict 1 (i.e. true) into the array. Other non-zero values would also evaluate to true in conditions but they would completely mess up the terse code.

For an example that uses an integer working variable I'm appending a simple, straightforward Delphi rendition of the code (since I need to learn Delphi ATM). It clocks about 50 ms for n = 20, and a C++ version should be even faster. The code can be made significantly faster still for higher n, by using a packed bitmap and preallocating the result string (i.e. calling reserve() in C++).

function DeBruijn_sequence (n: Cardinal): string;
var
   seen: array of Boolean;
   bits: Cardinal;
   mask: Cardinal;
   i: Cardinal;
   w: Cardinal;
begin
   bits := 1 shl n;
   mask := bits - 1;
   assert(bits <> 0);
   SetLength(seen, bits);
   result := StringOfChar('0', n);
   w := 0;
   for i := n + 1 to bits do begin
      seen[w] := true;
      w := ((w shl 1) or 1) and mask;
      if seen[w] then begin
         w := w and not 1;
         assert(not seen[w]);
      end;
      result := result + Char(Byte('0') + (w and 1));
   end;
end;


One of the easiest ways to improve code is to reduce repetition. The
most-repeated elements in your code are random.choice and outputpass. You
can reduce bulk by importing what you need rather than importing a module containing
what you need.
from random import choice
from string import digits, ascii_letters, punctuation

Another bulk-reducer is to choose more practical variable names. By practical,
I mean names that are are more
compact but no less informative to the reader. For example, in a script that
generates a password, the context is quite clear, so you can get away with a
very short variable name: pw is one sensible option. Similarly, a simple name
like n is just as clear as asklenght, because in context everybody
understands what n means.
On the subject of naming, what does asku mean? Not very much to me. But
your input prompt text is very clear. A better name might be be method
(which your text uses)
or perhaps even chartype, which is more specific.
Your code has a bug for All: it creates a password 3x as long as it should be.
You don't need any special logic for n of 1, 2, or 3. Just set up
the loop and let it handle everything. The key is to use n rather
than n - 1.
for i in range(n):
    ...

The conditional logic inside the loop has only one purpose: selecting
the relevant characters to include in the password. Anytime you have
a situation like that, logic can often be greatly simplified by
creating a data structure.
characters = {
    1: digits,
    2: ascii_letters,
    3: punctuation,
    4: digits + ascii_letters + punctuation,
}

That change drastically reduces the code inside the loop:
pw = ''
for i in range(n):
    pw += choice(characters[chartype])

If you want to impress your friends, you can even write it
in one shot by using a comprehension:
pw = ''.join(choice(characters[chartype]) for i in range(n))

For usability, you might also consider changing the way that chartype
works: instead of asking users to type a number, which requires a small
mental translation from a meaningful thing (letters, numbers, symbols, all)
to an abstract thing (1, 2, 3, 4), you could just let them type the
first letter of the actual thing.
Also for usability, if the context is already clear, shorter messages
are easier on users, because they can scan them very quickly.
A final change to consider is whether to subject your user to interrogation by a
computer. I come from the school of thought that says humans tell computers what to
do, not the other way around. In addition to being pro-human, that policy has many practical benefits.
For example, isn't it annoying that everything time you edit the code and
re-run it, you have to answer the same damn questions. A different approach
is to take those instructions directly from the command line. Python
ships with a module called argparse that would work well for a script
like this, but you can skip that if you want and just use sys.argv directly.
You probably should do some input validation, but I'll leave that
for you to pursue or for some other reviewer to comment on. Here's
the code with those suggested changes.
from string import digits, ascii_letters, punctuation
from random import choice
from sys import argv

if len(argv) == 3:
    chartype = args[1]
    n = int(args[2])
else:
    prompt = 'Password characters:\n (D)igits\n (L)etters\n (S)ymbols\n (A)ll\n'
    chartype = input(prompt)
    n = int(input("Length?  "))
    chartype = chartype.lower()[0]

characters = {
    'd': digits,
    'l': ascii_letters,
    's': punctuation,
    'a': digits + ascii_letters + punctuation,
}

pw = ''.join(choice(characters[chartype]) for i in range(n))

print(pw)


Try this:

class Program
{
    static void Main(string[] args)
    {
        //var input = File.ReadAllText("input.txt");

        var input = "5 string one | 5.2 string two | 5.2.1 string three\r\n"+
                    "5 string four >> 5.6 string five >> string six\r\n" +
                    "1 string seven >> 1.1 string eight || 1.1.1 string nine\r\n";

        var matches = Regex.Matches(input, @"([0-9. ]*)(string \w*)([\|> $]*)",
            RegexOptions.Multiline);
        var template = "Number[{0}] = {1}\r\n" +
                       "Name[{0}] = {2}\r\n" +
                       "Separator[{0}] = {3}\r\n";
        var sb = new StringBuilder();
        sb.AppendLine("MyClass");
        int counter = 0;
        foreach (Match item in matches)
        {
            sb.AppendLine(String.Format(template,
                counter++,
                item.Groups[1].ToString().Trim(),
                item.Groups[2].ToString().Trim(),
                item.Groups[3].ToString().Trim()));
        }
        Console.WriteLine(sb.ToString());
    }
}

The output is:

MyClass
Number[0] = 5
Name[0] = string one
Separator[0] = |

Number[1] = 5.2
Name[1] = string two
Separator[1] = |

Number[2] = 5.2.1
Name[2] = string three
Separator[2] =

Number[3] = 5
Name[3] = string four
Separator[3] = >>

Number[4] = 5.6
Name[4] = string five
Separator[4] = >>

Number[5] =
Name[5] = string six
Separator[5] =

Number[6] = 1
Name[6] = string seven
Separator[6] = >>

Number[7] = 1.1
Name[7] = string eight
Separator[7] = ||

Number[8] = 1.1.1
Name[8] = string nine
Separator[8] =

Based on the request in your comment, I'm adding ordering of the output. Just replace the foreach statement above  with the following lines and make sure you add a using System.Dynamic; to the top of your class file:

List<dynamic> items = new List<dynamic>();
foreach (Match match in matches)
{
    dynamic item = new ExpandoObject();
    item.Index = counter++;
    item.Number = match.Groups[1].ToString().Trim();
    item.Name = match.Groups[2].ToString().Trim();
    item.Separator = match.Groups[3].ToString().Trim();
    items.Add(item);
}

var sb = new StringBuilder();
sb.AppendLine("MyClass");
foreach (var item in items.OrderBy(i => i.Number))
{
    sb.AppendLine(String.Format(template,
    item.Index,
    item.Number,
    item.Name,
    item.Separator));
}


referenceRow.field

The field name does not comply with the C# naming convention for public members that should be PascalCase. It should also probably be Fields since it's apparently a collection.

typeActions

Consider changing its name to convertTo which in this context makes the usage more natural:

var fieldValue = convertTo[typeof(T)]();

Func<object>

Consider using a parameter rahter then using closures. That makes the usage even clearer.

If you define it as

Func<object, object>

and the lambdas as

{ typeof(DateTime), x => { return DateTime.Parse(x.ToString()); } },

you can call it with

var fieldValue = convertTo[typeof(T)](referenceField.Item);

if (referenceField != null)

Avoid unnecessary nesting. You can use a postive condition == null and return right away if it's nulll.

return (T)Convert.ChangeType(fieldValue, typeof(T));

This is redundant. The converted value has already the target type. It just needs to be casted and because the ChangeType boxes the value anyway, you might as well do it yourself like this:

return (T)(object)typeActions[typeof(T)]();


The second one is much easier to read, it expresses the developers intent. At first sight I (as a maintainer or another developer in the same team, for example) just want a quick overview about the code and don't care about the details. (How the code creates a server socket, for example.) The second one exactly gives that.

The System.exit side effect could be eliminated: throw an exception with a proper message (and don't forget to set the cause). Then handle the exception in the run method. I often see wrappings like the following:

public void run() {
    try {
        doRun();
    } catch (SomeException e) {
        // exception handling here
    }
}

This often makes the doRun() simpler and easier to read.

Some other notes:

Socket clientSocket = null;
clientSocket = acceptConnection();

Could be written as

Socket clientSocket = acceptConnection();

I'd modify the createServerSocket() method to return the server socket and the acceptConnection() method to have a ServerSocket parameter. It would remove the temporal coupling between the two methods. It would be impossible to call them in the wrong order.
I've not written any threading code recently but I don't think that creating a separate thread for every client scale well. You might want to use an executor/thread pool there.


You can try something like this:

Create a list of utility function that you might want to use. You can export them to a utility file. This will keep code clean and maintainable.

isWorkingDay: Monday - Friday
isWorkingHours: Start at 8am and for working day end at 4pm. On Saturday, end at 2pm.
getDoubleDigitNumber: This will be helpful for both hours and minutes.
getHoursIn12HrFormat: To get hours in 12 hour format.
getDayText: To get name of day.

Now, in you main file, you can write a formatter function that would give you date time in specific format.
In your checkTime function, you do not want to write much logic. Use your utility functions and add any specific logic to mutate DOM.
Since you are dealing with classes, you should avoid className. This will replace all existing classes. Instead, use .classList. It provides many useful utilities.

Following is a sample:

function getDoubleDigit(value) {
  return ("00" + value).slice(-2);
}

function getHourIn12HrFormat(hour) {
  hour = hour || new Date().getHours();
  // This can be written as:
  // return hour % 12 || 12;
  return ((hour + 11) % 12 + 1);
}

function isWorkingDay(day) {
  return day !== 0 && day !== 6;
  // This can also be weitten as
  // return day > 0 && day < 6;
}

function isWorkingHours(hour) {
  hour = hour || new Date().getHours();
  return hour >= 8 && (isWorkingDay() && hour <= 16 || !isWorkingDay() && hour <= 14);
}

function getDayText(day) {
  var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  day = day || new Date().getDay();
  return weekday[day]
}

function getDateTimeString(date) {
  var now = date || new Date();
  var today = getDayText();
  var minutes = now.getMinutes();
  var hour = now.getHours();
  //add AM or PM
  var suffix = ["PM", "AM"][hour % 12];
  return today + ' ' + getHourIn12HrFormat() + ':' + minutes + suffix

  // If you are ok to use moment.js, all the above code can be converted to:
  // return moment().format('dddd hh:mm A')
}

var checkTime = function() {
  var now = new Date();
  var timeDiv = document.getElementById('timeDiv');
  var dayOfWeek = now.getDay();

  // reset classes and only add necessary class.
  timeDiv.classList.remove('open,close');
  if (isWorkingHours() && dayOfWeek !== 0) {
    timeDiv.innerHTML = ((isWorkingDay() ? 'Hi!! ' : '') + getDateTimeString() + ' - we\'re open!');
    timeDiv.classList.add('open');
  } else {
    timeDiv.innerHTML = ' Sorry—we\'re closed!';
    timeDiv.classList.add('closed');
  }
};

var currentDay = getDayText();
var currentDayCLASS = "." + currentDay; //gets todays weekday and turns it into     class
$(currentDayCLASS).toggleClass("today"); //hightlights today in the view hours

setInterval(checkTime, 1000);
checkTime();
#timeDiv {
  padding: 4px;
  border: 1px solid cyan;
  background: #ddd;
}

Hours

Monday - Friday

8:00am - 4:00pm

Saturday

8:00am - 2:00pm

Sunday

Closed

As suggested by @Nitin Dhomse, you can use moment.js.

This is how your formatting code would look like with moment:

return moment().format('dddd hh:mm A')


Your code would be slightly nicer this way:

jQuery.validator.addMethod("easyEmail", function(value, element, param) {
    if (this.optional(element)) {
        return true;
    }
    var trimmed = $.trim(value);
    var index = trimmed.indexOf('@');
    return index > 0 && index < trimmed.length - 1;
}, "Please enter a valid email address.");

Slightly nicer, because:

Check element before trimming value, as you might not use value at all.
It's a good practice to not overwrite parameter variables
It's good to cache the result of .indexOf to avoid calling twice

That said, since @user45891 found that nice link for you, I recommend you use it. I understand you only want a super-simple email validation, but this is waaaay too simple, to the point of almost uselessness.


If you're on C# 5.0, you can use await with IObservables to write code like this:

await itemsManipulationStarted.FirstAsync();
Items.IsHitTestVisible = false;

var e = await pageManipulationDelta.FirstAsync();
e.EventArgs.Complete();

await pageManipulationCompleted.FirstAsync();
Items.IsHitTestVisible = true;

Though I'm not completely sure this will do what you want, because of timing.


Good, flexible and secure MVC router PHP

Where you have:

$class = ucfirst($this->autoMap($command[0]), $this->classAliases);

I think it should be:

$class = ucfirst($this->autoMap($command[0], $this->classAliases));

The closing ) is in the wrong place.

Besides that I like your router, maybe it would be even better if it had a module control (so you could have something like: module/controller/method). This way you can have separated modules for admin, debug, default, etc.


Add variable columns to INSERT statement

You’re not using values except for its length. But this should be the same length than cols, so use that instead.

You also don't need a for-loop to build a list with the same element N times, list multiplication can handle that just fine.

Lastly, I would use f-strings or at least str.format instead of string concatenation, it is prettyier.

def insert_statement(db, columns):
    column_names = ', '.join(columns)
    placeholders = ', '.join(['%s'] * len(columns))
    return f'INSERT INTO {db} ({column_names}) VALUES ({placeholders})'

Usage:

>>> insert_statement('Publicationes', ['item_id', 'title', 'price'])
'INSERT INTO Publicationes (item_id,title,price) VALUES (%s,%s,%s)'

Depending on your calling site, you can also make columns a variable length argument, it may be easier to use:

def insert_statement(db, *columns):
    column_names = ', '.join(columns)
    placeholders = ', '.join(['%s'] * len(columns))
    return f'INSERT INTO {db} ({column_names}) VALUES ({placeholders})'

Usage:

>>> insert_statement('Publicationes', 'item_id', 'title', 'price')
'INSERT INTO Publicationes (item_id,title,price) VALUES (%s,%s,%s)'

But you should limit yourself to only use this function using trusted input. If anything comming from a user enters here, this is a vulnerability waiting to happen:

>>> user_input = "price) VALUES (42, 'foobar', 0.00); DROP TABLE Publicationes; -- Now this a vulnerability in disguise :"
>>> insert_statement('Publicationes', 'item_id', 'title', user_input)
"INSERT INTO Publicationes (item_id, title, price) VALUES (42, 'foobar', 0.00); DROP TABLE Publicationes; -- Now this a vulnerability in disguise :) VALUES (%s, %s, %s)"


Turning off Application.ScreenUpdating and Application.Calculation will greatly increase the speed.  But reading the data into an Array, modifying it and writing the Array back to the Worksheet is the real key to speed.

Recommended viewing: Excel VBA Introduction Part 20.2 - Application Events, Excel VBA Introduction Part 25 - Arrays

Sub CompareTime()
    'Optimize Setting for faster data writing
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With

    Dim Target As Range, ws As Worksheet
    Dim x As Long
    Dim results As Variant

    Set ws = ActiveSheet

    'Find last data point
    With ws
        .Columns("B:C").Insert
        .Columns("B:B").NumberFormat = "mm/dd/yy;@"
        .Columns("C:C").NumberFormat = "h:mm:ss;@"

        Set Target = .Range("A5", .Cells(.Rows.Count, "A").End(xlUp)).Resize(, 3)
        results = Target.Value2

        For x = 1 To UBound(results)
            results(x, 2) = Int(results(x, 1))
            results(x, 3) = results(x, 1) - results(x, 2)
        Next

        Target.Value2 = results
    End With

    With Application
        .Calculation = xlCalculationAutomatic
        .EnableEvents = True
        .ScreenUpdating = True
    End With

End Sub

  Set Target = .Range("A5", .Cells(.Rows.Count, "A").End(xlUp)).Resize(, 3)

Code Explaination

.Cells(.Rows.Count, "A").End(xlUp)

Target the last non-empty cell in Column A

.Range("A5", .Cells(.Rows.Count, "A").End(xlUp))
= Target Range from A5 to last non-emtpy cell in Column A
.Resize(, 3)
= Resize the Target range to include 2 more Column to the right same number of rows
results = Target.Value2

Create an array of values from the Target range.
.Value 2 is more effiecent than .Value because it ignores formatting

Target.Value2 = results

Assign the modified values from the results Array back to the Target range.


Two BDD unit tests for an account repository with identical code

One of the hardest piece of knowledge to learn as a developer is: code duplication does not mean responsibility duplication.

Having said this, you are testing different methods so it's ok to have more than one test. In this case, you are testing complementary (or were they supplementary? I never remember it) methods, so to test one, you need to have the other one working properly.

However, there are some code duplication that will bite you in the future (but since this question is from the past, you can tell me if I'm wrong or not).

You are duplicating the way a User entity is created, so if you change its constructor, you will have to modify your tests, even though it might not matter in the actual logic you are testing. It happens something similar with the Account entity. To avoid this you can have a private method or to a public builder.
You are duplicating the way a User is created and persisted. The same problem as in point #1 happens. You probably don't care how or when is created, you just need it to be created and persisted properly. This applies also for the Account entity with a slight different: in the first test you need to make the code of save into the repo explicit since it's what you are testing.

Besides all of this, when you are writing tests you need to tell the reader what's important and what's not and describe that accordingly. It's a balance between explicitness and abstraction. For instance in the example, I've written a method called createAccount to encapsulate the logic of creation and persistence of the Account entity. However, someone would say that if a developer reading the test needs to know what the arrange does, it has to move to the method implementation (a test should be self-explanatory and auto).

@DisplayName("user exists -- account does not exist -- save persists")
@Test
void save_userExistsAndAccountDoesNotExist_accountIsSaved() {
    // Arrange
    User existingUser = createUser();
    Account createdAccount = makeAccount(existingUser);

    // Act
    repo.save(createdAccount);

    // Assert
    assertThat(repo.findById(createdAccount.getId())).contains(createdAccount);
}

@DisplayName("user exists -- account exists -- findById finds")
@Test
void findById_userExistsAndAccountExists_returnTheAccount() {
    // Arrange
    User existingUser = createUser();
    Account existingAccount = createAccount(existingUser);

    // Act
    Optional<Account> foundAccount = repo.findById(existingAccount.getId());

    // Assert
    assertThat(foundAccount).contains(existingAccount);
}

private User createUser(){
    return userRepo.save(new User("John", "Smith"));
}

private Account createAccount(User existingUser){
    return repo.save(makeAccount(existingUser));
}

private Account makeAccount(User user){
    new Account(user, null);
}


Comment, Comment, Comment. If you want any other person on this blue planet to know whats going on in your code in the easiest way possible, comment your code.

// This is what the code does in the next line.
/* I'm going to write a block of text to tell you the purpose of what this function
is trying to accomplish */

Your code doesn't have to be pretty or legible for that matter, but a few comments go along way.

Also, whitespace for your if and while statements are appealing to the eye and allow the reader to break apart your conditional statements. Trying to cram as much as you can on one line causes headaches when trying to interpret them.


Sauna experiment - Celsius to Fahrenheit converter

Review

Several issues have also been addressed in the comments below your question. A quick re-iteration:

You state the user only knows Fahrenheit, yet you ask them to input in Celcius: Enter a desired temperature between 73 och 77 celcius.
For each bad attempt, you add the new input to the previous input temperature = temperature + celcius;. This doesn't make any sense at all.
You should be able to read from code what the code is about. tempCheck(double temperature) doesn't tell us the unit of the input. Prefer celcius or a custom class Celcius.

tempCheck(double temperature)

This method has two very different responsibilities: (1) detect status by provided temperature (2) render status information to user. These should be two different methods to allow for reusability of the status check.

The status could be an enum:

enum TemperatureStatus
{
    Normal,   // 73°C - 77°C (but not 75°C)
    Perfect,  // 75°C
    Freezing, // < 0°C

    // and so on ..
}

Have tempCheck return the status:

static TemperatureStatus tempCheck(double celcius)
{
    if (celcius < 0) return TemperatureStatus.Freezing;

    // and so on ..

    return TemperatureStatus.Normal;
}

Rendering the status message can then go to its own method:

static string RenderStatus(TemperatureStatus status, double celcius)
{
    celcius = Math.Round(celcius);
    switch (status)
    {
        case TemperatureStatus.Freezing:
            return "The sauna has now become a freezer, \nCelcius: {celcius}";
        // and so on ..
    }
}


Option Explicit
That should be at the top of every VBA module you ever create. Go to Tools -> Options -> Require Variable Declaration to have it inserted automatically. It's important because it forces you to declare every variable you use, and so automatically gets you to declare types and catches any typos that creep in. Those 2 alone will prevent all sorts of problems down the line.

Very Low Hanging Performance Fruit
VBA has 3 of these:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Doing the following will vastly increase the speed of your code:
Public Sub DoThing()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    ...

    Code

    ...

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub

In this case, since you're relying on certain formulas to throw errors, you should probably keep Application.Calculation on xlCalculationAutomatic.

Use the Object Model
The great power of VBA comes from its' tight integration with the Office Object Model (from were Intellisense gains its' power).
Worksheet objects, Workbook objects, Range objects, Array objects, Err (error) objects etc.
Rather than constantly activating different worksheets, put them in objects and then refer to them instead:
    Dim sourceDataSheet As Worksheet
    Set sourceDataSheet = Worksheets(1)

    Dim foundItemsSheet As Worksheet
    Set foundItemsSheet = Worksheets(2)

    Dim remainingItemsSheet As Worksheet
    Set remainingItemsSheet = Worksheets(3)

    ...

    Do While sourceDataSheet.Cells(k, 24) <> ""

        Tab_Data = sourceDataSheet.Range(sourceDataSheet.Cells(k, 24), sourceDataSheet.Cells(k, 44)).Value

        remainingItemsSheet.Range(remainingItemsSheet.Cells(k, 1), remainingItemsSheet.Cells(k, 21)).Value = Tab_Data

        k = k + 1

    Loop

This also lets you do really awesome things like hold object references using With statements:
    Do While sourceDataSheet.Cells(k, 24) <> ""

        With sourceDataSheet
            Tab_Data = .Range(.Cells(k, 24), .Cells(k, 44)).Value
        End With

        With remainingItemsSheet
            .Range(.Cells(k, 1), .Cells(k, 21)).Value = Tab_Data
        End With

        k = k + 1

    Loop

And now you can forget about having to keep using Activate ever again.
It also lets you re-use references, so this:
    Do While Cells(i, 1).Value <> "" And Not IsError(Cells(i, 2).Value)
        Dataset = Range(Cells(i, 1), Cells(i, 22)).Value
        Range(Cells(i, 1), Cells(i, 22)).Value = Dataset
        Worksheets(2).Activate
        Range(Cells(i, 1), Cells(i, 22)).Value = Dataset
        Worksheets(1).Activate
        For j = 2 To Aud_Tot
            If CStr(Cells(j, 24).Value) = CStr(Cells(i, 2).Value) Then
                Worksheets(3).Activate
                Range(Cells(j, 1), (Cells(j, 22))).Delete Shift:=xlShiftUp
                Worksheets(1).Activate
                Exit For
            End If
        Next j
        i = i + 1
    Loop

becomes this:
    Dim startCell As Range
    Dim errCheckCell As Range

    Const START_COLUMN As Long = 1
    Const ERR_CHECK_COLUMN As Long = 2
    Const END_COLUMN As Long = 22

    Dim sourceDataRange As Range
    Dim pasteDataRange As Range

    Set startCell = sourceDataSheet.Cells(i, START_COLUMN)
    Set errCheckCell = sourceDataSheet.Cells(i, ERR_CHECK_COLUMN)

    Do While startCell.Value <> "" And Not IsError(errCheckCell.Value)

        With sourceDataSheet
            Set sourceDataRange = .Range(.Cells(i, START_COLUMN), .Cells(i, END_COLUMN))
        End With

        With foundItemsSheet
            Set pasteDataRange = .Range(.Cells(i, START_COLUMN), .Cells(i, END_COLUMN))
        End With

        Dataset = sourceDataRange

        sourceDataRange = Dataset
        pasteDataRange = Dataset

        For j = 2 To Aud_Tot

            If CStr(sourceDataSheet.Cells(j, 24).Value) = CStr(errCheckCell.Value) Then

                With remainingItemsSheet
                    .Range(.Cells(j, 1), (.Cells(j, 22))).Delete Shift:=xlShiftUp
                End With

                Exit For

            End If

        Next j

        i = i + 1

    Loop

which looks a little bigger (right now, we'll get to cleaning it up later) but is much, much clearer about what's going on and where, and lets you change just one reference if and when things get moved/changed in the future.
For instance, what happens if your order of worksheets gets changed? Now, you only have to change that once, right at the start, and the rest takes care of itself.

Tips and Tricks

finalRow - Want to find the last used row in a column?
    Dim finalRow As Long

    With sheetObject
        finalRow = .Cells(.Rows.Count, targetColumn).End(xlUp).Row
    End With

And you can then use
    For k = 2 To finalRow

        ...

    Next k

instead of that unwieldy Do While cellReference(k).Value <> ""

constants - if you're going to hard-code values (e.g. Column 1, Column 22, Worksheets(1)) then actually hard-code them. Once. In one place. So you can change it in a single go rather than having to track down every occurence of the thing (and invariably missing some and causing errors).
The proper variable for a constant value is, unsurprisingly a Constant. Standard VBA Naming Conventions use SHOUTY_SNAKE_CASE for constants. Created like so:
Option Explicit

Public Const GLOBAL_CONSTANT As Boolean = True
Private Const MODULE_CONSTANT As Long = 42

Public Sub DoThing()

    Const PROCEDURE_CONSTANT As Long = 1

    ...

End Sub

Codenames - Every Worksheet has a codename (name) property. If you got to the properties window in the Editor, select a worksheet and type, e.g. sheetCodename in the (name) property, then you can write a procedure like so:
Public Sub DoThingWithSheet()

    sheetCodename.Cells(1, 1).Value = 1

without having to declare the sheet, or assume anything about its' name, or its' position in your workbook, or anything else. The variable is just there, constant and unchanging.

Your Code, Better
(assuming we've already given your sheets the following codenames: dataSheet, foundItemsSheet, remainingItemsSheet)
Public Sub UpdateAudit()

    Const TAB_START_COLUMN As Long = 24
    Const TAB_END_COLUMN As Long = 44

    Const TAB_PASTE_START_COLUMN As Long = 1
    Const TAB_PASTE_END_COLUMN As Long = 1
    Const START_ROW As Long = 2 '/ +1 for headers

    Dim numItemsToAudit As Long
    numItemsToAudit = Application.InputBox("How big is your audit", Type:=1)

    Dim finalRow As Long
    With dataSheet
        finalRow = .Cells(.Rows.Count, TAB_START_COLUMN).End(xlUp).Row
    End With

    '/ Copy All Raw Data to "remainingItemsToFind" sheet
    Dim tabData As Variant
    Dim iRow As Long
    For iRow = START_ROW To finalRow

        With dataSheet
            tabData = .Range(.Cells(iRow, TAB_START_COLUMN), Cells(iRow, TAB_END_COLUMN))
        End With

        With remainingItemsSheet
            .Range(.Cells(iRow, TAB_PASTE_START_COLUMN), .Cells(iRow, TAB_PASTE_END_COLUMN)) = tabData
        End With

    Next iRow

    '/ For each row in "rawData" sheet, check for error.
    '/ If not error, copy to "foundItems" sheet and delete from "remainingItems" sheet
    Const FOUND_START_COLUMN As Long = 1
    Const FOUND_END_COLUMN As Long = 22

    Const FOUND_ERR_CHECK_COLUMN As Long = 2
    Const REMAINING_ERR_CHECK_COLUMN As Long = 24

    With dataSheet
        finalRow = .Cells(.Rows.Count, FOUND_START_COLUMN).End(xlUp).Row
    End With

    Dim dataArray As Variant
    Dim dataRange As Range
    Dim pasteRange As Range

    Dim foundErrCheckCell As Range
    Dim remainingErrCheckCell As Range

    Dim errCheckRow As Long

    For iRow = START_ROW To finalRow

        Set foundErrCheckCell = dataSheet.Cells(iRow, FOUND_ERR_CHECK_COLUMN)

        If Not IsError(foundErrCheckCell) Then

            '/ Get Source Data
            With dataSheet
                Set dataRange = .Range(.Cells(iRow, FOUND_START_COLUMN), .Cells(iRow, FOUND_END_COLUMN))
            End With

            dataArray = dataRange

            With foundItemsSheet
                Set pasteRange = .Range(.Cells(iRow, FOUND_START_COLUMN), .Cells(iRow, FOUND_END_COLUMN))
            End With

            '/ Copy Data
            dataRange = dataArray
            pasteRange = dataArray

            '/ Find and Delete from "remainging items" sheet
            For errCheckRow = 2 To numItemsToAudit

                Set remainingErrCheckCell = dataSheet.Cells(errCheckRow, REMAINING_ERR_CHECK_COLUMN)

                If remainingErrCheckCell.Text = foundErrCheckCell.Text Then
                    remainingItemsSheet.Rows(errCheckRow).Delete shift:=xlShiftUp
                    Exit For
                End If

            Next errCheckRow

    Next iRow

End Sub

You'll notice the better code looks longer. This is entirely down to having more variable declarations and adding some whitespace for readability. When measuring code, the metric that matters is not how much you can cram into a small space, but how quickly you can read and understand the code and how to change it.


JavaScript Code for image rotation on a web page

Three things I noticed:

1. Looking through the document with DOM methods is a slow process. There's often no way around it, and it won't crash anything here, but try to minimize it when you can. From page 183 of Stoyan Stefanov's JavaScript Patterns:

  DOM access is expensive; it's the most common bottleneck when it comes
  to JavaScript performance. This is because the DOM is usually
  implemented separately from the JavaScript engine...

  The bottom line is that DOM access should be reduced to a minimum.
  This means:

  Avoiding DOM access in loops
  Assigning DOM references to local variables and working with the locals
  Using selectors API where available
  Caching the length when iterating over HTML collections

I've done that here. I created one extra variable named images and assigned it an empty array. Then, using your counting function, I store the image references in it.

var currentImage,
    images = [],

      ...

    count = (function () {
      // Figure out how many images we have on the rotation
      var x = 0;
      while (document.getElementById('rotateImg' + (x + 1).toString())) {
        images[x] = document.getElementById('rotateImg' + x.toString());
        x++;
      }
      return images.length;
    }()),

(If you're able to change the HTML, you can avoid the loop altogether and collect these images in one line. Just add an id to the element that contains them...

  ...

...and collect them with...

var images = document.getElementById("container").getElementsByTagName("img");

But this doesn't help you if you can't change the markup.)

Now you can run hideImage and showImages on the array instead of having to walk the DOM every time.

2. When the first argument to setInterval is a string, the browser runs eval() -- an implementation of the JavaScript compiler -- on it before firing. That's also expensive and unnecessary here. From page 111 of Douglas Crockford's JavaScript: The Good Parts:

  The browser provides setTimeout and setInterval functions that can
  take string arguments or function arguments. When given string
  arguments, setTimeout and setInterval act as eval. The string
  argument form also should be avoided.

Getting rid of the quotes and the closing parentheses makes it a plain old function reference, which works fine.

So I changed this:

var interval = setInterval("rotation.advanceRotation()", 4000);

To this:

var interval = setInterval(rotation.advanceRotation, 4000);

3. Not crucial here. You can do all your variable declaration with one var statement per function. This reduces the chances of your variables being overwritten or unavailable due to hoisting. From JavaScript Patterns again:

  JavaScript enables you to have multiple var statements anywhere in a
  function, and they all act as if the variables were declared at the
  top of the function... This can lead to logical errors when you use a
  variable and then declare it further in the function.

So I took out the multiple var statements and declared them all at the top of the outer function.

The final code:

  <title>Rice Flour Cookies' image rotation test</title>

And you can see it at work here:
http://james.da.ydrea.ms/riceflourcookies/rotate.html


RAII and code duplication in constructor/destructor

You can't call virtual functions in constructors and should not call them in destructors (you may have already destroyed state that the virtual function relies on).

You can use the PIMPl pattern to help you out though (like the c++ stream, they use a wrapper class and a buffer class that does the work).

class VidCaptureInterface
{
    public:
    virtual ~VidCaptureInterface() {}
    virtual open(string const& uri) = 0;
    virtual close()                 = 0;
};

// When C++17 comes along then
// You may be able to force T to be a VidCaptureInterface
// This is one solution. But you basically want interface
// to be derived from `VidCaptureInterface`. In C++ stream
// the buffer is held as a pointer and can be re-assigned
// So alternatives include using some form of re-assignable pointer.
template<typename T>
class VideoCapture
{
     T   interface;
     public:
         VideoCapture(std::string const& uri)
         {
             interface.open(uri);
         }
         ~VideoCapture()
         {
             if (isOpen())
             {
                 interface.close();
             }
         }
};

typedef VideoCapture<VidCaptureInterface1>  VideoCapture1;
typedef VideoCapture<VidCaptureInterface2>  VideoCapture2;
typedef VideoCapture<VidCaptureInterface3>  VideoCapture3;


Recursively list files within a directory

Your function could be a generator (which were introduced in Python 2.2). It should also expose the pattern for the filter as a parameter:

import os
import fnmatch

def files_within(directory_path, pattern="*"):
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for file_name in fnmatch.filter(filenames, pattern):
            yield os.path.join(dirpath, file_name)

if __name__ == "__main__":
    # You can simply iterate over the generator:
    for file_path in files_within("."):
        print file_path

    # If you absolutely need a list:
    file_list = list(files_within("../"))

    # Use the pattern parameter:
    text_files = list(files_within(".", "*.txt"))

I like to leave the names from os.walk the same as in the documentation, but this is a personal choice.

What is not quite a personal choice is the number of tabs per indentation level. Python's official style-guide, PEP8, recommends using always 4 spaces.

I also changed the way of the imports. Here it already becomes obvious why importing them like this is better (as far as readability goes). It is obvious that fnmatch.filter is from the module fnmatch and not the built-in filter.


As a general rule, if you want your markup to be semantic, you should be using classes, IDs and document structure to describe the content as clearly as possible, to whatever level is required to achieve the styling you need. Don't just add classes and IDs with the motivation "I need something to hook a CSS selector to", try thinking about what it is you want to style and use your tools to describe the thing.

Pragmatic design means you will have to be non-semantic to support particular browsers, particularly those that can't take advantage of the more advanced selectors, but you should only append these as required, if you can't achieve your desired design easily another way.

For your scenario, I would question whether main is a very good class name. Classes are intended to classify something, such that several instances of that thing can appear in a document (and be styled in the same way). If you intend to have several things in the page classified as main, it doesn't add a great deal of semantic value - I can't understand what that element really contains, other than that it's probably more important than non-main elements.

If you are trying to say "this is the primary content of the page", you should instead use an id. Use of an ID implies "there is only one of these per page", which gives you faster-performing scripts and the ability to reference the element with anchors (#main).

Additionally, if the header, footer and section elements are being given the main class because they're all related, you could try representing this relationship more strongly by nesting them inside a parent element and applying an ID to that element, e.g:

        ...

As an aside, the way you've listed section with header and footer makes me wonder if you're using it correctly.

The HTML5 specification says:

  The section element represents a generic section of a document or
  application. A section, in this context, is a thematic grouping of
  content, typically with a heading.

It specifically warns:

  The section element is not a generic container element. When an
  element is needed for styling purposes or as a convenience for
  scripting, authors are encouraged to use the div element instead. A
  general rule is that the section element is appropriate only if the
  element’s contents would be listed explicitly in the document’s
  outline.

So, the idea of a "main" section probably isn't right. Sections are meant to be ways partition a large article into headed-sections, in very much the way a Wikipedia article is laid out. You could easily say you have a "main" article, but a "main" section doesn't make as much sense.


A method for events callback with the correct "this"

First of all, since you're using jQuery already, why not use $.proxy() which does the same thing?

$('#button').click($.proxy(this, 'fooBar', true));

That's equivalent to your contextualize example, as far as I can tell. And $.proxy has the added benefit of working with functions themselves, not just their names. That means you can use it to wrap a function from some other object in a given context. I.e.

$('#button').click($.proxy(this.fooBar, someOtherContext, true));

Meanwhile, your contextualize can't similarly "re-contextualize" a function; it only works for functions present in the context argument.

There's also the built-in Function.prototype.bind which will return a function bound to a given context, like $.proxy does above:

$('#button').click(this.fooBar.bind(this, true));

It's available in all modern browsers, but if you want more compatibility, use $.proxy.

Second: !!!(...). Just use 1 negation, please. It'll coerce a value to a boolean and negate it just fine; there's absolutely no reason to negate it 2 more times. Besides, since the expression in the parentheses is boolean logic, it's already is a boolean value to begin with, so it really is straight-up negation; no coercion involved. Yes, using !! can be a handy way of coercing a value to a boolean without negating it, but even that is almost never needed since whatever you're coercing is thruthy or falsy all on its own (if(!!something) is equivalent to just if(something))

I'd also skip the "is this a function" check entirely. JS will complain all by itself, if you let it. Of course, it won't call your error function when it complains, but I'd rather have JS complain loudly than go through a custom error function. Sure, your function checks for the function's existence right away, rather than failing when trying to call it, but you can always remove the function from the context object afterward, so the upfront check guarantees nothing.

var boundFunction = Utils.contextualize(contextObj, 'fooBar');
delete contextObj['fooBar']; // boundFunction will now fail when called

Or you might want to add the function after calling contextualize, but you can't do that right now without error being called.

Third: You're returning a function by invoking a function that returns a function. Much like the triple-negation above, that's an unnecessary, round-about way of doing things. This will do the same

return function() {
    var args = [];
    $.merge(args, otherArgs);
    $.merge(args, $.makeArray(arguments));
    return (context[methodName].apply(context, args));
};

otherArgs and context are already available as closures, so there's no reason to pass them to a function, just to create new closures there.

So, yeah, your function will work, but it's unnecessary and overly complex, while being less versatile than the alternatives you already have at hand. I wouldn't recommend using it, to be honest. Sorry.


First of all, the PrimeFactorize() does never terminate for number = 1
because the check IntUtils.IsPrime(number) will never return true.
The call PrimeFactorize(1) should return an empty list.

To compare the performance of various implementations, I used the following simple
test program which computes all prime factors of the numbers up to 10,000. The sum
is calculated to prevent the compiler from removing function calls whose result is
not used, and to verify that all implementations give the same results.

using System.Diagnostics; // for StopWatch

public static void Main()
{
    Stopwatch stopWatch = Stopwatch.StartNew();
    var sum = 0;
    for(var N = 2; N <= 10000; N++)
    {
        foreach(var P in IntUtils.PrimeFactorize(N))
        {
            sum += P;
        }
    }
    stopWatch.Stop();
    Console.WriteLine("Sum: {0}, Time: {1} ms", sum, stopWatch.Elapsed.TotalMilliseconds);
}

The tests were done on a MacBook, using
 Mono.

For your code, the result is

 Sum: 10243046, Time: 2945.7256 ms

Your code creates a list of primes in order to find the lowest factor of the given number,
and the GetPrimesBetween() function seems be the performance bottleneck.

The IsPrime() function can be improved slightly. Since divisibility by 2, 3, 5 is
checked upfront, the loop can start with i = 7. Inside the loop, divisibility by
both i and i+2 is checked, so that the next possible divisor is i+4. Therefore
the loop should be

    // iterate with trial division
    int i = 7;
    while (i * i <= n)
    {
        if (n % i == 0 || n % (i + 2) == 0)
        {
            return false;
        }
        i += 4;
    }

This reduces the execution time to

Sum: 10243046, Time: 1193.3498 ms

To improve the PrimeFactorize() function, note that every composite number \$ n \$ necessarily
has a factor \$ p \le \sqrt n \$. Also, if a factor is found,
you can repeatedly check that factor instead of breaking out of the
loop and starting with the first prime again.

This leads to the following implementation:

public static IEnumerable<int> PrimeFactorize(int number)
{
    List<int> primes = IntUtils.GetPrimesBetween(2, (int)Math.Sqrt(number));
    foreach (var p in primes)
    {
        while (number % p == 0)
        {
            yield return p;
            number /= p;
        }
    }
    // Now either number == 1 or number is a prime:
    if (number > 1) {
        yield return number;
    }
}

which reduces the execution time considerably:

Sum: 10243046, Time: 15.6476 ms

A faster way to determine all prime numbers in a given range are sieving methods.
A simple implementation of the sieve of Eratosthenes is
(taken from https://codereview.stackexchange.com/a/62158/35991, but
as an enumerator):

public static IEnumerable<int>GetPrimesUpto(int number) {
    bool[] isComposite = new bool[number + 1];
    for (int x = 2; x <= number; x++)
    {
        if (!isComposite[x])
        {
            yield return x;
            for (int y = x * x; y <= number; y = y + x)
            {
                isComposite[y] = true;
            }
        }
    }
}

which can then be used as:

public static IEnumerable<int> PrimeFactorize(int number)
{
    var primes = IntUtils.GetPrimesUpto((int)Math.Sqrt(number));
    foreach(var p in primes)
    {
        while (number % p == 0)
        {
            yield return p;
            number /= p;
        }
    }
    if (number > 1) {
        yield return number;
    }
}

Execution time:

Sum: 10243046, Time: 9.6804 ms

But actually you don't need to compute a list of primes first
(and I am essentially repeating the arguments from https://codereview.stackexchange.com/a/64795/35991).

The smallest factor of a number is necessarily a prime. You already
divide the number by any factor found, but this means that the lowest
factor of the updated number is again a prime. So by repeatedly
searching for the lowest factor you'll find all prime factors without
doing any extra test for primality.

Again it suffices to check for factors up
to the square root of the (remaining) number. After that,  number is
either equal to one or a prime.

This leads to the following function:

// Generate prime factors for a number, e.g., input 12 returns 2 2 3
public static IEnumerable<int> PrimeFactorize(int number)
{
    // Check divisibility by 2:
    while (number % 2 == 0) {
        yield return 2;
        number /= 2;
    }
    // Check divisibility by 3, 5, 7, ...
    for (var i = 3; i * i <= number; i += 2) {
        while (number % i == 0) {
            yield return i;
            number /= i;
        }
    }
    if (number > 1) {
        yield return number;
    }
}

Execution time:

Sum: 10243046, Time: 2.6631 ms

(C# is not my primary language, but I hope that the code demonstrates the idea.)


Jquery field add code - Improvements in readability, compactness or efficiency

First of all there is a great article on refactoring jQuery by Jack Franklin.

Second is my solution that i came up with in last 2 hours(ocd kicked in). My solution is probably not right, because i still have a ton to learn and would appreciate any feedback !!

Here fiddle with implementation. Here is a short version of what is going on inside, as you can see i tried to refactor each action in it's own method:

// detail object that handles our form
var details = {
    maxFields: 10,
    form: "",
    init: function(el) {},
    bindEvents: function() {},
    appendCopy: function(event) {},
    removeCopy: function(event) {},
    createCopy: function(value) {},
    focusOnEnter: function(event) {},
    addCopyOnEnter: function(event) {},
    _isValueEmpty: function(val) {},
    _isMaxReached: function(copyContainer) {},
    _getParent: function(event){},
    _getCurrent: function(event){}
    _getCopyContainer: function(event){},
    _getValue: function(event){},
};

// initialize our details object
    details.init(".form");

I think this could also be rewritten using $.deferred where each deferred would be responsible for tracking it's own progress (requirements,benefits,qualifications).