Firstly, underneath everything Javascript is an event driven language so I do not think that there is anything wrong with using an event driven design pattern if you are comfortable with it. Events are a great way to be able to interlink different components of your system without exposing the inner workings of them (loose coupling) and they add queuing by default. However they are more complex, they make it hard to trace behavior which in turn can make them hard to debug.

I think that you would get a cleaner interface by developing using something called the revealing module pattern, there is an excellent resource on various design patterns by a guy called Addy Osmani at adyosmanio.com and the revealing module pattern specifically here. This (or a flavor of it) is commonly used in jQuery plugin development which you can see on the jQuery advanced plugin development page (see Keep private functions private). By following these principles you can keep the private stuff private and only expose the functions that you want the calling code to have access to.

You mentioned specifically showPopup(), hidePopup() and updateColor(newColor) so a quick example of how that might look.

;(function($) {
    var ColorPickerSliders = function($element, options) {
         //if you want publicly modifiable configuration options.
         var defaults = {
            "opacity": 0,
            "hsl": 1,
            ...
        };

        function init() {
            ...
        }

        function showPopup()
        {
           ...
        }

        function hidePopup()
        {
           ...
        }

        function updateColor(newColor) {
            //uses private function
            var updatedcolor = tinyColor(newColor);
            ...

        }

        //private
        function tinyColor(newColor) {
            ...
        }

        //private
        function buildHtml()
        {
           ...
        }

        //this is the bit that makes your functions public
        //note that each function returns $element to preserve
        //chaining capabilities.
        return {
            "showPopup": function() {
                showPopup();
                return $element;
            },
            "hidePopup": function() {
                hidePopup();
                return $element;
            },
            "updateColor": function(newColour) {
                updateColor(newColour);
                return $element;
            }
        }
    };

    //the use of the data in here is to prevent the plugin being instantiated multiple times
    $.fn.colorPickerSliders = function(options) {
        return this.each(function() {
            if (!$(this).data('colorPickerSliders'))
                $(this).data('colorPickerSliders', new ColorPickerSliders(this, options));
        });
    };
})(jQuery)

Using the above you can then pull the plugin api from the element using:

$yourElement.data('colorPickerSliders').showPopup();

And you can chain:

$yourElement.data('colorPickerSliders').showPopup().delay(1000).hidePopup();

For reference you can also check this excellent article from Smashing Magazine (check the author) and related GitHub repository.


Computing the improper integral of several functions

You are assuming the functions in <cmath> (e.g. fabs(), sin()) etc. are in the global namespace already. However, it is unspecified in the standard whether or not these functions exist in the global namespace. The easiest way to ensure they are in the global namespace is to add using namespace std; to the appropriate source file, but that's bad practice. A better practice would be to add using declarations (preferably in the most local scope possible), or simply add std:: to the beginning of each function call.

There is little point in passing a primitive like double by const reference rather than by value. The performance is about the same and it saves you typing to pass by value.

Areas of your code are difficult to read due to lack of spacing. For example:

while(eps<fabs(previousSum-currentSum));

The same line is easier to read like this:

while (eps < fabs(previousSum - currentSum));

Similarly, this:

for(int i(1); i < n; i+=2)
    {s4 += f(a+i*step);}

would be easier to read with the { and } on their own lines like this:

for (int i(1); i < n; i += 2)
{
  s4 += f(a + i*step);
}

If your compiler supports C++11 or later you may want to initialize with curly braces ({, }) to avoid the most vexing parse.


Speed optimization for girth-counting algorithm

What you should be using is a neighboring matrix.

The key is graph theory.

You represent the graph with a matrix.

For example:

\$
\begin{bmatrix}
0 & 1 & 1 & 0 & 2 \\
1 & 0 & 2 & 0 & 0 \\
1 & 2 & 0 & 1 & 1 \\
0 & 0 & 1 & 0 & 1 \\
2 & 0 & 1 & 1 & 0 \\
\end{bmatrix}
\$

Here is a graph and its corresponding neighbouring matrix.
If you look at the first row you see that A has no one-step connection to itself. But it has a one-step connection to every other node.
Node B has a one-step connection to A and 2 different one-step connections to node C.
As you can see it all sums up if you keep going like this.

Now then, here's the mathemagic. If you multiply the matrix with itself the result will be a matrix which tells you all the connections of two-stop length.
Continue multiplying with the original matrix until you've done it 8 times and you will have a matrix which tells you how many connections of eight-step length you have.

How is matrix multiplication done, you might ask?
Wikipedia
Another site (with examples)
Basically, you multiply rows with columns.(It would take another whole answer to explain it)

When you've gotten the neighbouring matrix of the eight power, you just sum up all the elements of the diagonal. That will tell you the number of cycles of length 8. (because the diagonal holds the information of a n-step way back to itself, where n is the power of which the matrix has been multiplied)

This method works for all graphs. All you need to do is make sure the graph is bipartite to begin with.


indexOf Boyer-Moore String Search algorithm

1. Bug

The code in the post does not work!

>>> index_of('abba', 'bba')
>>> # expected 1 but got None

Read on to see how you could have discovered this.

2. Review of the unit tests

Having a suite of unit tests is excellent, better than 99% of submissions to Code Review.
Using assert for the unit tests means that you don't get much information out of a test case failure. For example, if I artifically introduce a bug into the code, then I might get this test output:

======================================================================
FAIL: test_index_of_with_matching_patterns (cr179311.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr179311.py", line 38, in test_index_of_with_matching_patterns
    assert index_of('abc', 'c') == 2
AssertionError
----------------------------------------------------------------------

At this point it would be helpful to know what the incorrect value was. The unittest.TestCase class has a bunch of assert methods that produce better output. For example, if I replace the line:

assert index_of('abc', 'c') == 2

with:

self.assertEqual(index_of('abc', 'c'), 2)

then the test failure message includes the incorrect value:

======================================================================
FAIL: test_index_of_with_matching_patterns (cr179311.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr179311.py", line 38, in test_index_of_with_matching_patterns
    self.assertEqual(index_of('abc', 'c'), 2)
AssertionError: -1 != 2
----------------------------------------------------------------------

Each unit test knows its expected result. But you had to type these in by hand and could have made a mistake. It would be more reliable if the expected result were computed. In this case we could use the built-in str.find method, for example:

self.assertEqual(index_of('abc', 'c'), 'abc'.find('c'))

This approach is known as using a test oracle.
The unit tests are very repetitive. Every test has the form:

assert index_of(haystack, needle) == expected_index

or if you follow my suggestions above,

self.assertEqual(index_of(haystack, needle), str.find(haystack, needle))

The repetition could be avoided by making the tests data-driven, like this:

class TestIndexOf(unittest.TestCase):
    CASES = [
        # Positive cases
        ('abc', ''),             # all strings contain empty string
        ('abc', 'a'),            # single letters are easy
        ('abc', 'b'),
        ('abc', 'c'),
        ('abc', 'ab'),           # multiple letters are harder
        ('abc', 'bc'),
        ('abc', 'abc'),          # all strings contain themselves
        ('aaa', 'a'),            # multiple occurrences
        ('aaa', 'aa'),           # overlapping pattern
        ('thisisabsolutelycrazy', 't'),
        ('abcdef', 'abcdef'),    # all strings contain themselves
        ('ababc', 'abc'),        # overlapping prefix
        ('bananas', 'nas'),      # overlapping prefix
        ('abcabcabc', 'abc'),    # multiple occurrences
        ('abcabcab', 'abc'),     # multiple occurrences
        ('abcabcdef', 'abcd'),   # overlapping prefix
        ('abcabcdef', 'abcdef'), # overlapping prefix
        ('abcabcdabcde', 'abcde'), # overlapping prefix
        ('abcabcdabcde', 'abcd'), # multiple occurrences, overlapping prefix
        ('abra cadabra', 'abra'), # multiple occurrences
        ('abra cadabra', 'adab'), # overlapping prefix

        # Negative cases
        ('abc', 'z'),           # remember to test other letters
        ('abc', 'ac'),          # important to test close cases
        ('abc', 'az'),          # first letter, but not last
        ('abc', 'abz'),         # first 2 letters, but not last
    ]

    def check(self, haystack, needle):
        expected = haystack.find(needle)
        if expected == -1:
            expected = None
        self.assertEqual(index_of(haystack, needle), expected,
                         "index_of({!r}, {!r})".format(haystack, needle))

    def test_cases(self):
        for haystack, needle in self.CASES:
            self.check(haystack, needle)

This makes it easy to add more test cases.
Since we have a test oracle, it would make a lot of sense to generate random test cases. This allows us to explore a much larger space of possibilities than we could do just by writing out test cases by hand.

It's easy to generate random (positive) test cases:

def test_random(self):
    for n in range(1, 100):
        haystack = ''.join(random.choice('abc') for _ in range(n))
        start, stop = sorted(random.sample(range(n + 1), 2))
        needle = haystack[start:stop]
        self.check(haystack, needle)

And if we run these randomly generated test cases, we soon get a test failure as described in §1 above:

======================================================================
FAIL: test_random (cr179311.TestIndexOf)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr179311.py", line 91, in test_random
    self.check(haystack, needle)
  File "cr179311.py", line 81, in check
    "index_of({!r}, {!r})".format(haystack, needle))
AssertionError: None != 3 : index_of('cacaaaaaa', 'aaaaaa')
----------------------------------------------------------------------


Doer is not a particularly expressive name. Sure, the class does something -- but what class doesn't? Your impulse to name the class Calendar is definitely on target. There are a few other naming things that are not according to Ruby style guidelines; you should avoid CamelCasing your method names -- for instance, makeCal should be make_cal and even better something like make! or create! (assuming the class itself is named calendar, saying @calendar.make_calendar is repeating yourself.)

In general, with respect to 'spaghetti' code, the issue is usually that you are not really separating concerns. The problem that Objects are trying to solve is encapsulating responsibility. It destroys any advantage you stand to gain to put all your functionality into one place. Object-oriented programming involves modularity and encapsulation -- naming a class Doer might indicate some weaknesses in terms of really grokking the paradigm. Consider studying some actual web application source code and see how concerns are separated and handled at an appropriate level of abstraction.

On that last point, one good rule of thumb is that code which is 'nearby' should be operating at roughly the same level of abstraction. Try to identify different concerns and modularize them -- make them 'loosely coupled' to one another. You might make a class which handles the business logic of padding and packing the string stuff, and separate the 'pure' calendar logic into a different class altogether; your application would then just have to 'glue' the two capabilities together.


Overall your code is readable and it seems reasonably clear what it does. As you said, the code is somewhat inefficient if one of the arrays is much larger than the rest, but for your example (and honestly, even if you had a thousand items in one array), the time cost would probably be negligible, unless the number of arrays in arr is very very large.
Number.MIN_VALUE
Number.MIN_VALUE is not what you think it is. It represents the smallest positive number that can be represented, not the most negative number. As a result, if you use let arr = []; you end up with a biggestLength that is slightly more than 0 and run your second loop... only to figure out that you do not have items. Or arrays, This in itself does not break anything, but you could just initialise biggestLength to 0 and things would work out fine.
Optimising
As I said earlier, the amount of time it takes to do this operation is negligible, even if you have 100 items in the first array. With 11 items over 4 arrays (16 operations) it takes me 0.010ms, and with 107 items over 4 arrays (400 operations) it takes me 0.025ms.

const arr = [
  [1, 2, 4, 6],
  [3, 8, 7],
  [12, 13],
  [],
  [9, 10]
];

function getUnfoldedArray(arr) {
  let biggestLength = Number.MIN_VALUE;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length > biggestLength) {
      biggestLength = arr[i].length;
    }
  }

  let result = [];
  for (let l = 0; l < biggestLength; l++) {
    for (let k = 0; k < arr.length; k++) {
      if (arr[k][l] !== undefined) {
        result.push(arr[k][l])
      }
    }
  }

  return result;
}

console.time('First run is always slower');
getUnfoldedArray(arr);
console.timeEnd('First run is always slower');

console.time('time1');
const result = getUnfoldedArray(arr);
console.timeEnd('time1'); // 0.010ms

arr[0] = [];
for (let i = 0; i < 100; i++) {
  arr[0].push(i);
}

console.time('time2');
const result2 = getUnfoldedArray(arr);
console.timeEnd('time2'); // 0.025ms

console.log(result);
console.log(result2);

If you don't mind destroying the array you are doing stuff on, you can potentially use Array.shift(). You could also splice out any empty arrays then, but keep in mind that loops will mess up when you do that. Overall your code would probably get more complicated for not a lot of gain.


pyramid numbers in alternative reverse order

Naming

int n=5; // no of rows

If you need a comment to explain the intent of an variable, then something went wrong. You should just rename the variable to numberOfRows.
Also variable names which aren't loop iteration variables shouldn't have single letter names.
E.g c should better be currentNumber.

Space

for(int i=1;i<=n;i++){

Help you code to breath and add some space

for(int i = 1; i <= n; i++){

is easier to read.

Indention

    if(i%2!=0){
    for(int j=0;j<i;j++){
        c++;
        System.out.print(c +" ");
    }
    }

wouldn't the above be easier to read if coded like

    if(i%2 != 0){
        for(int j = 0; j < i; j++){
            c++;
            System.out.print(c +" ");
        }
    }


Misleading Message?

    if (args.length != 1) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }

So if I have 2 arguments, I get the message No arguments provided. Umm... I provided 2 arguments!
Suggested fix:
Change the above code to:
    if (args.length == 0) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }

And you can possible warn the user about only requiring one argument if they provide too much. Something like:
    if (args.length > 1) {
        System.out.println("Warning! Too many arguments; only the first one will be considered.");
    }


A starts-with should be easy enough to store in a pre-sorted list, ideally using a case-insensitive sort comparer rather than applying conversions each sort. Then: use binary search to find the first match, and keep moving forwards until it no longer matches. Should be pretty efficient.

If this needs to be edited in a shared multi-threaded context, be sure to use appropriate synchronization - presumably readers will be more common than writers, so a ReaderWriterLockSlim may be the best option.


Constantly checking for activity in a page then log out if no activity

I would route all ajax calls through 1 function in JavaScript, and that function then keeps track of the last call. In essence, the browser itself should know whether there was activity or not.

If for some odd reason you need multiple windows with the same session to stay open as long as one of them has activity, then I would change the timer from 3000 to 60000. Checking once a minute should be more than fine.

Finally executeQuery is a terrible name, perhaps checkTimeOut?


A few things:

I would supply all the variables that you have hard coded into the method i.e. localPath, filename, ftp server, networkcredentials.  Otherwise how can you re-use this method for other operations?
I would probably avoid making the method static unless there was good reason to.
In your finally clause you don't check if responseStream or writeStream are null?  What if they never got created before an exception was thrown?
I personally think unless there is a very valid reason you should always do something in an exception catch block, whether it be logging somewhere, re-throwing the exception or anything.  Otherwise the calling method will have no idea that something went wrong.
What is _result?  I don't see it being set and I don't see it being declared anywhere?
If Length is a constant, make it a constant.  i.e. const int Length = 2048.
I might also consider implementing some sort of call back method so you can provide status updates on the progress on the download.  Just a suggestion, not sure how you would implement it exactly.

I might consider writing the loop as such:

int bytesRead;
while((bytesRead = responseStream.Read(buffer, 0, Length)) > 0)
{
   writeStream.Write(buffer, 0, bytesRead);
}

As to your quesion.  Is this code useful?  In short.  Yes, but only if you ever want to do only one thing with it and never want to re-use anything inside.  Otherwise no.

That's just a few comments off the top of my head.  I hope those are a good starting point.


Script for showing/hiding on click - how can I write this code cleaner?

First I think that using document.querySelector seems much user friendly than using document.getElementsByClassName. Instead of let coll = document.getElementsByClassName('collection'); coll[0].xxx, we can just use document.querySeletor('collection').xxx.
So code can refactor a bit to
    let coll = document.querySelector('.collection');
    let dis = document.querySelector('.display');
    let drop = document.querySelector('.drop');

    document.getElementById("menu-btn1").addEventListener("click", function() {
        if(coll.style.display == 'none') {
            coll.style.display = 'block';
            dis.style.display = 'none';
            drop.style.display = 'none';
        } else {
            coll.style.display = 'none';
        }
    });

Next, I will place the DOM retrieval code into the event handler, to prevent unnecessary namespace pollution. Though maybe in your working code, you may use the coll for other handling, then it is okay to place there. In addition, I don't think one will change the variable of a DOM to other value, so I would use a constant instead.
    document.getElementById("menu-btn1").addEventListener("click", function() {
        const coll = document.querySelector('.collection');
        const dis = document.querySelector('.display');
        const drop = document.querySelector('.drop');
        if(coll.style.display == 'none') {
            coll.style.display = 'block';
            dis.style.display = 'none';
            drop.style.display = 'none';
        } else {
            coll.style.display = 'none';
        }
    });

However these changes does not resolve the fact that display: none is actually scattered in both HTML and Javascript. I think a better idea is just to place the code in one place. That is remove the styling in HTML.

To do so, I think there are possibly 2 approaches, one is the use of RxJS, another way is to use of data driven approach, e.g. React, Angular, Vue, ...
Data Driven Approach: Use of VueJS
Let's first have a look at How we can implement it in Data Driven Approach.
I will use Vue for demonstration, as it is the simplest to setup among the three.

new Vue({
            el: "#app",
            template: `

                    collection

                    Collection Inside

            `,
            data: function() {
                return {
                    show: false
                }
            },
            computed: {
                styles: function() {
                    return {
                        "display": this.show ? "block": "none"
                    };
                },
            },
        })

As you can see, the HTML code is now placed in Javascript as a template, and we make use of :style and @click in the template, instead of normal HTML. These are Vue specific
syntax and is used in Vue for easy interaction between the Vue component Javascript and the template.
Event Driven Approach: RxJS
Another approach would be RxJS, that just work without a framework, so makes it more easy to adopt in a legacy web application.

rxjs.merge(
    rxjs.of(1), // so that it immediately triggers
    rxjs.fromEvent(document.querySelector("#menu-btn1"), 'click'),
)
    .pipe(
        rxjs.operators.scan((accum, value, index) => {
            return index % 2 == 1;
        }, false)
    ).subscribe(show => {
        const coll = document.querySelector(".collection");
        const value = show ? "block" : "none";
        coll.style.display = value;
    }

    )

    collection

    Collection Inside

Here is all the solution I think of, and it is left to you to decide which way is the cleanest code. To me, I just like the way RxJS is constructed, and do not need to maintain an extra data for storage.


Use the correct headers

#include "assert.h"

should be

#include <cassert>

since you're writing C++. C++ provides special headers for all C headers, they generally start with a 'c' and have the '.h' removed at the end. Prefer these.

Also system headers, should always use <> rather than "".

Your definition of NULL is unsafe

NULL is typically reserved to use in the context of pointers. Defining NULL as you do means that NULL is not of a pointer type and you can pass NULL as an integer for example this is not desirable.

If you must define NULL you should do it like this:

#ifndef NULL
#define NULL (reinterpret_cast<void*>(0))
#endif

but really most likely it is already included by one of your other headers (<cstddef>, <clocale>, <cstdio>, <cstdlib>, <cstring>, <ctime> and anything that includes those, so pretty much everything).

If you are using C++11 or newer you should use nullptr instead of NULL.

Style

I personally would name node with the same convention as your other classes, Node. I'm also not a big fan of using _ as a suffix for class members but that is personal taste.

Pass template arguments by constant reference

As T can be just about anything, you should pass all Ts by const reference (const T&) to avoid possibly expensive copies.

Const correctness

Methods that do not modify the state of the queue should be declared const.

bool isEmpty()

should be

bool isEmpty() const

being const correct allows you to get compile time errors if you unintentionally modify something you didn't intend to. It's a good habit.

Construct objects as close as possible to their final state

Your node class should have a constructor that initialises the data member. This will reduce some code for you.

Put the sentinel in the class.

Allocating the sentinel node on the heap in your constructor is unnecessary. Prefer to have it be a member variable. It is a good practice to not allocate on the heap when it suffices to use a local or member variable.

Avoid code duplication

The copy constructor and copy assignment operator are typical places where one usually gets code duplication.

I would suggest using the Copy and Swap Idiom for implementing the assignment operator.

And welcome to the site!


Here are some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Rethink your object design

Right now, the Solver object simply holds two dozen static strings.  It has no intelligence and does not, in any sense, know anything about the cube it purports to solve.  A better solver might keep a model of the scrambled cube to track its state.

Don't optimize blindly

First, we should keep in mind what Donald Knuth has said about optimization:

  "The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming."

Your particular program probably spends 99% of its time doing I/O, so the performance differences among possible alternatives is probably best approximated as zero.  If what you're really after is a better algorithm, then that's a different problem.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can potentially improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Use string concatenation

The code currently includes these lines:

cout<<"-----------------------------------------------"<<endl;
cout<<"|            Cube Solver 2x2 v1.0             |"<<endl;
cout<<"|            Developed by Pavan P             |"<<endl;
cout<<"-----------------------------------------------"<<endl<<endl;
cout<<"Enter the Sequence in small letters: ";

Each of those is a separate call to operator<< but they don't need to be.  Another way to write that would be like this:

std::cout <<
    "-----------------------------------------------\n"
    "|            Cube Solver 2x2 v1.0             |\n"
    "|            Developed by Pavan P             |\n"
    "-----------------------------------------------\n"
    "Enter the Sequence in small letters: ";

This reduces the entire sequence to a single call to operator<< because consecutive strings in C++ (and in C, for that matter) are automatically concatenated into a single string by the compiler.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Refactoring and condensing a Javascript function with many repeat conditions, strings, and variables

Try to avoid repetition.

var args, i, check, len, filtered;

function parseUrl() {
    var getArgs = {};

    function decode(s) { // declare this function only once, don't declare functions inside any kind of loop
        return decodeURIComponent(s.replace(/\+/g, ' '));

    document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
        getArgs[decode(arguments[1])] = decode(arguments[2]);
    });

    return getArgs;
}

function create_filter_input($name, $termname) {
    var $input = '<input class="query-input" type="hidden" value="' + $termname + '" name="' + $name + '" />';
    return $input;
}

args = parseUrl();
check = ['area', 'property_type', 'style', 'feature'];
len=check.length;

for(var i=0; i<len; i++) {
    if (!args[check[i]]) {
        continue;
    }
    filtered = create_filter_input(check[i], args[check[i]]);
    $filterTerms.append(filtered);
}

Try to write code anticipating change and write it to make your life easy. For example this:

type = $_GET["property_type"],

creates a variable named type but you then effectively need a map to get back to "property_type":

create_filter_input('property_type',type);

Is the same as:

create_filter_input('property_type', $_GET["property_type"]);

(Which, incidentally is the same as: create_filter_input('property_type', $_GET.property_type); - use dot notation where possible.)

If you write it like that - seeing that you are passing (almost) the same argument in all use cases to your create_filter_input function - you can start to see/think that you don't need 2 local variables - just having "property_type" is enough.

As one of the other answers says - don't serially append to the dom. each write is relatively expensive. it's better to build a dom fragment and append it to the dom in one go.


Framework to define and require JavaScript modules

First off, you could start by naming the variables meaningfully. Your define looks like this:

App.define = function(name, reqs, func) {
    if (typeof reqs === "function") {
        func = reqs;
        reqs = [];
    }
    App.require(reqs, func, name);
};

If I were another dev (which I am), I'd wonder what reqs mean. Is it requests? Requirements? Oh wait, dependencies! That's the word. How about func? Should it be a callback? Hmm... probably moduleDefinition would be better, right? Naming them properly would allow others to review your code easily, and maybe allow you to remember your code, just in case you went on vacation for 2 weeks.

Now I know you're trying to emulate AMD, which is fine (I personally prefer it over Browserify). However, one recurring complaint from devs is the issue of the "array of dependencies". What if you had more than a handful of dependencies for the module?

App.define('MyModule',['oh','my','vegetables','thats','very','long'], function('its','very','unweildly','dont','you','say'){
  // End of ceremonious module definition.
});

I personally would recommend the "wrapped CommonJS" approach, where you pass in require into your module definition, and just have it run there. I'm assuming all your modules are loaded, nothing async and your solution is just to have them load in any order.

App.define('MyModule', function(require){
  var Foo = require('foo');
  var Bar = require('bar');
  var John = require('john');
  // and so on
});

Though technically longer in the long run, but it's more manageable and readable than an array and another list of variable names. Another advantage, unlike the real AMD (which does static analysis to fine CJS-style requires), is that your "modules" are already loaded in memory. Calling require this way, synchronously, is possible as require will merely return a reference to the loaded module.


Is this an excessive abstraction using objects?

I think the use of classes here is excessive because of complexity added by their structure and inheritance. Since your objects have only one method putObject you can make abstraction on the function level. So you can just use closures to save state by returning a function that will put objects. In this case s3Cache will use only one function of s3Legacy as a dependency.
Here is the code:
const s3Legacy = (sdk, bucket) => function putObject(key, body, callback) {
    sdk.putObject({ Bucket: bucket, Key: key, Body: body }, callback);
}

const s3Cache = (putObjectLegacy) => function putObject(params, callback) {
    const toS3Key = (unitId, incidentTimestamp, incidentId, archiveIncidentObjectName) => 'implementation';
    const toTimestampObject = (timestamp) => 'implementation';

    const key = toS3Key(
        params.unitId,
        toTimestampObject(params.timestamp),
        params.eventId,
        params.eventFileName
    );

    putObjectLegacy(key, params.body, callback);
}

module.exports.handle = (event, context, cb) => {
    const s3Sdk = new AWS.S3({ region: config.s3.region });
    const putObjectLegacy = s3Legacy(s3Sdk, config.s3.legacyBucketName);
    const putObjectCache = s3Cache(s3Legacy(s3Sdk, config.s3.cacheBucketName));

    putObjectLegacy(key, event.body, callback);
    putObjectCache({
        unitId: event.pathParameters.unitId,
        timestamp: event.timestamp,
        eventId: event.id,
        eventFileName: event.id,
        body: event.body
    }, callback);
}


Do not include types in variable names

carCostP
       ^

Remove that P (probably stands for a number type?) the compiler takes care of types for you.

Avoid so many variables

You can avoid those four variables altogether, you may just convert to double as soon as you read the vars, like this:

double carCost = Double.parseDouble(
     JOptionPane.showInputDialog("What is the total cost of the car?"));


Using a Generic Value Object in a DDD application

Using the code in your example along with the following article for reference

Representing a collection as a Value Object

Lets start with refactoring the City value object to use the improved ValueObject

public sealed class City : ValueObject<City> {

    public string Name { get; }
    public bool IsEnabled { get; }

    public City(string name, bool isEnabled) {
        Name = name;
        IsEnabled = isEnabled;
    }

    protected override IEnumerable<object> GetEqualityComponents() {
        yield return Name;
        yield return IsEnabled;
    }
}

Note how GetEqualityComponents was implemented. Reflection could also have been used to enumerate the properties as needed

return this.GetType().GetProperties().Select(propInfo => propInfo.GetValue(this, null);

There is room for improvement above and I will leave that as an exercise.

For collections, the GetEqualityComponents allows for a simplified approach of returning the items used to check equality.

public class CityList : ValueObject<CityList>, IEnumerable<City> {

    private List<City> _cities { get; }

    public CityList(IEnumerable<City> cities) {
        _cities = cities.ToList();
    }

    protected override IEnumerable<object> GetEqualityComponents() {
        return this.OrderBy(c => c.Name);
    }

    public IEnumerator<City> GetEnumerator() {
        return _cities.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}

Note that since the collection already implements IEnumerable one simple needs to return the desired enumeration that will be used to calculate equality.

GetEqualityComponents() proves to be a very convenient approach and really does improve and simplify how the ValueObject can be implemented. I initially though it to be a premature optimization attempt but having taken some time to review its potential I have changed my initial view of its function.

UPDATE from comments about the potential of using reflection.:

  The use of reflection automates and simplifies a repetitive task with
  a minor performance trade off. Caching the property/field info could
  help a little but I personally have had no issues with it performance
  wise. Also using reflection grabs all while using the yield like in
  the example you get to be selective of which ones to use for equality.
  You can make an extension method to get the best of both worlds and
  have options.

public static class ValueObjectExtensions {
    /// <summary>
    /// Uses reflection to extract all public properties from the target value object
    /// </summary>
    public static IEnumerable<object> GetComponents<T>(this ValueObject<T> target)
        where T : ValueObject<T> {
        return target.GetType().GetProperties().Select(propInfo => propInfo.GetValue(target, null));
    }
}

and used like

protected override IEnumerable<object> GetEqualityComponents() {
   return this.GetComponents(); //<-- calling extension method
}


Check divisibility of each line in a large dataset

class InputTest{

Spacing.

public static void main(String args[]) throws Exception{

Again. There should be a space before each "{".

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

You're using a platform dependent encoding (which is actually nearly always wrong). There are chances that it's UTF-8 and it probably takes quite some time.

Nearly any encoding would do, and e.g., LATIN-1 should be faster as it converts one byte to one char, which is way simpler than UTF-8.

But even faster would be no encoding at all. The whole input can be easily read directly from bytes.

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Spaces are inexpensive, use them! No more comments on formatting.

if(m>Math.pow(10,9))

Gotcha! Why are you exercising such an expensive operation every time? And why do you wonder that it's slow? Maybe the JIT may be able to optimize it away, but

You could simply 1e9 and get rid of the computation.
You could simply write 10000000 or (since Java 7) even 10_000_000 and have an integer as it should be.
But you surely should define a constant instead. The it doesn't matter how complicated the computation is as it gets done just once.

throw new Exception();

That's ugly. Exception is too unspecific and there's no message there. What about a

throw new RuntimeException(String.format("Invalid (k, n) = (%s, %s)", k, n));

Or would maybe

assert n > 0 : n;
assert k > 0 : k;
assert k <= 10_000_000 : k;

do?

So again, if you want to speed it up,

remove the obvious inefficiency
don't use strings
read the file in as a byte[]
parse numbers from it manually

For really big inputs, it could make sense to avoid both the conversion to int and the modulo computation by creating a data structure working directly with the input byte[]. But this is rather complicated , surely not for everyone.


According the work around section in the kb article mentioned in the blog entry, your solution looks correct.


POSIX.1-2008 only mandates support for the -k option of man, so you can't rely on man having any -s option on a POSIX compatible system, and in fact it is absent in both FreeBSD and Dragonfly BSD. That aside, your command should be reasonably portable barring the following issues:

Some older shells do not support $() for command substitution

Most notably C shell and the original Bourne shell do not support dollar-parentheses expansion. Use `` instead.

Output of man -k may differ between operating systems

On OpenBSD at least, there are no spaces separating the command names and the section numbers in parentheses, so it's probably better to delimit by left parenthesis. But beware of command synonyms that look like byacc, yacc (1) (MINIX), which will produce undesirable results if not further delimited by comma.

man may only display the first manual page found

Again on OpenBSD at least, the default behavior of man is to display only the first manual page found. From the man manual:

  -a Display all of the manual pages for a specified section and name combination. Normally, only the first manual page found is displayed.

Note: this is not POSIX compliant behavior.

man -k . may actually search for the literal . character

Both man -k . and man -k '' should, according to the POSIX specification, match anything in the man database, but this is not the case in OpenBSD, MINIX and SmartOS.

Piping to tr is unnecessary

Unless the IFS variable has been tampered with, the last command of the pipeline is superfluous.

Proposed solutions

Tested OS: Fairly recent versions of CentOS, Kali Linux, Manjaro Linux, openSUSE, Ubuntu, nixOS; OpenBSD, FreeBSD, Dragonfly; SmartOS; MINIX

Tested shells: sh, csh, tcsh, ksh, bash, dash, zsh

There are three ways to search for man pages in a section: man -ssection, man -Ssection or just mansection, presented roughly in the order of decreasing support by the OSes. Linux distros seem to prefer the first way, and BSDs the second. The CentOS man manual also mentions the -s option is for compatibility with System V, so it is the safest bet.

A general solution that works in all tested OSes except FreeBSD and Dragonfly:

man -a -s 1 `man -s 1 -k '(' | awk -F '[,(]' '{print $1}' | sort`

A targeted solution that works in all tested BSDs:

man -a -S 1 `man -k sec~^1$ | awk -F '[,(]' '{print $1}' | sort`

Simplest solution for a specific OS (OpenBSD):

man -a -k sec~^1$ ; # May contain duplicates


Let's create a scenario. You have lots of log files to prune - some from January, February and March. You have, for whatever reason, way more than maxLogsToKeep. I can see a possibility that your routine would delete the February files and keep the January ones because you do not sort and you trust the order in which Dir returns the files. However, this may not be important to you.

Firstly, reference Microsoft Scripting Runtime in your VBA project. This gives you access to the FileSystemObject and related classes. This gives you more helper functions that will make the code easier to read and maintain (e.g. the File class allows you to access file information without additional reference to the file path; and a File.Delete).

The only way around that scenario I noted is to sort. While the FSO has a Files collection, I don't see any additional functionality that allows you to sort the collection, so you can create your own collection (array in VBA for sorting) and sort that.

Some web references (links are now old - while the fundamentals stay the same the coding could take advantage of newer functionality in VBA):

https://forums.overclockers.com.au/threads/vba-retrieve-files-names-in-order.863553/
http://www.vb-helper.com/howto_dir_quicksorted.html
https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/
http://www.cpearson.com/excel/CollectionsAndDictionaries.htm

If I was writing this, then I would traverse the Files collection and build the Array (of File) as I went (the Files.Count will let you dimension the array properly in the first place) but perhaps a quick sort would be more efficient. After you have built the sorted array, you can traverse the array from the end until maxLogsToKeep and delete the files (File.Delete) (*).

Yes, a little more complicated, but addresses a scenario where you might retain ancient logs at the expense of more recent ones.

(*) I know I am working with an array rather than a For Each or other collection enumeration, but I now have a habit of working from the end when deleting things.


Rendering function for total player points

Split code of getTotalPoints function into two steps:

Save list of players into temp variable. If playerId is specified, then create array with only one element;
Call calculatePoints in a foreach.

Other suggestions:

Put var before points variable in calculatePoints function to move it from global to local scope;
Rename getTotalPoints function to updateTotalPoints;
Depending on the rest of your code it may be possible to pass array of players into render function. And move playerId check out of it.


Count the number of ways an integer can be represented as a sum of consecutive positive integers

Some ideas that can improve the complexity:

I am seeing that you are trying to equate num to i + (i+1) + ... + j, you can calculate this by j*(j+1)/2 - i*(i-1)/2
Further for a given i if we assume that num = j*(j+1)/2 - i*(i+1)/2 we can solve the quadratic equation and check if we get integral roots, that makes the whole solution O(n)
You may also wanna try looking up solutions to quadratic Diophantine equations, see here, after all j*(j+1)/2 - i*(i-1)/2 = num is a quadratic diophantine equation only.

What I would probably do

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConsSum {

    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        long num = Long.parseLong(br.readLine());
        System.out.println("There are " + getConsSumWays(num) + " total way(s) to get " + num);
    }

    private static int getConsSumWays(long n) {
        int count = 0;
        /*
         * i + (i+1) + (i+2) + ... + j = n
         * => j(j+1)-i(i-1)=2n
         * => let k = j(j+1) = 2n + i(i-1)
         */
        for (long i = 0; i <= n / 2; i++) {
            long k = 2 * n + i * (i - 1);
            /*
             * j^2+j-k=0 => j = [-1+sqrt(1+4k)]/2 since j>0
             */
            long j = (long) ((-1 + Math.sqrt(1 + 4 * k)) / 2);
            if (j * (j + 1) == k) {
                System.out.println("sum [" + i + ".." + j + "] = " + n);
                count++;
            }
        }
        return count;
    }

}


As with most of your questions, your code violates PEP8.

Don't print your output.
Since \$\text{start} = \text{exclude_index} + 1\$ you can never visit exclude_index.

Your code with the above changes make your code more readable.
But it'd be better if you:

Start using Python's standard library. Itertools can drastically improve your codes readability.
Stop relying on while so much.
Use a dictionary, it's fast, and increases readability.
sorted runs in \$O(n\log(n))\$ time.

Using itertools.combinations_with_replacement and collections.Counter you can generate all three of your numbers, still in \$O(n^2)\$ time.

Pass a sorted list to combinations_with_replacement, and generate two numbers.
Check target - i - j is in the list of numbers, and that it is greater or equal to i and j.
Group; i, j and k, in a Counter and check there is enough of each number in the original list.

import collections
import itertools

def three_sum(numbers, target):
    Counter = collections.Counter
    count = Counter(numbers)
    for i, j in itertools.combinations_with_replacement(list(sorted(count)), 2):
        k = target - i - j
        if k in count and j <= k >= i:
            nums = (i, j, k)
            if all(count[k] >= v for k, v in Counter(nums).items()):
                yield nums


Tree Template Class Implementation for C++

Do not get in the habit of using using namespace std.
Since you're using <cstddef> for size_t, you should make it std::size_t for C++.
Since you define your own destructor, you should also overload the copy constructor and the assignment operator.  This is known as The Rule of Three in C++.  This is especially important in the case of raw pointers as data members as the compiler-provided copy constructor and assignment operator will only copy the pointer (shallow copy), not the data (deep copy).

You should also follow Dieter's advice (in the comments): use T data instead of T* data, and remove thenew/delete.  Use as little manual memory allocation as possible in C++.
You're using a range-based for-loop in the destructor, which must mean you're using C++11.  Bearing this in mind, one change you should make is using nullptr instead of NULL.


Asking user input until a valid datetime is given (bloated try-except blocks)

I will focus on the main question, i.e. how to decompose the code so that checks are kept, but the code does not get bloated with them.

Regarding the first part: I recommend to factor out the code asking for input, and split the initialization function into two separate ones. Something like this:

import datetime as dtt

def read_date(prompt, def_date=None):
          switch = 1
          while switch == 1:
                week = input(prompt) or def_date
                try:
                       week = dtt.datetime.strptime(week,'%m/%d/%Y')
                       switch = 0
                except ValueError:
                       print('Unrecognized date format, please try again\n')
          return week

def init_week():
    return read_date('Week to check: MM/DD/YYYY\n')

def init_before_day():
    return read_date('Check days before date (Press enter to use today): MM/DD/YYYY\n', '{0:%m/%d/%Y}'.format(dtt.date.today()))

def week_init():
    return [init_week(), init_before_day()]
    # alternatively (without the helpers): return [read_date(), read_date(dtt.date.today())]

For the second part, I suggest factoring out the mapping logic from inputting the date (or at least, the date should also be read in the function itself -- but receiving it as a parameter, and then reading it again is very messy IMHO). So this would look something like the following:

def spotmap_impl(week, bam, pt):
    bam['SD'] = bam.index.to_series().map(pt.fillna(0)['len',week])
    return bam

def spotmap(bam, pt):
    switch = 1
    while switch == 1:
        try:
            week = input('Week start date (Sunday): MM/DD/YYYY\n')
            bam = spotmap_impl(week, bam, pt)
            switch = 0
        except KeyError:
            print('Invalid date, please try again.')
    return bam;

Remarks:

I tried to leave the original names as much as possible, but I feel they could be improved (e.g. in read_date we are reading a date, which is then somehow used as a week; so I would call the internal variable something like input_date. Also instead of switch, I would use a name like success, and values True/False, instead of 1 and 0).
I could not test the second part, as I do not understand exactly what is the meaning and contents of bam and pt, but I hope you get the idea :) (Btw., these variable names might be improved too.)
You might want to add further validation code to the parameters of spotmap_impl. And then write unit tests for it, if you haven't done so yet ;)


Find position of a word in a list in Python

A similar solution using enumerate():

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

if word in word_list:
    for position, name in enumerate(word_list):
        if name == word:
            print("Your word is in the list at ", position)
else:
    print('Your word is not in the sentence')

You could also use a list comprehension:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

positions = [x for x, n in enumerate(word_list).split() if n == word]
if positions:
    for position in positions:
        print('your word is in the list at ', position)
else:
    print('Your word is not in the sentence')

Also, a generator expression that's a little more efficient:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

found = False
for position in (x for x, n in enumerate(word_list) if n == word):
    print('your word is in the list at ', position)
    found = True
if not found:
    print('Your word is not in the sentence')


Concurrent access to data with QReadWriteLock

Locking
Let's see what these member functions actually do, and what can go wrong:
getData
The lock acquired in getData basically only ensures that nobody is currently modifying data while inside. As soon as the caller gets the returned value, another thread is free to modify it.
To be a bit clearer, this is how RAII breaks down:
QVector<DataType> getData() {
    QReadWriteLocker lock(rwLock);
    QVector<DataType> temp = data;
    lock.~QReadWriteLocker(); // unlock
    return temp;
}

So the lock doesn't actually cover subsequent usage.
beginModifyData/endModifyData
These two member functions expect to be called in tandem. But what happens if the caller to beginModifyData forgets to call endModifyData (e.g. because an exception was thrown)? Obviously, in that case the lock never gets released.
Also, somebody might store the returned pointer, thus having unsynchronized access to the data after the lock got released.
General stuff
Is there any specific reason why rwLock has to be a pointer? It could simply be of type QReadWriteLock instead.
Is there any specific reason why beginModifyData returns a QVector<DataType>* instead of a QVector<DataType>&?
Your question regarding RVO
No, that is not how return value optimization (RVO) works. For a better understanding, if the compiler applies RVO it might conceptually rewrite the code to something similar to this:
void getData(QVector<DataType>* return_value) {
    QReadWriteLocker lock(rwLock);
    // construct a new QVector<DataType> at the given address (to be passed from the callsite)
    new(return_value) QVector<DataType>(data);
}

// the callsite would be rewritten from
QVector<DataType> myData = dataManager->getData();
// to
QVector<DataType> myData; // uninitialized!
dataManger->getData(&myData);

So this obviously won't work with a reference.
Without RVO, the reference won't work at all, as the lifetime of the returned object ends at the end of its declaration. However, it will work (at least partially) for a const QVector<DataType>& as lifetimes of temporaries get extended for those (though it will still refer to the copy).


Minimum priority queue using Singly Linked LIst

Data structures

Although the name "priority queue" is technically correct,
I find it a bit misleading,
because priority queues are usually implemented using a heap data structure,
with insert and find operations in \$O(\log n)\$ time.
Your implementation is practically a sorted linked list,
with insert and find operations in \$O(n)\$ time.
I'd clarify as "naive priority queue" to avoid confusion.

Memory leak

Watch out for memory leaks.
When deleting the first item,
the deleteItem function simply advances the pointer of front,
without actually deleting the item,
leaving allocated memory behind.

Performance

deleteItem is inefficient,
because it iterates to the node to delete twice:
once to find the node to delete,
and then one more time to actually delete it.


Cache implementation had bugs

Actually your cache implementation would have helped except that you didn't quite write it correctly.

The t_cache.put() is in the wrong spot.  It should be outside the while loop since you don't know t until the loop finishes.
This function t_cache.containsKey(n) is actually returning false always.  You need to cast n to an int like this: t_cache.containsKey((int) n).  Otherwise since n is a long, it doesn't actually look up the right key.  I believe it is attempting to look up a Long key instead.

With this fixed up code, it runs 3.7x faster than without the cache:

public static int get14() {
    int max = 1;
    int ans = 1;
    Map<Integer, Integer> t_cache = new HashMap<Integer, Integer>();

    t_cache.put(1, 0);
    for (int i = 2; i < 1000000; i++) {
        long n = i;
        int t = 0;
        do {
            ++t;
            if (t_cache.containsKey((int)n)) {
                t += t_cache.get((int) n);
                break;
            }
            if (n % 2 == 0) {
                n /= 2;
            } else {
                n = 3 * n + 1;
            }
        } while (n != 1);
        t_cache.put(i, t);
        // System.out.println(i + "->" + t);
        if (t > max) {
            max = t;
            ans = i;
        }
    }
    return ans;
}

How to get even faster

Maaartinus already pointed out how to use bit operators to improve your speed.  Using the bit operators in addition to the HashMap cache improves the speed to 4.5x the original (from 3.7x, or a 22% speedup).  But this is still slower than just using the simple loop in maaartinus's answer (5.3x faster than original).

The problem is that the cache implementation can still be improved.

You don't need to call t_cache.containsKey() at all.  Since you are proceeding in order, the check if (n < i) will do the same thing, since you know that at any i, all the results below i have been found and cached.
You only need to check the cache in the "even" case, where n is decreasing.  In the "odd" case, n will increase so there is no chance that the cache will be hit.
You can use an array instead of a HashMap.  You are filling in the cache sequentially, so there is no reason for hashing.

So here is the final version with all of the improvements:

public static int get14() {
    int max = 1;
    int ans = 1;
    int [] t_cache = new int[1000000];

    for (int i = 2; i < 1000000; i++) {
        long n = i;
        int t = 0;
        do {
            ++t;
            if ((n & 1) == 0) {
                n >>= 1;
                if (n < i) {
                    t += t_cache[(int)n];
                    break;
                }
            } else {
                n = 3 * n + 1;
            }
        } while (true);
        t_cache[i] = t;
        if (t > max) {
            max = t;
            ans = i;
        }
    }
    return ans;
}

And here is the speed of each implementation:

Implementation                 Time    Speedup from original
---------------------------    ----    ---------------------
Original (uncached)            3.33           1.0x
HashMap                        0.90           3.7x
HashMap + bit ops              0.74           4.5x
maaartinus (bit ops)           0.63           5.3x
JS1 (Array cache + bit ops)    0.10          33.3x


Retrieving a message from a cryptocurrency daemon

I don't get the point where you cast null to object.

I'm not sure what are you trying to achive,
but you can always make if 'less ugly'.

$transcations_pool = json_decode($rpc->getTransactionPool(), false);
$transactions_pool = isset($transactions_pool->transactions) ?
                         $transaction_pool->transactions :
                         (object) null;

Also i would move div .show-grid to separate file and load it like this:

@include('path/to/file', [ 'transaction_json' => json_decode($transaction->tx_json) ])

Or you can implement special method like $transaction->decodeTxJson() to handle this decoding in $transaction class.


Calculator of combinations without repetition

One trick is to keep the partial products in small, \${n}\choose{k}\$ so they don't overflow.

I iteratively multiply \$n/(n-k)\$ by \$(n-1)/(n-k-1)\$, cache the result in an accumulator, multiply that by \$(n-2)/(n-k-2)\$ and so forth.

#include <iostream>

template <class T>
T choose(T n, T k)
{
    T accum = 1;
    T m = n;
    for (T i = 1; i <= m - k; i++)
    {
        accum = accum * n / (n - k);
        n--;
    }
    return accum;
}

int main()
{
    std::cout << std::fixed;
    long double n = 50, k = 25;
    std::cout << "\nLDBL_MAX" << LDBL_MAX;
    long double result = choose(n, k);
    std::cout << "\nC(" << n << "," << k << ") = " << result;
    std::cin.clear();
    std::cin.get();
    return 0;
}


Finding all intervals that match predicate in vector

Code Review

This piece

        Interval interval;
        interval.start = start_position;
        interval.end = end_position;
        intervals.push_back(interval);

can be transformed into

intervals.emplace_back(start_position, end_position);

Don't accept small objects by reference for read-only purposes. Although it usually doesn't hurt, in most implementations reference (which is implemented as pointer) will take up more space (compiler will probably inline the function or just pass by value though).
Algorithm. When there is a state which is represented by combination of flags and some metadata, flags usually go out of hand quickly. I would instead implement something like this:

1. Set previous, current to start of the input
2. previous = current
3. current = first index of element that is higher than threshold
4. if current - previous >= minlength, add to result
5. increment current
6. Go to 2

One could also create it the other way around, e.g. searching for those below threshold.

Alternative implementation

#include <vector>
#include <algorithm>
#include <type_traits>

using index_type = std::make_signed_t<std::size_t>;

struct interval {
    index_type first;
    index_type last;
};

bool operator==(const interval lhs, const interval rhs) {
    return lhs.first == rhs.first && lhs.last == rhs.last;
}

std::vector<interval> find_suitable_intervals(const std::vector<int>& input,
                                              const int threshold,
                                              const index_type min_length) {
    auto predicate = [threshold](int x) {
        return x <= threshold;
    };
    std::vector<interval> intervals;
    auto first = input.begin();
    auto previous = input.begin();
    auto current = first;
    while (current != input.end()) {
        previous = current;
        current = std::find_if_not(current, input.end(), predicate);
        if (current - previous >= min_length) {
            intervals.push_back({previous - first, current - first});
        }
        if (current == input.end()) {
            break;
        }
        ++current;
    }

    return intervals;
}

int main() {
    const int min_length = 3;
    const int threshold = 3;
    const std::vector<int> v { 4, 2, 1, 1, 4, 1, 2, 4 };

    const auto actual = find_suitable_intervals(v, threshold, min_length);
    const std::vector<interval> expected { {1, 4} };

    return actual != expected;
}

Wandbox Demo.

The logic got more "flat", but there are culprits of bridging STL style with more traditional style. Also, since incrementing iterator beyond end will cause undefined behavior, I had to put in the condition to check if the loop reached end. Mixing std::size_t and std::distance/difference will cause a warning and will require a cast to get rid of the warning, since one is unsigned and the other is not, thus I created index_type. There are rumors of std::index, but I wouldn't expect it in near future.

One could also make the condition an input into the function, e.g. predicate. Then it would look like this:

find_suitable_intervals(data, min_length, [threshold](auto x) {
    x < threshold;
});

Which is I believe is a bit more readable.


Class variables

Considering that neither the method nor the list of variables (plus what seems to be a missing private String[] lastLine) are static, I presume these belong to a class which requires instantiation for it to work.

This approach is fine - without knowing what else the class is doing - but I'm not too sure if currentWorkerLine (you have a currentWorkerline too, I'm going to assume that's just a small typo) and lastLine really needs to be 'saved' as class variables. For example, at the end of the method, is there a need to set lastLine = null?

Throwing Exceptions

The only checked Exception I can see from the method is just reader.readNext(), so you may want to replace the throws Exception part with the stricter throws IOException. This forces the method callers to explicitly deal with an I/O-related error, instead of an unusually wide Exception, which offers no (direct) hint as to what has gone wrong.

BTW, on a related note, if the code happens to deal with a malformed CSV input, the line currentWorkerLine = reader.readNext(); will cause NullPointerException should reader.readNext() return null. You may want to check for this, just to be sure.

Comparisons

While your code block is looping through the lines that have passed the identity check, there is no need to keep re-assigning relationIdentifier and currentStartDate:

while ((currentWorkerline = reader.readNext()) != null) {
    if (!isRelatedLine(currentWorkerline[0]) || !isCurrentDateLine(currentWorkerline[2])){
        lastLine = currentWorkerline;
        return workers;
    }
    // they will be the same as the past values, so why re-assign?
    //relationIdentifier = currentWorkerline[0];
    //currentStartDate = currentWorkerline[2];
    workers.add(currentWorkerline);
    lastLine = currentWorkerline;
    rowCount++;
}

Model classes

You may also want to consider having a suitable model class to give a better representation to the three-column row inputs you get over the current String[]. With a model class, you can have a custom equals() implementation that only compares the ID and date values between two 'instances' aka rows, so that the next different row will return false for the comparison. This may simplify not only your approach within the method here, but outside usage as well for the method callers to deal with the List of results.

Also, food for thought, would it be better/more efficient to return one Result object that contains an id, startDate and a List<String> of names, since the id and startDate are the same for all the names?


Strongly connected component algorithm in Python 2.7

1. Review

The code is not portable to Python 3 due to the use of the print statement.
The code is not organized into functions. This makes it hard to understand and hard to test.
Using a global variable (namely visitTimeCounter) makes code fragile (if the global variable starts out with the wrong value then it goes wrong) and hard to test (because you have to remember to reset the global variable each time you call it).
A graph node isn't the best choice of data structure here (it only has one attribute that you actually use, namely the list of its out-neighbours). A better data structure for this algorithm is a directed graph. A directed graph supports several methods that can be used by this algorithm: adding nodes and edges to the graph; iterating over the nodes; and getting the in- or out-neighbours of a node.

class Graph(object):
    """A directed graph. Nodes may be any hashable values."""

    def __init__(self, edges=()):
        """Initialize graph from optional iterable of edges."""
        self._out = defaultdict(set) # Map from node to its out-neighbours
        self._in = defaultdict(set) # Map from node to its in-neighbours
        for u, v in edges:
            self.add_edge(u, v)

    def add_node(self, u):
        """Add a node u to the graph."""
        self._out[u]
        self._in[u]

    def add_edge(self, u, v):
        """Add a directed edge to the graph, from node u to node v."""
        self.add_node(u)
        self.add_node(v)
        self._out[u].add(v)
        self._in[v].add(u)

    def in_neighbours(self, u):
        """Return the set of in-neighbours of the node u."""
        return self._in[u]

    def out_neighbours(self, u):
        """Return the set of out-neighbours of the node u."""
        return self._out[u]

    def __iter__(self):
        """Return iterator over the nodes of the graph."""
        return iter(self._out)

The constructor makes it very easy to create example graphs:

Graph('AB BA CD DC AC'.split())

(Compare this to the ten lines of code needed to create the graph in the post.)
To make the code for the algorithm easy to understand, it would make sense to closely follow the algorithm description. Wikipedia describes the algorithm like this:

  For each vertex \$u\$ of the graph, mark \$u\$ as unvisited. Let \$L\$ be empty.
  For each vertex \$u\$ of the graph do \$Visit(u)\$, where \$Visit(u)\$ is the recursive subroutine:
  If \$u\$ is unvisited then:

  Mark \$u\$ as visited.
  For each out-neighbour \$v\$ of \$u\$, do \$Visit(v)\$.
  Prepend \$u\$ to \$L\$.

  For each element \$u\$ of \$L\$ in order, do \$Assign(u,u)\$ where \$Assign(u,root)\$ is the recursive subroutine:
  If \$u\$ has not been assigned to a component then:

  Assign \$u\$ as belonging to the component whose root is \$root\$.
  For each in-neighbour \$v\$ of \$u\$, do \$Assign(v,root)\$.

which can be translated directly into Python like this:

def components(self):
    """Return list of strongly connected components."""
    visited = set()         # Set of visited nodes.
    L = []                  # Nodes in topological order.
    def visit(u):
        if u not in visited:
            visited.add(u)
            for v in self.out_neighbours(u):
                visit(v)
            L.insert(0, u)
    for u in self:
        visit(u)
    component = defaultdict(set) # Map from root to its component.
    assigned = set()       # Set of nodes assigned to a component.
    def assign(u, root):
        if u not in assigned:
            component[root].add(u)
            assigned.add(u)
            for v in self.in_neighbours(u):
                assign(v, root)
    for u in L:
        assign(u, u)
    return list(component.values())

It's much easier to compare and check this kind of directly translated code against the algorithm description than it is to check the more complicated translation in the post.

(Note that the directly translated code above has the correct functionality, but not the right complexity: inserting an item at the beginning of a list with L.insert(0, u) is inefficient (it takes time proportional to the length of the list). We can fix this by adding nodes to the end of the list instead (which is efficient). This requires three changes. First, the comment becomes:

L = []           # Nodes in reverse topological order.

Second, L.insert(0, u) becomes L.append(u). Third, the iteration over the list L proceeds in reverse order:

for u in reversed(L):

If you don't like the idea of maintaining this list in reverse order, then an alternative would be to switch L from a list to a collections.deque, which has an efficient appendleft method.)

Some quick tests:

>>> Graph('AB BA CD DC AC'.split()).components()
[{'D', 'C'}, {'B', 'A'}]
>>> Graph('AB BC CD DA AE FB DG'.split()).components()
[{'D', 'B', 'C', 'A'}, {'E'}, {'F'}, {'G'}]
>>> Graph('AB BC CD DE'.split()).components()
[{'D'}, {'B'}, {'E'}, {'C'}, {'A'}]

2. Answers to questions

() is the empty tuple. See the documentation.
Your (1) is correct. If there is a directed edge from \$u\$ to \$v\$, then \$u\$ appears before \$v\$ in the list \$L\$ (unless \$u\$ and \$v\$ belong to the same strongly connected component, in which case they could appear in either order).

But in your (2), I think you have been confused by the wording of the sentence you quoted. When Wikipedia says,

  either way \$v\$ will be prepended to \$L\$ before \$u\$ is

what it means is,

  either way \$v\$ will be prepended to \$L\$ at an earlier time than \$u\$ is prepended to \$L\$.

In other words, if there is a directed edge from \$u\$ to \$v\$, then when step 2 is complete, \$u\$ appears before \$v\$ in the list \$L\$. Hence this has the same interpretation as your (1).
The "in-neighbours" of a node \$u\$ are the nodes \$v\$ such that there is an edge from \$v\$ to \$u\$. So the in-neighbours are the set of nodes that can be reached from \$u\$ by following one edge in the reverse direction.


Codechef COOKMACH solution, exceeding time limit

if(A%2!=0){
        if(A<B){
            while(A!=1){
                A=(A-1)/2;
                count=A;
            }

This looks like a bug.  Consider the case where A is 5 and B is 8 or more.  A is odd, less than B, and not equal to 1, so it enters the while loop.  First iteration A becomes 2.  Second iteration we have \$(2-1)/2\$ which rounds down to become 0.  Since 0 is not equal to 1, we loop again and have \$(0-1)/2\$ which rounds off to 0 (negative fractions rounds up, towards zero).  But now we're back to 0.  So it loops endlessly.

This is why I would recommend saying A > 1 rather than A != 1.  Then you would have returned an answer (possibly wrong) quickly rather than gotten Time Limit Exceeded.

The worst part is that this is unnecessary.  Integer arithmetic would have handled this correctly.  You don't need to check for odd numbers.  Normal integer arithmetic already rounds down.

The count=A; is also wrong.  You'd want to increment count here as well, not set it to 1.

You also don't correctly handle values for A like 6.  It's not odd, but it's not a power of two either.  You should reduce it to 1, but you won't so long as it is less than B.  Instead you'll endlessly double it until the program crashes.


Some thoughts from a non-game-developer:

The second and subsequent if lowestKey should use elif to short-circuit the evaluation when it finds a match.
I believe algorithms such as A* (A-star) are very well suited to find the shortest path between two points on a 2-dimensional map.
Running this code through a linter such as flake8 will show how to make your code more pythonic.


Plugin for showing cross-sells on the single product page in WooCommerce

The code looks ok to me from a security point of view. You're not accessing the database directly and it looks like you are escaping the output ( assuming that the template part does the same ).

A couple of suggestions:

Instead of looking for the filename in the list of active plugins, use function_exists or class_exists to check to see if the plugin is enabled by looking for a function or class defined by the plugin. The reason being that options can be cached and filenames can be changed. Function/Class names rarely change and it's much cleaner looking.

if ( class_exists( 'WC_Query' ) ) {
    // Your plugin code.
}

Check to make sure that you're actually getting data returned in $crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true); before using it in the query. If there is no data, there's no point in querying the database.

// Put this before the query
$crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true);
if ( empty( $crosssells ) {
    return;
}

WP_Query will always return something and so if( $products ) will always be true. Use if( $products->have_posts() ) instead. This will only return true if there were posts returned from the query.

To answer your question, the while loop is fine. That's what WordPress core and the bundled theme use.

The only other suggestion I would make is for performance. Add a couple of items to your query args:

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 4,
        'post__in' => $crosssells,

        /**
         * If you're not paginating, this skips MYSQL_CALC statments
         */
        'no_found_rows' => true,

        /**
         * Skips updating meta cache
         */
        'update_post_meta_cache' => false,

        /**
         * Skips updating term cache.
         */
         'update_post_term_cache' => false,
    );

Hope it helps!


'iplayer' style content accordion/slider

I'd normally suggest you post this on StackOverflow  as it doesn 't work properly.

Firstly:

You have the same two functions repeated over and over .... don't.  Put them in one big selector.

$('#accordion > li.bg1 .heading, #accordion > li.bg2 .heading, a.see-more-p, #accordion > li.bg1 .heading-side').toggle

You have two headings for each. Semantically this is wrong. change your .heading-side to .heading.side. then all you need is an addClass('side'); and removeClass('side');
also you will need:

ul.accordion li .heading.side .right{ display: none; }

to hide the >.
To get the fadeIn/Out:

.fadeOut(500).queue(function(next) {
    $(this).addClass("side");
    next();
}).fadeIn(500);

That looks confusing with the .queue(... but that's just to make sure it happens between the fading so the user doesn't see any oddness.
The toggle only toggles for that specific context (i.e. the element being clicked) so it will toggle for each element, hence the double clickyness.
My solution is to roll your own toggling:

$(function() {
    var first = true;
    $('#accordion > li.bg1 .heading, #accordion > li.bg2 .heading, a.see-more-p, #accordion > li.bg1 .heading-side')
    .click(function() {
        if (first) {
            //do first stuff
        }else{
            // do second stuff
        }
        first = !first; // < --- Toggling done here!!!!
    });
});

Viola! see jsFiddle for my awesomeness!


Your spacing is all over the place, and the double null check against userDAO seems redundant.

I'm not making a comment on the big picture on whether or not the singleton is necessary, but I'd certainly fix getRAMUserDAO() up to look more like this:

public static RAMUserDAO getRAMUserDAO() {
    synchronized (RAMUserDAO.class) {
        if (userDAO == null) {
            userDAO = new RAMUserDAO();
        }
        return userDAO;
    }
}

The Egyptian-style braces are just my general preference.  I don't know if there's a Java standard for how to do the braces.


Neatly printing integers interspersed with spaces - follow-up

Style
Why make the delimiter an input parameter, but not the group length (3)? The DEFAULT_DELIMITER_CHAR is also... out of place, either you have DEFAULT values for both, or you have for none, but the mixed concept is cumbersome.
Apart from that incongruity, the code is otherwise really quite neat, and understandable.
For what it's worth, I tend to use magic numbers, and not constants, when confronted with these situations. I am aware that magic numbers are not generally welcomed, but your code here:

public static String neatify(final long number) {
    return neatify(number, DEFAULT_DELIMITER_CHAR);
}

is really not much better, or perhaps even worse, than:
public static String neatify(final long number) {
    return neatify(number, ' ');
}

That's a personal thing.
Algorithm
I dislike the char-by-char algorithm you have chosen. The reason is that, as I see it, you are working in an "arse-backwards" way. The problem is about right-referenced values. The groups-of-3 blocks are referenced to the right-side of the value, not the left, so the trick is getting the reference correct to start with, and then you don't have to play tricks to keep it correct.
The trick is to find the right 'start' point that's correct, relative to the right, but then referenced from the left... let me explain:
    final String raw = Long.toString(val);
    int end = raw.length() - span * ((raw.length() - 1) / span);
    int start = 0;

What does the above code do? It converts the long input value to a string without any spaces. It uses the length() and from that, it subtracts the full number of blocks that have to be padded.
So, the following table gives the 'input' and 'end' result:
1         -> 1
12        -> 2
123       -> 3
1234      -> 1
12345     -> 2
123456    -> 3
.....

So, the start position for the first group is at char 0, and the end position is calculated above. From there on, it is just a simple case of getting the next group, and so on.
The full code I would recommend is:
public static String neatify(final long val, final char pad, final int span) {
    if (val == Long.MIN_VALUE) {
        long minblock = (long)Math.pow(10, span);
        // recursive hot-fix for otherwise impossible-to-make-positive value.
        return neatify(val / minblock, pad, span) + pad + neatify(-(val % minblock), pad, span);
    }
    if (val < 0) {
        return "-" + neatify(-val, pad, span);
    }

    final String raw = Long.toString(val);
    int end = raw.length() - span * ((raw.length() - 1) / span);
    int start = 0;
    StringBuilder sb = new StringBuilder(raw.length() + (raw.length() / span) + 1);
    while (start < raw.length()) {
        sb.append(pad);
        sb.append(raw.substring(start, end));
        start = end;
        end = start + span;
    }
    return sb.substring(1);
}

Note that, for this system, I have enabled all three input parameters, and I have done some simple 1-level-down recursive tricks to handle negative values (and Long.MIN_VALUE which is a PITA).
Update - Performance
Since the question was edited to include performance as a criteria, then the following code will do essentially the same as above, but with some performance tweaks:

it won't use recursion for negatives, but instead do some more complicated sign-juggling
it keeps everything as primitives (chars, etc.) instead of Strings
it pre-computes the output sizes, etc.

It is still referenced against the right-side of the output, and has the same basic concepts, just... faster. About twice as fast, and about 20% faster than the OP's...
public static String neatifyRLP(final long val, final char pad, final int span) {
    final String raw = Long.toString(val);
    final int signlen = val < 0 ? 1 : 0;
    final int digitlen = raw.length() - signlen;
    final char[] out = new char[signlen + digitlen + (digitlen - 1) / span];

    int pos = out.length - 1;
    int src = raw.length() - 1;
    final int ospan = span + 1;
    while (pos >= signlen) {
        out[pos] = (out.length - pos) % ospan == 0 ? pad : raw.charAt(src--);
        pos--;
    }
    if (val < 0) {
        out[0] = '-';
    }
    return new String(out);
}

I am not at all certain that it is more readable, but, it is not horrible either.
Here are the performance numbers based on neatifying 1000 random long values:
Task NumberPad -> OP: (Unit: MILLISECONDS)
  Count    :    10000      Average  :   0.2202
  Fastest  :   0.1960      Slowest  :   9.8499
  95Pctile :   0.2927      99Pctile :   0.4620
  TimeBlock : 0.265 0.222 0.222 0.215 0.218 0.217 0.217 0.208 0.206 0.211
  Histogram :  9769   218     7     1     4     1

Task NumberPad -> RL: (Unit: MILLISECONDS)
  Count    :    10000      Average  :   0.3524
  Fastest  :   0.3127      Slowest  :  15.0630
  95Pctile :   0.5521      99Pctile :   0.6260
  TimeBlock : 0.416 0.368 0.360 0.340 0.366 0.347 0.330 0.334 0.328 0.335
  Histogram :  9900    88     6     2     3     1

Task NumberPad -> RLP: (Unit: MILLISECONDS)
  Count    :    10000      Average  :   0.1866
  Fastest  :   0.1683      Slowest  :   5.9859
  95Pctile :   0.2280      99Pctile :   0.4241
  TimeBlock : 0.218 0.189 0.193 0.181 0.185 0.185 0.177 0.178 0.179 0.182
  Histogram :  9826   165     3     2     2     2


Found a solution and I think this is elegant, but I'm unsure if this is something that should be avoided or not since I'm fairly new to ES6.

Here are the following things I did to refactor it:

Unify the Builder signatures to use a single parameter product
Invoke the parent constructor within the child constructor with the same arguments on the instance.
Move the defaults into the build step of the Builder.
Use Object.assign to merge new properties.

There's a bit more that can be done to clean this up even further, but hopefully, this could be useful for someone else. One could repeat step 2 to include multiple Builders as well.

function ParticleBuilder(product) {
  MoveableBuilder.call(this, product);
  this.lifespan = (lifespan) =>
    new this.constructor(Object.assign({}, product, {
      lifespan: lifespan
    }));

  this.decay = (decay) =>
    new this.constructor(Object.assign({}, product, {
      decay: decay
    }));

  this.build = () => Object.assign({
      lifespan: 255,
      decay: 1
    },
    product);
};

function MoveableBuilder(product) {
  this.at = (...coordinates) =>
    new this.constructor(Object.assign({}, product, {
      coordinates: coordinates
    }));

  this.facing = (...vector) =>
    new this.constructor(Object.assign({}, product, {
      vector: vector
    }));

  this.build = () => Object.assign({
    coordinates: [],
    vector: []
  }, product);
}

console.info(new MoveableBuilder().at(1, 1).facing(2, 1).build());

console.info(new ParticleBuilder().at(1, 1).build());


What if you have 167 hotels? Would you copy/paste the code for all those hotels? I don't think you would.
Start with making the script more general, so you have only to feed the data into the function.

var hotel=new Array;
hotel[1] = {Name: "Park Hotel", Price: "£120.00", Rooms: 50, pict: "pict1"}
hotel[2] = {Name: "West End", Price: "£240.00", Rooms: 150, pict: "pict2}

(make sure you use the same keys all the time")

Now you can feed that into a function:

function showHotel(hotelnumber){
   var hoteldata=hotel[hotelnumber];
   document.getElementById['name'].innerHTML=hoteldata['Name'];
   document.getElementById['price'].innerHTML=hoteldata['Price'];
   // etc etc etc
   }

Inside the function you have all the elements you need to display the hotel information. Replace the content of all the elements (give your divs id's!) like name, price, rooms and the picture.

If you want to display a hotel, call the function with

showHotel(11);


Self-modifying esoteric language interpreter in Ruby

I would suggest refactoring the switch. This would make scaling easier

   def remove_callback
     @code.slice!((@i + value(line[1]))..(@i + value(line[2])))
   end

   ...

   line = @code[@i].split " "
   self.send("#{line[0]}_callback")


Creating a ModelBinder to Sanitize user input in HTML format

Developer gone 'rogue'

  I am not entirely happy with this code. The reason is, in the future, a developer may forget that HtmlSanitizerFactory should be used for
  instantiating HtmlSanitizer... so he would create his new ModelBinder
  ..

For this to happen, a developer has to dive in your code and deliberately change

private HtmlSanitizer _htmlSanitizer = HtmlSanitizerFactory.CreateInstance();

to

 private HtmlSanitizer _htmlSanitizer = new HtmlSanitizer();

He would probably have a good reason to. And if not, other developers in the team should review and challenge that change. After all, it's best practice to perform code reviews, typically with pull requests.

Test-Driven Development

You have introduced a dependency on a third-party class in your code. Generally, when providing such API code, you would like to reduce the hard dependencies to a minimum. What you could do, is use its interface IHtmlSanitizer instead. This allows for white-bow testing such as

string unsanitizedMessageHtmlString = ".."; // some input
IHtmlSanitizer sanitizer = Mock<IHtmlSanitizer>(); // using some mock method ..
sanitizer.AssertWasCalled(m => m.Sanitize(unsanitizedMessageHtmlString));

You could go a step further and refactor out the third-party dependency entirely by providing your own interface. An adapter class mapping the third-party interface to yours can than be provided in a different library if you wish interop with that API. I am not suggesting this is a must. You should decide which dependencies you want to include in your own API.

Regression

  But it is likely that a year from now, we need to developer a new model binder to sanitize a different HTML input. It is at that point
  that the developer could forget to initialize the sanitizer using the
  factory.

In the comments you stated you are worried for new developers to use that class in a wrong way, possibly introducing bugs. These bugs should become apparent when providing unit tests. With white-box tests you can check whether PostProcessNode was registered to. And with black-box tests you could easily verify the content of the sanitized string.

It also wouldn't hurt to provide a team Wiki with guidelines, do's and dont's for new developers to get acquainted with the conventions and avoidable regressions.

Dependency Injection

Instead of calling the factory to get an instance of HtmlSanitizer, you should use Dependency Injection. One way to do so is to have the dependency injected through the constructor.

public AllowAndSanitizeHtmlBinder(IHtmlSanitizer htmlSanitizer)
{
    _htmlSanitizer = htmlSanitizer;
}

You would typically have an Ioc container where you register the dependencies. I don't know enough about the IModelBinder's lifetime scope, so you may also want to register these to the container.

container.RegisterSingleInstance<IHtmlSanitizer>(HtmlSanitizerFactory.CreateInstance());

Resource Management

I don't like the third-party class HtmlSanitizer. The events are never cleared and the class does not implement IDisposable. It's a memory leak waiting to occur. You need to find a way to dispose these instances yourself and make sure to unsubscribe from:

 sanitizer.PostProcessNode += (s, e) =>  (e.Node
     as IHtmlAnchorElement)?.SetAttribute("red", "nofollow noreferrer");


Simple code to check format of user inputted email address

My preference for accepting user input in a blocking loop like this might look more like:

  public enum Returned { OK, ERROR_EMAIL };

…

  // Long loop here to get valid user registration info.
  /* In a transactional/event-driven (GUI, web) app this would not be
   * a loop, but with a blocking/modal (tty) program it works. */

  UserInfo u = new UserInfo ();
  // loop until you get valid one(s)
  while (!u.isReady()) {

    // for each field that must be validated, prompt and try to set it
    if (u.getName () == null) {
        System.out.print ("Enter an eMail address:");
        String entered = scanner.nextLine ();

        Returned settingName = u.setName (entered);

        // check each object's validity and report errors
        switch (settingName) {
            case Returned.OK:
                  System.out.println ("OK.");
                  break;
            case Returned.ERROR_EMAIL:
                  System.out.println ("That does not look like a valid eMail address.");
                  break;
             // No "default": if you add new error types later, you can handle them here.
             // The compiler will issue a warning about unhandled enum cases
        }
     }
  }

…and then in class UserInfo …

  final static Pattern rfc2822 = Pattern
                            .compile ("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");

  public Returned setName (final String address)
  {
       Returned valid = isValid(address);
       if (Returned.OK == valid) { this.name = address; }
       return valid;
  }

  public boolean isValid (final String address)
  {
         return ( (rfc2822.matcher(address).matches ())
                  ? Returned.OK : Returned.ERROR_EMAIL );
         // you could also check for a valid MX record for the domain part…
  }

  public boolean isReady () {
         return name != null; // and whatever else
  }


Slow delete query on table with composite index

Oracle uses the following strategy when deleting data. It:

identifies the rows that need to be deleted (it does use your PRIMARY KEY index to check the RUN_ID value, but because the RUN_ID is not the first column in the index it needs to 'skip' values in the index).
it deletes the record in the online version of the data
it writes a physical record to the transaction / redo log to record the values that were deleted

Oracle works on a per-block bases for it's redo log:

  A redo record, also called a redo entry, is made up of a group of change vectors, each of which is a description of a change made to a single block in the database

Each time you change a record, the block it is stored in is changed, and the difference is recorded in the redo log. The number of blocks you change is a key factor in determining the amount of redo-log work that you do. The number of blocks is closely related to the amount of data you are changing, and the way that the data is distributed.

If you are deleting a bunch of records that are all stored really close to each other, then the chances are that the number of blocks that are affected will be small. If the records are scattered on many blocks, then the number of blocks affected is high.

Based on the key you have specified for your data "DEAL_ID", "RUN_ID" it appears to me that your data for a specific RUN_ID will be scattered all over the database.

This means that, for each time you delete the data, you are actually inserting 400,000 redo-log entries, modifying 400,000 blocks of storage (let's say 8K each, so that's 3GB of IO), and generally processing the system quite hard.

So, apart from the basic problem of deleting 400K records, and inserting 400K redo-entries, and writing all that data to disk, what else could it be?

Locks will likely need to be escalated. Oracle will start by trying to lock the records one at a time, but will quickly find that the lock-management requires a bigger lock strategy, so it make replace the row-locks with block-locks, and then finally escalate the block locks to a full table lock. In itself, this is not a significant performance problem, but what is a problem is if anyone else is running anything against the table.... the lock escalation will have to wait until all other locks on the table are serviced. Only then will it gain exclusive access.

Ways to improve the performance would be:

monitor the database. Confirm that IO is a real problem
monitor the lock strategies... are there significant lock-wait situations.
reduce the logging requirments...  physically order the data in the same order as the RUN_ID. you can 'cluster' the data, or, in Oracle terms, you can have "index organized table". Much fewer blocks will change with this.
improve the log-device performance - put your log files on an SSD?


Concise code to perform action on every element, when need index

linqObject.Where((obj, index) => {
  DoWork(obj, index);
  return true;
}).ToArray();

Never ever! This is the worst possible abuse of an API. I 100% agree with the comment.

int index = 0;
foreach (var item in someEnumerable) {
    DoWork(item, index);
    index++;
}

Yes, this is the way it should be, although this can be shortened... keep reading.

public static void ForEachWithIndex<T>(IEnumerable<T> e, Action<int, T> a)
{
    int index = 0;
    foreach (T v in e) {
        a(index, v);
        index++;
    }
}

This is better but the naming is still quite wrong and the Action parameters are in the wrong order. They should be incremental. This means that T is always there so it should be first, then any other parameters may follow, like the index.

I'm not sure what's wrong with using normal loops where necessary but if you really want to encapsulate them then...

Try to be consistant with the LINQ API and don't invent new method suffixes like WithIndex. Use overloads instead. In fact you can implement it once and call the core method with other overloads.

Notice the order of Action parameters. It's consistant with current APIs. T first then index. There is also no explicit parameter checking because it uses an empty collection if the source is null and the ? operator to not call the delegate if this one is null. You can also throw if you want.

public static class Loop
{
    public static void ForEach<T>(IEnumerable<T> source, Action<T, int> action)
    {
        var i = 0;
        foreach (var item in source ?? Enumerable.Empty<T>()) action?.Invoke(item, i++);
    }

    public static void ForEach<T>(IEnumerable<T> source, Action<T> action)
    {
        ForEach(source, (x, i) => action(x));
    }
}


From the outset the code looks ok. I would leave the Change and Query methods inside the class.

If the class does get abit too much then partial the class into sensible files. Also, as a side note, look up SOLID it will help you to break down and structure your code if appropriate.