Find select values on one worksheet and copy to a second

First - nice job declaring all of your variables. The naming could use a little work (sourceRange, applianceQuantityArray). Declaring several on the same line and giving them both a type (below) - A+

Dim i As Long, j As Long

A few standard blurbs -

  Always turn on Option Explicit. You can have it automatically by
  going to Tools -> Options in the VBE and checking the Require
  Variable Declaration option. This way if you have any variables not
  defined, the compiler will let you know.

  Worksheets have a CodeName property - View Properties window
  (F4) and the (Name) field (the one at the top) can be
  used as the worksheet name. This way you can avoid Sheets("mySheet")
  and instead just use mySheet.

  Standard VBA naming
  conventions
  have camelCase for local variables and PascalCase for other
  variables and names.

I do want to talk about a few variables though-

Dim j as Long
Dim target as String
Dim i as Long
Dim source as String
j=4
>loop i
   target=j
   source = i+4
   j=j+1
>end loop

This seems pretty unnecessary. I'll take this -

 Range("B" & target) = Worksheets("Calculator").Range("F" & source) & " units"

to mean that you thought you need to use a string to put into a range format. You don't. This does the same thing (i being arbitrary) -

Dim i As Long
For i = 1 To 10
    Sheet1.Range("B" & i + 3) = Sheet1.Range("F" & i + 4).value & " units"
Next

You'd probably benefit from just using the .Cells(row, col) format instead. But I digress.

Using an array

As you yourself have pointed out, using an array would be faster. It's always faster. Your loop is really difficult to read -

Range("H" & target) = "=H" & target - 1 & "-" & Worksheets("Calculator").Range("L" & source)

(You're subtracting 1 from a String you realize?) It's the same as this -

 Sheet1.Cells(target, 8).value = Sheet1.Cells(target - 1, 8) - calcSheet.Cells(source, 12)

In the most basic way, say you take everything you need into an array

Dim calcArray As Variant
calcArray = calcsheet.Range(calcsheet.Cells(5, 3), calcsheet.Cells(22, 13))
For i = LBound(calcArray) To UBound(calcArray)
    If calcArray(i, 4) <> vbNullString Then

Pretty simple yeah? Just use the 2nd dimension of the variant to specify what column you're targeting (see I started at column 3 (C) so I had to use 4 (F).

Looks to me like you would need an array from the other sheet too, something like

Dim targetArray As Variant
targetArray = Sheet1.Range(Sheet1.Cells(4, 6),Sheet1.Cells(UBound(calcArray) - 1, 9))

And then maybe you make a results array

Dim resultsArray As Variant
ReDim resultsArray(1 To UBound(calcArray), 1 To 3)

Now you can (roughly, this isn't perfect)

For i = LBound(calcArray) To UBound(calcArray)
    If calcArray(i, 4) <> vbNullString Then
        resultsArray(i, 1) = targetArray(i - 1) - calcArray(i, 8)

Populate that results array using what is essentially range("F5").offset(,-1) but in the array.

Then it would need to be printed back out. A few of them come straight from the calcArray hence I didn't make room in the resultsArray but you could.

Anyway, since the range is weird to me you'd just need to adjust it as you like. Or just declare your arrays starting in row 1 and change nothing.


With regards to your code, the only comments I have are that lo and hi may be better names than up and down, and that you probably should have a more specific name than search. As to why you don't see this in the wild, the biggest reason is that Step-wise Linear Search is almost always faster, and simpler to implement. step-wise linear search takes 2n steps to complete, has no recursion, and uses no memory. quad-partitioning, on the other hand, is more complicated, has worse complexity (n^ln(3) vs 2n), and has worse constant factors (due to more branching, and recursion).


Find sequence to a target number using restricted set of primitive operations

using namespace std;
Stop doing this.  It is a easy, but sloppy, way to code; a change to the standard library that introduces a new identifier can break your code.
Being explicit, and writing std::vector instead of vector everywhere would be painful.  But there is a middle ground:
#include <vector>
using std::vector;

Now you can lazily use vector, without fear that something you are not using from the standard library will suddenly become defined, colliding with your identifiers, and causing carnage.
White space
Either put white space around all binary operators, like v[i + 1], or never put the white space around the binary operators, like v[i*2].  But be consistent.
cout << endl;
Don't use this; it slows your code down.  The endl manipulator does two things: it adds \n to the stream AND it flushes the stream.  If you don't need to flush the stream (and you rarely do), simply write
cout << '\n';

Avoid repeated calls to functions that return the same result
for(int i = 1; i < v.size(); i++)

What is the value of v.size()?  Will it ever change?  Can the compiler tell it won't, and optimize it out?  Could you store the value in a local variable to avoid the repeated function calls?
Or ... you could use the variable that already exists: n.
for(int i = 1; i <= n; i++)

Don't Repeat Yourself (DRY)
        if((v[i + 1] == 0) || (v[i + 1] > v[i] + 1))
        {
            v[i + 1] = v[i] + 1;
        }
        if((2*i <= n) && (v[2*i] == 0 || v[2*i] > v[i] + 1))
        {
            v[2*i] = v[i] + 1;
        }
        if((3*i <= n) && (v[3*i] == 0 || v[3*i] > v[i] + 1))
        {
            v[3*i] = v[i] + 1;
        }

These statements look very similar.
        if((target <= n) && (v[target] == 0 || v[target] > v[i] + 1))
        {
            v[target] = v[i] + 1;
        }

You could pull them out into a function:
inline void explore_step(vector<int> &v, int n, int i, int target) {
    if ((target <= n) && (v[target] == 0 || v[target] > v[i] + 1)) {
        v[target] = v[i] + 1;
    }
}

And then write:
        explore_step(v, n, i, i+1);
        explore_step(v, n, i, i*2);
        explore_step(v, n, i, i*3);

Optimization
You approach takes \$O(n)\$ time, because you explore each value from 1 to n.
You do this, because you don't know which values are going to be useful in reaching the target value, and test things like v[2*i] > v[i] + 1 because you don't know which values could be reached via a faster path.
A slightly better approach:

seed 1 into a list of values to explore
for each value in the list of values to explore:

for each of the 3 target values i+1, i*2, & i*3 if <= n:

if v[target] == 0, then

store v[target] = i
add target to the list of values to explore
if target == n, stop

Consider n = 10.
explore = [1], value = 1, targets = [2, -, 3]
explore = [1, 2, 3], value = 2, targets = [-, 4, 6]
explore = [1, 2, 3, 4, 6], value = 3, targets = [-, -, 9]
explore = [1, 2, 3, 4, 6, 9], value = 4, targets = [5, 8, -]
explore = [1, 2, 3, 4, 6, 9, 5, 8], value = 6, targets = [7, -, -]
explore = [1, 2, 3, 4, 6, 9, 5, 8, 7], value = 9, targets = [10, -, -]

You could use a queue for explore, but a vector of length n, and just walking forward through the items works fine.
Notice that all values reachable after 1 step [2, 3] are processed before values reachable after 2 steps [4, 6, 9], and would be processed before those values reachable after 3 steps [5, 8, 7], and so on.
More over, we've built up a trail of breadcrumbs for the fastest path.
v[10] = 9
v[9] = 3
v[3] = 1

So no searching is required to find the correct path.
Implementation left to student.

Can we do better?  What if we started with n, and explored n-1, n/2, and n/3?  An odd value can't lead to an n/2 point, and a non-multiple-of-3 can't lead to a n/3 point, so you may be pruning more values out of the search, so might be slightly faster.
[28] -> [27, 14]
     -> [26, 9, 13, 7]
     -> [25, 13, 8, 3, 12, 6]
     -> [24, 12, 4, 2, 1!, ....]


Python binary to decimal converter (without using built-ins)

This algorithm could pretty easily be converted to a one-liner.  Let's walk through the logic:

You want to work over each element of a string.  You can just iterate over the string, rather than keeping track of an index.
You also need the index of that element, so you can use enumerate to get both.
You want to apply a mathematical operation if and only if the integer is not 0.  This can be done using int(val), which converts the value to the number it represents.
You want to add all the values at the end.  This can be done with sum.

To get error checking, you can convert the string to a set, and make sure the set is equal to a set with only 0 and 1 in it.

Also, you probably want the input handling in a while loop to avoid the recursion, which will fill up your memory, and then have a separate function to handle the actual conversion.

Also, I would only run main if the code is run as a script.

And keep in mind python has a built-in way to do binary to decimal conversion: int(binstr, 2), which can be used to test your implementation at the very least.

So here is how I would implement it:

def bin2int(binstr):
    if set(binstr) != {'0', '1'}:
        raise ValueError('String is not binary: "%s"' % binstr)

    return sum(int(x)*2**i for i, x in enumerate(a[::-1]))

def main():
    while True:
        binary = input("Enter a line of binary, enter 'q' to quit: ")

        if binary.lower() == 'q':
            break

        try:
            print(bin2int(binary))
        except ValueError as err:
            print(err)

if __name__ == "__main__":
    main()


Morgan and a String HackerRank challenge

This is an improvement on @Toby's answer

Instead of str += char which allocates a new string you can yield the result and "".join() it later on

Here's the problem: consider "BAB", "BAC". One would think to compare the two strings, see that BA->B is more minimal than BA->C. or you see that BA->B(end of string) is shorter than BA->(jump to other string)BA. Both of these are wrong, because we end up with BABBAC, instead of BABABC, which is more minimal (BABA < BABB).
The z fixes things because it fixes the issue where we incorrectly choose BA->B\0 over BA(first stack)->(other stack)BA. BA->BA < BA->Bz. Realistically what we should do during tiebreakers is jump to the other stack when one ends so we are comparing against BABB instead of BABz, but the z solution is faster.

Normally with the "z" fix you need to remove them from the end result, but because any uppercase char is lower then the lowercase "z" we know after len(a) + len(b) - 2 iterations only the 2 "z" strings remain in the resulting string. thus we only need to loop len(a) + len(b) - 2 times

Improved code
def morgan(a, b):
    a += "z"
    b += "z"
    for _ in range(len(a) + len(b) - 2):
        if a < b:
            yield a[0]
            a = a[1:]
        else:
            yield b[0]
            b = b[1:]

def morgan_and_string(a, b):
    """
    Return the lexicographically smallest string formed from the input strings, keeping each string
    in order in the result.

    Same length
    >>> morgan_and_string("ACEG", "BDFH")
    'ABCDEFGH'
    >>> morgan_and_string("ABCD", "ABCD")
    'AABBCCDD'

    Empty input
    >>> morgan_and_string("ABCD", "")
    'ABCD'
    >>> morgan_and_string("", "ABCD")
    'ABCD'

    Different length
    >>> morgan_and_string("Z", "ABCD")
    'ABCDZ'
    >>> morgan_and_string("ABCD", "Z")
    'ABCDZ'

    Descending strings
    >>> morgan_and_string("BA", "BA")
    'BABA'

    >>> morgan_and_string("ZAX", "ZAY")
    'ZAXZAY'
    >>> morgan_and_string("ZAY", "ZAX")
    'ZAXZAY'

    Proper prefix
    >>> morgan_and_string("BABC", "BA")
    'BABABC'
    >>> morgan_and_string("CABC", "CA")
    'CABCAC'
    >>> morgan_and_string("BAAC", "BA")
    'BAABAC'
    """
    return "".join(morgan(a, b))

if __name__ == '__main__':
    import doctest
    doctest.testmod()


Simple: Need help refactoring this awkward looking method

You could use scopes to do this at the database level, which would (potentially) be much faster than returning then iterating over all ActivityFeedEvents.

# ActivityFeedEvent
scope :by_type, ->(type){ where(type: type.to_s) }
scope :recent, ->{ where("event_date > ?", Time.now - 7.days) }

# wherever report_total is
def report_total(feed_event_type, advisor)
  advisor.activity_feed_events.by_type(SignupFeedEvent).count +
    advisor.activity_feed_events.recent.by_type(feed_event_type).count
end

Note that you need a lambda for the recent scope despite it not taking args, because otherwise the Time.now will only be evaluated once (when the server starts).

Or, perhaps even more neatly, you could do it the other way round:

# ActivityFeedEvent
scope :for, ->(advisor){ where(advisor_id: advisor.id) }
scope :recent, ->{ where("event_date > ?", Time.now - 7.days) }

# wherever report_total is
def report_total(feed_event_type, advisor)
  SignupFeedEvent.for(advisor).count + feed_event_type.for(advisor).count
end

Depending on your models you may need a more descriptive name than for for this one, belonging_to or for_advisor are candidates.

Also note that some people prefer to write scopes as class methods instead of using lambdas

# ActivityFeedEvent
def self.for(advisor)
  where(advisor_id: advisor.id)
end

def self.recent
  where("event_date > ?", Time.now - 7.days)
end


You can rewrite your asserts without comparing to True and False:

assert is_pandigital(1423, 4)
assert not is_pandigital(1423, 5)
assert is_pandigital(14235554123, 4)
assert not is_pandigital(14235552222, 4) # !important
assert not is_pandigital(1444, 4)
assert is_pandigital(123564987, 9)

You can rewrite your benchmark with list comprehension:

# this loop is strictly for benchmarking is_pandigital
pandigitals = [i for i in range(100000, 999999) if is_pandigital(i, 6)]

Now for the algorithm itself, I must confess that I have troubles understanding what you want to do as you seem to be calling "pandigital" two different things. In any case, I have the feeling that something is wrong in your code, it seems like :

   if str(i) not in nr[0:9]:
        return False
    if str(i) not in nr[-9:]:
        return False

should be

    if str(i) not in nr[0:n]:
        return False
    if str(i) not in nr[-n:]:
        return False

and

assert not is_pandigital(9999912399999, 3)

should provide you some hints.

I'll go deeper in the code once you confirm that my understanding is correct.

Edit : I have to go, no time to run benchmarks but here are the improvements. I kept different versions to that you can take ideas out of it.

def is_pandigital(nr, n):
    nr = str(nr)
    beg=nr[0:n]
    end=nr[-n:]
    for i in map(str, range(1, n + 1)):
        if i not in beg or i not in end:
            return False
    return True

def is_pandigital(nr, n):
    nr = str(nr)
    beg=set(nr[0:n])
    end=set(nr[-n:])
    return beg==end and beg==set(map(str, range(1, n + 1)))


Listing WordPress posts with thumbnail images

One of the nested loops can be eliminated, by joining these two queries:

$query = "
SELECT *
FROM imagemap
WHERE exercise = '".$data['ExerciseID']."'
LIMIT 1
";

$result = $wpdb->get_results($query);

foreach($result as $row) {
    echo '<div class="imageGridImages imageGridImagesLarge">';
    global $wpdb;
    $exerciseTitleQuery = "
    SELECT post_title
    FROM wp_posts
    WHERE id = '".$data['ExerciseID']."'
    LIMIT 1
    ";

This code is inefficient, because for every row in the first query, you run another query. For example if there are 10 rows in the first query, you'll be running 11 queries. Queries can be expensive, it's better to minimize them as much as possible, for example by selecting multiple rows in bulk instead of doing it one by one. Since in both the outer and the inner queries the parameter is the same, $data['ExerciseID'], you should be able to use a JOIN instead in a single query.

Another problem you have in the first query is that SELECT * is not recommended. You should specify exactly the columns you need, and their order. When you use SELECT *, you might be selecting too much, downloading more data than you really need, and if the order columns change in the database or new columns are added, you could have nasty bugs.


Incorrect size check
itoa(num, 2, buffer); forms "17", which needs 3 char, even though only 2 provided.
Perhaps OP meant 2 to be the string length allowed and not the string size needed.  In which case sizeof buffer / sizeof *buffer is not the length allowed.
Missing header
Add #include <stdbool.h>
Missing size check
Corner case: strcpy(buffer, "0"); occurs even if sz == 1.

A simple alternative to buffer overflow concerns is to form the initial characters in a local buffer that is right-sized for worst case (INT_MIN) like char local_buf[12].  Check idx against sz.  Then reverse into the true destination.
// Re-write end-of-code.
// ....
// Prior code does not check `sz` nor change sz as characters are saved in ample sized local_buf

if (idx + 1 > sz) {
  if (sz > 0) buffer[0] = 0;  // Set buffer[] to "" if possible
  return NULL;
}

for (int i=0; i<idx; i++)
    buffer[idx-i-1] = local_buf[i];
buffer[idx] = '\0';
return buffer;

Rather than hard-code 12 use code to scale to the size needed.  E.g.
// Scale by log10(2)
#define INT_STR_SZ (sizeof(int)*CHAR_BIT*301030/1000000 + 3)
char local_buf[INT_STR_SZ];


Inserting filename, reading data, inserting regex, and testing if each line matches

Some thoughts:

Don't use globals, pass variables as function arguments.
Follow pep8
Don't use == None.  False, 0, 0.0, None, and empty sequences like lists or strings are all considered False, so in your case you can just do something like if not regex.  If you need to test for None specifically, use is None.
Don't do return None, just an empty return will return None automatically.
Don't do a blind except:, you should always check for a specific exception.
For the loop, use enumerate to keep track of the current index.
Use with open(filename, 'r'):.  This will automatically close the file when you leave the with block, even if there is an exception, so you don't need to manually close.
In read_file, don't catch the exception at all.  The default exceptions give the user more information and more useful information than your exceptions, so just let them be handled normally.
It is clearer to do something like print('"%s"' % regex) rather than print('"', regex, '"').  Or better yet regex = '"%s"' % regex if regex else 'empty', then print('Current regex is', regex).
show_menu shouldn't be a separate function.


Merge sort algorithm implementation using C++ (redux)

The first thing I would suggest is using better names for your variables.  It's very hard for someone else looking at or using your code to determine what those variables are supposed to represent.


Magic numbers
Avoid magic numbers. Magic numbers are just numbers in your code that represent some abstract data value. The problem is that they are spreed within the code. To make changes to these values requires searching the code and often the same values are repeated making the task even more difficult.
Defining the magic numbers as named constants makes making changes very easy. See rewrite
Using native API's
P5 is great but using it to create such a simple rendering task is not worth the need to load a huge chunk of code to do what the native API will do quicker (No need for the P5's overhead)
Naming
There are a lot of problems with your naming style.
JS naming convention
The naming convention for JavaScript is to use lowerCamelCase for all names with the exception of objects created with the new token which uses UpperCamelCase (Static objects and object factories can also use UpperCamelCase). For constants you can use UPPER_SNAKE_CASE
_underscoredNames
Use underscore to avoid possible naming classes in systems where you have no control of names.
Using underscore should only ever be a very last option and should never be used if there is no need. Eg the argument _n in push_particles(_n) { should be pushParticles(n)
Avoid redundancy
It is easy to add too much to a name. Keep names short and use as few words as possible. Names are never created in isolation and like a natural language requires context to have meaning.
Eg

Particles_Manipulation is overkill when Particles is all that is needed

my_Particles_Manipulation Never use my (unless its instructional code) This name can just be particles, or smoke

push_particles (don't repeat names) What does this function do? "Adds particles". push becomes add. What does it add particles to? "The Particles object", thus particlescan be inferred. The nameaddis all that is needed. If you were adding monkeys then maybeaddMonkeys`

Avoid repeated long references
Avoid doing the same long reference path and array indexing by store the object reference in a variable.
      this.particles[i].update();
      this.particles[i].show();
      if (this.particles[i].finished()) {
        // remove this particle
        this.particles.splice(i, 1);
      }

Becomes
      const p = this.particles[i];
      p.update();
      p.show();
      if (p.finished()) {
          this.particles.splice(i, 1);
      }

Keep an eye on Logic
The render system reduces the particle alpha each step. You use the alpha value to check when to remove particles alpha < 0. However you reduce the alpha, then render, then remove. That means than once going every frame you are trying to render 5 invisible particles. Remove befor rendering.
JS and Memory
Javascript is a managed language. Meaning that it manages memory for you.
This is great in most cases but it comes with a serious performance hit in applications like particle systems where many small independent objects are frequently being created and destroyed .
Object pool
To avoid the memory management overhead we use object pools.
An object pool is just an array of objects that are not being used. When an object is no longer needed we remove it from the main array and put it in the pool. When a new object is needed we check the pool, if there are any object in the pool we use it rather than create a new one.
This means that the particle object will need a function that resets it.
See rewrite
Note you can also pool the particles in the one array by using a bubble iterator to avoid the expensive @MDN.JS.OBJ.Array.slice@. Dead particle bubble to one end of the array. This is even faster but makes the inner update loop a lot more complex. You would only do this if you where using 10K+ particles.
JavaScript OO design
Many believe that using class is how to write good OO JavaScript. Sorry to say it is not and is in fact the worst way to write OO JavaScript. The class syntax does not provide a good encapsulation model, its only plus is easy inheritance, which is kind of redundant in lieu of JavaScript's lose polymorphism
In this case factory functions (a function that creates Object AKA Object factory) is best suited. Because we use an object pool when need not even bother with assigning a prototytpe for particle functions.
Some advantages of factory functions

This eliminates the need to use this and new.

Lets you define private properties without the need to #hack names

Lets you create objects before the first execution pass has completed (move the init and setups to the top where it belongs)

Some disadvantages of factory functions

Requires a good understanding of closure and Scope both of which are a difficult subjects to get a good understanding of.

Does not work well with object prototypes.

Rewrite
The rewrite uses the CanvasRenderingContext2D API to avoid the overhead of P5, Some replacement functions are at the bottom.
Note that when defining constants it is always a good idea to include unit types, ranges, and or a description  as a comment

animate();
;(() => {
    const CANVAS_WIDTH = 600;       // in CSS pixels
    const CANVAS_HEIGHT = 400;
    const PARTICLE_SPREAD = 1;      // max x speed in canvas pixels
    const PARTICLE_POWER = 3;       // max y speed in canvas  pixels
    const PARTICLE_RADIUS = 12;     // max y speed in canvas pixels
    const MAX_PARTICLES = 1000;     // Approx max particle count
    const PARTICLES_RATE = 3;       // new particle per frame
    const SMOKE_PARTICLES_PATH = new Path2D;  // circle used to render particle
    const PARTICLE_COLOR = "#FFF";  // any valid CSS color value
    const START_ALPHA = 1;          // particle start alpha max
    const START_ALPHA_MIN = 0.5;    // particle start alpha

    // Rate particle alpha decays to match MAX_PARTICLES. The life time in seconds
    // can be calculates as  Math.ceil(1 / ALPHA_DECAY_SPEED) * 60
    const ALPHA_DECAY_SPEED = 1 / (MAX_PARTICLES / PARTICLES_RATE);

    SMOKE_PARTICLES_PATH.arc(0, 0, PARTICLE_RADIUS, 0, Math.PI * 2);
    const canvas = createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT);
    const smoke = new Particles(canvas);
    animate.draw = function() {
        canvas.ctx.setTransform(1, 0, 0, 1, 0, 0);
        canvas.ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        smoke.add(PARTICLES_RATE);
        smoke.update();
    }

    function Particle() {
        var x, y, vx, vy, alpha;
        const PARTICLE = {
            init() {
                x = CANVAS_WIDTH / 2;
                y = CANVAS_HEIGHT;
                vx = random(-PARTICLE_SPREAD, PARTICLE_SPREAD);
                vy = random(-PARTICLE_POWER, -PARTICLE_POWER);
                alpha = random(START_ALPHA_MIN, START_ALPHA);
                return PARTICLE;
            },
            update() {
                x += vx;
                y += vy;
                alpha -= ALPHA_DECAY_SPEED;
                return alpha < 0;
            },
            draw(ctx) {
                ctx.globalAlpha = alpha;
                ctx.setTransform(1, 0, 0, 1, x, y);
                ctx.fill(SMOKE_PARTICLES_PATH);
            },
        };
        return Object.freeze(PARTICLE.init());
    }
    function Particles(canvas) {
        const particles = [];
        const pool = [];
        const ctx = canvas.ctx;
        return Object.freeze({
            add(n) {
                while (n-- > 0) {
                   pool.length ?
                        particles.push(pool.pop().init()) :
                        particles.push(Particle());
                }
            },
            update() {
                var i = 0;
                ctx.fillStyle = PARTICLE_COLOR;
                while (i < particles.length) {
                    const p = particles[i];
                    p.update() ?
                        pool.push(particles.splice(i--, 1)[0]) :
                        p.draw(ctx);
                    i++;
                }
            }
        });
    }
})();

// functions to replace P5
function createCanvas(width, height) {
    const canvas = Object.assign(document.createElement("canvas"), {width, height, className: "renderCanvas"});
    document.body.appendChild(canvas);
    canvas.ctx = canvas.getContext("2d");
    return canvas;
}
function random(min, max) { return Math.random() * (max - min) + min }

function animate() {
    animate.draw?.();
    requestAnimationFrame(animate);
}
.renderCanvas {
    background: black;
}


Normally I'd go on and ramble about how your procedure's name should start with a verb, how the casing of your local variables isn't consistently camelCase, how the procedure is implicitly Public, how the indentation is broken and therefore confusing here:

With DateRng
        .Interior.ColorIndex = xlColorIndexNone
        .Borders.ColorIndex = 1
        .Borders.Weight = xlHairline
For Each cellA In DateRng
    For Each cellB In DateRngPay
            If cellB.Value > "" And cellA.Value > "" And cellB.Value = cellA.Value Then
            With cellA.Borders
                .ColorIndex = myColor
                .Weight = xlMedium
            End With
            Exit For
        End If
    Next cellB
Next cellA
End With

Compare to:

With DateRng
    .Interior.ColorIndex = xlColorIndexNone
    .Borders.ColorIndex = 1
    .Borders.Weight = xlHairline
    For Each cellA In DateRng
        For Each cellB In DateRngPay
            If cellB.Value > "" And cellA.Value > "" And cellB.Value = cellA.Value Then
                With cellA.Borders
                    .ColorIndex = myColor
                    .Weight = xlMedium
                End With
                Exit For
            End If
        Next cellB
    Next cellA
End With

...I'd also so mention that I find cellB.Value > "" a little weird when everyone else would have written cellB.Value <> "" or perhaps cellB.Value <> vbNullString.

I might even have wrecked my brains around trying to find a way to remove the need for a nested loop at all.

All of that would have been useful advice... but there's an even better one.

Ready?

Unless you have a VERY specific and cast-in-stone requirement for the border width, there's no need for any VBA code to do this.

First, name the range on SS!$C$2:$C$67, say MyValues - here I've populated the data with values 1-66, but anything will do:

On the PS sheet, select cell PS!$B$11 and create a conditional format for it, using this formula:

=AND(Info!$B$67=1,NOT(ISNA(MATCH(B11,MyValues,0))))

Decide how you want the conditional format to look like, and then change the applies to range to the cells you're interested in:

=$B$11:$F$16,$I$11:$M$16,$P$11:$T$16,$P$19:$T$24,$I$19:$M$24,$B$19:$F$24,$B$27:$F$32,$I$27:$M$32,$P$27:$T$32

I've shaded these target cells on my own sheet here, but as you can see, any value in these cells that's present on MyValues gets a yellow background and a black border...

...instantaneously.


Your immediate problem is that the exit condition of the loop is when read version returns an error status. This happens when the loop reaches the end of its input file. This call to read also sets version to the empty string.

You can salvage this code by keeping the last known-good value of version in another variable — which you already do here, in last. So change the last line to echo version $last count $count. But there are simpler ways of doing this; uniq -c, which has already been suggested being the simplest, and awk as a general purpose text processing tool being something to keep in mind as well.

While I'm at it, some general notes on shell programming.

Always put double quotes around variable substitutions and command substitutions, unless you can explain why it is safe to leave them off in a particular instance. For example, tail -1 $i should be tail -1 "$i": if you leave off the quotes, this command will fail if the file name contains whitespace or globbing characters.
In fact, this line should be

tail -n 1 -- "$i"

The -- is there in case $i begins with a -; without the -- it would be treated as an option to tail. In this specific case $i always begins with s so the -- is unnecessary, but it's a good habit to get into.
The form -1 is obsolete, and some modern implementations of tail don't support it. -n 1 is the standard form.
To read a line from a file, don't use plain read, but IFS= read -r. See How can I read line by line from a variable in bash? Plain read expands backslashes (expecting a continuation line if a line ends with a \), and strips off leading and trailing whitespace.
Using a named pipe requires a lot of management: you need to create it with a unique name (use mktemp) and make sure the permissions are correct. You may have tried and failed with the following structure:

for i in stats/*; do … done | while read version; do … count=…; done
echo $count

In most shells (Bourne, ash, bash, pdksh), each component of a pipe is executed in its own subshell, so any assignment to count in the while loop doesn't affect the parent shell. Only in a few shells (ATT ksh, zsh) does the rightmost command in a pipeline run in the parent shell. There's a simple workaround for that: run all the code that depends on the assignments performed by a pipeline component inside that pipeline component.

for i in stats/*; do … done | sort -n | {
  while read version; do … count=…; done;
  echo $count
}


Handling missing elements on login form in Selenium

I don't understand what you are intending to do with break in your catch blocks to begin with.  Even in your first code example, you are not within a loop construct to where this makes sense.

In your new code, you should have method name begin with lower case (i.e. byId) as this is pretty much standard in PHP.  I don't really see what value this method is bringing though, as I would tend to agree with the post by @YourCommonSense that you might simplify your operation by using a looping construct.  However I might suggest you put the try-catch within the loop if your intent is to be able to engage in the try-catch for each element rather than for the collection of elements as a whole.

For example:

$elements = [
    'login_feld' => null,
    'password_field' => null,
    'field3' => null
];
foreach($elements as $id => $notUsed) {
    try {
        $elements[$id] = $SeleniumObj->driver->findElement(WebDriverBy::id($id));
    } catch (NoSuchElementException $e) {
        $SeleniumObj->setErrorMessage(
            '1 ID ' . $id . 'does not exist.',
            $e,
            true,
            $id
        );
        // if you want to break here, you now have proper loop context
        // break;
    }
}

// if successful, you can now access the elements from $elements array

This approach is scalable as you add more elements into your test cases, as you could just add new id keys into the element array and not worry about polluting your global namespace with a bunch of $[elementId] variables. You also now have the ability to simply look at the value stored at each key to determine if the element was found.  So for example, if you are going to perform a test action against a certain element, you can test for it like:

if(!is_null($elements['login_field'])) {
    // execute tests against element
} else {
    // log test fail
}

This approach might totally alleviate your need to break altogether, meaning you could now continue to execute your test suite even if one of the elements you expect to be present is missing.  You could just fail those particular tests relevant to the missing element.


Your bi_search() method is recursive.  It doesn’t have to be.  Python does not do tail-call-optimization: it won’t automatically turn the recursion into a loop.  Instead of if len(L) < 1:, use a while len(L) > 0: loop, and assign to (eg, L = L[:mid]) instead of doing a recursive call.

Better: don’t modify L at all, which involves copying a list of many numbers multiple times, a time consuming operation.  Instead, maintain a lo and hi index, and just update the indexes as you search.

Even better: use a built in binary search from import bisect.


To make them square:

var size = Math.max(window.innerWidth,window.innerHeight)/200;
var xbound = Math.floor(window.innerWidth/size);
var ybound = Math.floor(window.innerHeight/size);

Simply use xbound and ybound as the upper limits in the for loops.

Try to use CSS where you can.

Additionally, your script loads very slowly because of the excessive DOM manipulation. Rather than adding each element to the page one by one, create a single object and then paste that in one go. Just add up the html code with the += operator before inserting it into the page.


Firstly, I think your overall approach is sensible. You work your way through the coin types, from highest to lowest, pulling out as many coins of that type as possible, and passing the remainder to the next stage. So, logically, you're on the right track.

But as you've probably noticed, there's a lot of duplication in your code. You need to think about what you're doing the same for each coin type, and pull that logic into its own function. Which will yield something like the following:

def calculate_coins_of_denomination(change, denom):
    """
    Returns a tuple where the first value is the number of coins of the given denomination,
    and the second is the remainder

    Examples:

    calculate_coins_of_denomination(105, 100) => (1, 5)
    calculate_coins_of_denomination(100, 25) => (4, 0)
    """
    num_coins = change // denom
    return (num_coins, change - (num_coins * denom))

Once you've got this function in place, you can then call it repeatedly with each coin type, passing just the remainder to each successive function call:

(num_dollars, change) = calculate_coins_of_denomination(change, 100)
(num_quarters, change) = calculate_coins_of_denomination(change, 25)
(num_dimes, change) = calculate_coins_of_denomination(change, 10)
(num_nickels, change) = calculate_coins_of_denomination(change, 5)
(num_pennies, change) = calculate_coins_of_denomination(change, 1)

Now you've got the values for num_dollars etc, it's just a question of printing your output in the desired format.

As a final note, avoid using profanity or insults in code comments, even for little experimental programs like these. The brief satisfaction that it yields does not justify the potential cost in terms of looking unprofessional or developing bad habits.


Null replacement - Is this LINQ readable?

List.ForEach might have its uses, but I wouldn't use it here. It's not "wrong" per se, but a classic foreach loop

is at least as easy to read as your LINQ expression,
does not require the explicit Cast<...>(),
does not require ToList().

If you put it on one line, it is actually shorter than your LINQ-based solution.

foreach(DataGridViewRow row in dGV_factory.Rows)
{
      //Replace every null cells with an empty string
      foreach (DataGridViewCell cell in row.Cells) cell.Value = cell.Value ?? "";
}

Although, for readability, I'd prefer:

foreach (DataGridViewRow row in dGV_factory.Rows)
{
      foreach (DataGridViewCell cell in row.Cells)
      {
          cell.Value = cell.Value ?? "";
      }
}

(Of course, this is still a great improvement over your co-worker's code.)


If you know that ItemsSource is a dictionary then you can simply cast it into IDictionary and iterate it because you just need objects and it gives you exacly that:

var items = (IDictionary)ItemsSource;
foreach (var key in items.Keys)
{
    AddToItemsAndSelectionValues(key, items[key]);
}

You cast it into a concrete dictionary but you never use the types anyway so go directly with objects instead.

That's all. You don't need any of those ifs.


Find char which appears maximal number of times

According to a modern C# and LINQ you could try to "shock" interviewer with solving in a row:

var res = File.ReadAllText(path)
            .Where(ch => char.IsLetter(ch))
            .GroupBy(x => x)
            .OrderByDescending(x => x.Count())
            .First()
            .Key;


Some recommendations:

Running your code through a linter like pycodestyle, then learning what the messages mean and applying them to your code is going to make your code more idiomatic, and therefore easier to understand for Python veterans.
I would use an external command like time my_script.py to time the execution. This will shorten your code a fair bit (and besides, you would never put timing code into production code). Sure, it's a little bit less accurate, but for Euler Project questions you just want a ballpark estimate.
Use argparse rather than input(). That makes your scripts, well, scriptable, so that they can be used easier within the context of a bigger project, and they can be re-run quicker on the command line.
The only things on the top level of your script should be a shebang line like #!/usr/bin/env python3, imports, class/function definitions, and the following:

if __name__ == '__main__':
    main()

This way, anything declared in the script can be imported by other scripts without running the algorithm.
Naming is one of the most difficult but also most useful skills in programming. If you can think of any better names for n, t, num, j, etc, the program will be much easier to understand for someone without all the context you have.
You hard code the list [2, 3, 5, 7] three times in your code, but only once (at most) should be necessary.
On a related note, starting with a list of the four first primes is very arbitrary. Why not the first million? Or the first one?
isPrime (or is_prime as it should be in idiomatic Python) is a good name, but there is no explanation for which algorithm you're using to check primality. You can introduce the algorithm name in one of several ways:

As a comment.
By refactoring the entire contents of isPrime into a separate method and naming that according to the algorithm. This only really makes sense if either isPrime ends up containing something more than just the call to the other function (a "vacuous" function) or if you intend to implement multiple algorithms in your code and swap them out dynamically (for example, using the fastest algorithm based on the size of the numbers you're dealing with).
More complex means like a dispatcher, but this is not applicable in this situation.

Rather than round(sqrt(n)) you can use floor(sqrt(n)), it'll be faster half the time.
Every time you run isPrime you build up a list of primes, but it goes out of context and has to be recomputed for every number. Your code will be much faster for long lists of input if you save all the primes calculated so far for subsequent runs. For example, you could create an ErathostenesSieve class which has a field sieve which contains the primes detected so far, and it could even be a generator from which you can take an arbitrary number of primes.
If you start with l = 2 or even l = res[-1] you can remove if l!=1:.
Do not append to prime_fst until you're sure the number is prime. That way you won't ever have to sort the list or remove from it.

By the way: Don't be discouraged by the amount of suggestions! IMO this is a very good start, and learning programming is an infinite journey which can be incredibly rewarding.


Simple Commentary

The MSDN provides some naming conventions, the relevant bit being that public members should be ProperCamelCase (e.g. Data, not data).
Public Members, and types, should ideally have at least minimal inline documentation (\\\) to make it perfectly clear how to consume the API.
It's usually for the best to strip out old (commented) code. It has a habit of not being maintained and becoming incompatable with the code that is there. It also adds clutter.
For 'export' code, it's rarely useful to have methods which explicitly write to the console: much more useful to have something that writes to an abstract TextWriter (which can take Console.Out or a StreamReader), or that just returns a string. These give the consumer many more options.
deleteOdd(ref MyLinkedList) probably can't cope with empty lists (being passed them or returning them).
printLL isn't a great variable name: what is "LL"? It's a member of MyLinkedList, so the "LL" bit is redundant; I spect a while trying to work out if it was something to do with printing left to right or something.
mmm isn't a great variable name either: I can only assume it was meant to be mll!

Alternative implementation

Below are some methods which just about tally with yours, but using LinkedList<T>, and incorporating some of the suggestions above.

I don't know if you have a particular reason for needing a custom LinkedList implementation (not suggested by the code), but you can implement your methods tidily with .NET's built in LinkedList<T>, which could be argued to provide a nicer API. Crucially, it wraps up a linked list of LinkedListNode<T>s under a LinkedList<T>, which allows some (illusion of) separation of concerns, and spares you having to keep track of the head of the list explicitly. It also allows you to have an 'empty' list, which is good.

Delete Odd

This method is considerably shorter than before, and doesn't require a ref parameter. This works with empty lists. This is a much more understandable implementation, and much harder to 'get wrong', because of the API for LinkedList<T>.

/// <summary>
/// Removes odd elements from a LinkedList of integers
/// </summary>
public static void DeleteOdd(LinkedList<int> ll)
{
    LinkedListNode<int> cur = ll.First; // grab first node

    while (cur != null)
    {
        var next = cur.Next; // make a note of the next node (will be null if cur is the last element)

        if (cur.Value % 2 != 0)
        {
            ll.Remove(cur); // remove the current node if odd
        }

        cur = next; // advance to the next node
    }
}

printLL

Here are two possible alternatives, which don't depend explicitly on Console: one just produces a string, the other prints to a TextWriter (sadly there is no better interface). These are both extension methods for LinkedList<T>, but there is no particular need for this.

/// <summary>
/// Renders a linked list as a string
/// </summary>
public static string Render<T>(this LinkedList<T> ll)
{
    StringBuilder sb = new StringBuilder();

    foreach (var e in ll)
    {
        sb.Append(e.ToString());
        sb.Append("->");
    }

    return sb.ToString();
}

/// <summary>
/// Prints a linked list to a TextWriter, optionally appending a NewLine
/// </summary>
public static void Print<T>(this LinkedList<T> ll, TextWriter textWriter, bool newLine = true)
{
    foreach (var e in ll)
    {
        textWriter.Write(e.ToString());
        textWriter.Write("->");
    }

    if (newLine)
        textWriter.WriteLine();
}

I wouldn't necessarily condone having the newLine parameter being optional, or indeed being there at all: this is just for illustration of some options. It would probably be better to have both Print and PrintLine if you need both.

Example usage

Note the nicer API for building a LinkedList<T>.

private static void ExampleUsage()
{
    LinkedList<int> ll = new LinkedList<int>();
    ll.AddLast(1);
    ll.AddLast(2);
    ll.AddLast(3);
    ll.AddLast(4);
    ll.AddLast(5);

    Console.WriteLine(ll.Render());
    ll.Print(Console.Out);
    DeleteOdd(ll);
    Console.WriteLine(ll.Render());
    ll.Print(Console.Out);
}


Python3 - merge sort, O(n) space efficiency

Merge is usually O(m) time, where m is the number of elements involved in the merge. Due to your insertions and deletions, it's rather O(mn), where n is the length of the entire list. That makes your whole sort O(n^2 log n) time instead of mergesort's usual O(n log n).
You call it inplace sort, which suggests it doesn't return anything, but you do return the list if it's short and you return some start/end indices otherwise. Rather inconsistent and confusing. I'd make it not return anything (other than the default None).
Your function offers to sort only a part of the list, but you don't test that.
You use quite a few rather long variable names. I'd use shorter ones, especially i and j for the main running indices.
You insert before you delete. This might require the entire list to be reallocated and take O(n) extra space if it doesn't have an extra spot overallocated. Deleting (or popping) before inserting reduces that risk and thus increases the chance that you only take O(log n) extra space.
Mergesort ought to be stable. Yours isn't, as in case of a tie, your merge prefers the right half's next value. For example, you turn [0, 0.0] into [0.0, 0].

A modified version:
def inplace_merge_sort(lst, start=0, stop=None):
    """Sort lst[start:stop]."""

    def merge(i, j, stop):
        """Merge lst[i:j] and lst[j:stop]."""
        while i < j < stop:
            if lst[j] < lst[i]:
                lst.insert(i, lst.pop(j))
                j += 1
            i += 1

    if stop is None:
        stop = len(lst)

    middle = (start + stop) // 2
    if middle > start:
        inplace_merge_sort(lst, start, middle)
        inplace_merge_sort(lst, middle, stop)
        merge(start, middle, stop)

Oh, I renamed end to stop, as that's what Python mostly uses, for example:
>>> help(slice)
Help on class slice in module builtins:

class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])

>>> help(list.index)
Help on method_descriptor:

index(self, value, start=0, stop=9223372036854775807, /)

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
```


Concise Proof of the Monty Hall Problem in R

The fundamental ideas of your code are solid, however there are a couple of areas that could be improved. For starters, when you call sample and you only want one number returned, you can make use of the size argument.  For vectors of only size 3, as in your case, there isn't much difference:

library(microbenchmark)
microbenchmark(sample(doors, size = 1),
               sample(doors)[1], times = 10^4, unit = "relative")
Unit: relative
                   expr      min      lq     mean   median       uq      max neval
sample(doors, size = 1) 1.000000 1.00000 1.000000 1.000000 1.000000 1.000000 10000
       sample(doors)[1] 1.104667 1.09216 1.111044 1.086809 1.082041 1.072216 10000

However, as the size of your input vector increases, there is a noticeable difference in methods.

doorsHuges <- rep(doors, 10^6)
length(doorsHuges)
[1] 3000000

microbenchmark(sample(doorsHuges, size = 1),
               sample(doorsHuges)[1], unit = "relative")
Unit: relative
                        expr      min       lq     mean  median       uq     max neval
sample(doorsHuges, size = 1)     1.00     1.00     1.00    1.00    1.000    1.00   100
       sample(doorsHuges)[1] 65693.19 31524.98 10609.52 9126.07 6347.235 4338.52   100

Next, we can greatly improve our efficiency by taking advantage of the fact that sample can perform many replications in one go by making use of the replace argument. For example, instead of using a for loop and generating a single scenario, we can do the following:

sample(doors, n, replace = TRUE)

The gains in efficiency are tremendous:

microbenchmark(forLoop = for(i in 1:1000){sample(doors, 1)},
               usingRep = sample(doors, 1000, replace = TRUE), unit = "relative")
Unit: relative
    expr      min       lq     mean   median       uq      max neval
 forLoop 211.0778 204.1896 127.7005 199.9415 191.6994 185.1182   100
usingRep   1.0000   1.0000   1.0000   1.0000   1.0000   1.0000   100

Now, let's look at our data types.  Since we are mainly concerned with probabilities, the actual values of our main vector doesn't matter.  Since this is the case, we should look to use integers when we can.  We can achieve this by using seq_along(doors) or simply length(doors). Observe:

intDoors <- seq_along(doors)
microbenchmark(intDoors == 2, doors == "B", times = 10^4, unit = "relative")
Unit: relative
         expr      min       lq    mean   median       uq      max neval
intDoors == 2 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000 10000
 doors == "B" 1.449541 1.422819 1.35682 1.396226 1.390533 1.053855 10000

While we are on integers, which is an awesome function which is very efficient and very intuitive. However, when we are indexing, it is completely unnecessary.  We can use logical subsetting instead. It is cleaner and just as efficient. Observe:

 mySamp <- sample(10^6, 10^6)
 boolTest <- rep(FALSE, 10^6)
 boolTest[mySamp] <- TRUE
 testIndex <- 1:10^6

 microbenchmark(testIndex[which(boolTest)], testIndex[boolTest], unit = "relative")
 Unit: relative
                       expr      min       lq     mean  median       uq       max neval
 testIndex[which(boolTest)] 1.533577 1.350712 1.185725 1.36155 1.386107 0.1012212   100
        testIndex[boolTest] 1.000000 1.000000 1.000000 1.00000 1.000000 1.0000000   100

In order to resolve the monty vector and the second iteration of contestant, we can implement vapply along with length to avoid calls to sample where the length is 1.

monty <- vapply(1:numReps, function(x) {
                mySet <- intDoors[intDoors != car[x] & intDoors != contestant[x]]
                if (length(mySet) > 1) sample(mySet, 1) else mySet}, 1L)

And finally, instead of incrementing win, we can get it all at once using sum(contestant == car).  This takes advantage of vectorization and the internal coercion from logicals to integers. Putting it all together, we get:

funImproved <- function(numReps) {
    car <- sample(intDoors, numReps, replace = TRUE)
    contestant <- sample(intDoors, numReps, replace = TRUE)

    monty <- vapply(1:numReps, function(x) {
                    mySet <- intDoors[intDoors != car[x] & intDoors != contestant[x]]
                    if (length(mySet) > 1) sample(mySet, 1) else mySet}, 1L)

    contestant <- vapply(1:numReps, function(x) {
                        mySet <- intDoors[intDoors != monty[x] & intDoors != contestant[x]]
                        if (length(mySet) > 1) sample(mySet, 1) else mySet}, 1L)

    wins <- sum(contestant == car)
    (wins/numReps)
}

The OP's function is:

funOP <- function(numReps) {
    wins <- 0

    for (i in 1:numReps) {
        # Choose which door the car is behind
        car <- sample(doors)[1]

        # The contestant chooses a door
        contestant <- sample(doors)[1]

        # Monty opens a door that the car is not behind
        monty <- sample(doors[which((doors != car) & (doors != contestant))])[1]

        # Force the contestant to switch
        contestant <- sample(doors[which((doors != monty) & (doors != contestant))])[1]

        # Count the wins
        if(contestant == car){wins <- wins+1}
    }

    (wins/numReps)
}

And the final comparison sees an improvement of about 4.5x.

microbenchmark(funOP(n), funImproved(n),
               times = 50, unit = "relative")
Unit: relative
          expr      min       lq    mean   median       uq      max neval
      funOP(n) 5.060335 4.518107 4.54938 4.539024 4.183145 7.831481    50
funImproved(n) 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000    50

The results are very similar as well:

## the average difference over 100 trials when n = 10^5
mean(replicate(100, funOP(10^5) - funImproved(10^5)))
[1] -0.0001978

As a final note, when one is performing any sort of procedure that calls for verification, it is a good idea to use set.seed so you can predictably verify your results. For example:

sapply(1:100, function(x) {
        set.seed(42)
        funImproved(10^3)
    })
 [1] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[16] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[31] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[46] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[61] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[76] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668
[91] 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668 0.668


Big O notation for quicksort implementation

Doesn't work

Your sort doesn't work on this array:

int[] input = { 4, 5, 3, 2, 6, 1};

The output is:

Before sorting : [4, 5, 3, 2, 6, 1]
After sorting : [1, 2, 3, 5, 4, 6]

What's wrong?

One problem with your quicksort is that it doesn't always rearrange items to the left and right of the pivot.  If you pick the pivot that is the smallest element in the array, no swaps will be made.  Thus, you should either pick the leftmost item to be the pivot so that "no swaps" will just work, or swap the pivot item into the correct spot after your loop is finished.

Another problem with it is that you have a hardcoded 0 which is wrong:

rechelperquickSort(array,0,left,array[left/2]);

That 0 there should be the original value of left passed into the array.  Otherwise you are creating more work.


First I want to suggest a concrete implementation:

public class ValidateUtil{

    private static Pattern pattern;
    private static final String REFFERENCE_PATTERN = "The regex pattern here";

    public static boolean validate(final String reference){
        return getPattern().matcher(reference).matches();
    }

    public static Pattern getPattern() {
        if (pattern == null) {
            pattern = Pattern.compile(REFFERENCE_PATTERN);
        }
        return pattern;
    }

    /*
     * Many util Methods here
     */

}

  This may lead to increase the line of codes

Lines of code is at the most an indicator of less code quality. Do not ask for lines, do ask for responsibilities. Hypothetically a method/a class can have thousands lines of code and it will not produce any problem if it has only one responsibility. But I'll give you that it becomes more and more probable to violate the SRP (single responsible principle) the more code is available in the scope. And of course you may have other problems can be derived from many lines of code available. But code of lines alone will say you less to nothing.

  and sometime, the performance gain can be neglectable

And here you got a point. In one of my projects I discussed using "synchronized" and the performance issues. We measured a relation about 1:20. So of course it MUST be an issue... We made a second measurement. We iterated over a synchronized method 20.000.000 times and with the available pc configuration it took 20 seconds. BTW, the methods we talk about were called in maximum 20 times a second. What I want to say is: It really depends on the use case. But in MOST use cases you do not need not care about preemptive optimization. And you have to look at both: relative and absolute metrics.

  On the other hand, is this really worth only for heavy, large objects (like Database connections)

A very clear answer in THIS case of LAZY INITIALIZATION: No.

It may be a case of preemptive optimization. But that is not the reason I would prefer it. The reason why I would do so is: If you only use lazy getter-methods within or from outside your object/class you make yourself independent of the order of object creation. You use the getter and you get an object, doesn't matter if it was created before or it was created right now. This is especially useful in component trees. You often play around with the position of an ui element in the ui component tree. A lazy getter saves your ass and time. After all ui components often are heavy and even if they are not you get the optimization for free.


Future in f# is this an unavoidable use of a mutable variable?

This looks pretty close to a Clojure Promise. On .NET, the similar type is (very Microsoftish) called TaskCompletionSource<TResult>.

However, you should consider if F# Lazy Computations isn't what you need.


Assuming that you are forced for some reason to use that particular type of datastructure, I think you will end up with an O(k) algorithm.

To deal with the edge case, note that your code arguably works fine if k is too large--it just doesn't print anything.  You could also store the size of the tree and check that.  But you'll have to be careful to keep it updated when you manipulate the tree.

Alternately, you could change your tree-walking code to return a value as soon as it finds one:

function reverseFind(node, test) {
  if (node == null) return undefined;
  return reverseFind(node.right, test)
    || test(node) ? node : undefined
    || reverseFind(node.left,  test);
}

function kthLargest(tree, k) {
  var count = 1;
  var node = reverseFind(tree, function(node) {
    if (count++ === k) return true;
  });
  if (node) {
    console.log(node.val);
  } else {
    console.log('no value');
  }
}

This, at least, is O(k), not O(n).

If your data is reasonably static, it is probably better to just store your data in a sorted array.  Then you can get the kth largest element in constant time with much less code:

var sortedArray = [2, 5, 6, 8];
function kthLargest(sortedArray, k) {
  return sortedArray[sortedArray.length - k];
}

Note that this code assumes that there are no values in the array with negative indices (i.e., that sortedArray[-5] === undefined).  So you can deal with the edge case of invalid k by checking to see if kthLargest returns a value.


Optimize function for assigning existing 3D array values to values of keys in array of objects

There's two things that might help performance, and could also make your code easier to understand:

only extract the length of the arrays once per loop, instead of per iteration
deference deeply nested structures earlier, and as infrequently as possible

For #1, I normally use:

for (var i = 0, n = array.length; i < n; ++i) { ... }

For #2, look at your innermost nested line:

organized[k - 1][arrKeys[j]] = arr3d[k][j + 1].trim();

Consider reversing the order in which you enumerate over the data.  There's more scope for optimising values from the inner loop to the outer loop if you iterate over the "leftmost" components of your 2D structures first:

for (var k = 1, kn = arr3d.length; k < kn; k++) {
    var o = organized[k - 1] = {};
    var a = arr3d[k];
    for (var j = 0, jn = arrKeys.length; j < jn; j++) {
        var t = a[j + 1];
        if (t) {
            o[arrKeys[j]] = t.trim();
        }
    }
}

Note also that now that the loops are the other way around there's no need to pre-create the objects that make up the organized array - it's initialised with an empty object in the first line of the outer loop.


Python script to read CSVs and regroup it into the data types I need

The opened file is never closed, a better habit is to use
with open(filename, 'rb') as foo:.
foo == True is rarely needed; unless you really need to
differentiate between True/False and the various other truthy
values it's easier just to test for the variable instead.  Same goes
for the empty list for that matter.
The pass doesn't do anything; price is unused.
Instead of linear search you could keep a set or dict of already
recorded people around.
With enumerate it's easier to destructure the result directly in the
loop; that said, the enumerate is also not necessary here.
The use of key looks buggy:  In the else branch it has never been
set (except maybe because of Pythons moronic scoping rules).  In any
case it'd better to make clear how that works.

That would be something the lines of the following then:

import csv

people = []
people_ids = set()

def add_person(group_id, new_subscription):
    people.append({
        'id': group_id,
        'subscriptions': [new_subscription]
    })
    people_ids.add(group_id)

#open csv file
with open(filename, 'rb') as file:
    csv_file = csv.reader(file)

    #read CSV file into a list of people
    for record in csv_file:
        sub_id = record[0]
        group_id = record[6]
        season_desc = record[11]
        series_desc = record[12]

        if "MW" in series_desc:
            sub_type = "Masterworks"
        elif "Pops" in series_desc:
            sub_type = "Pops"
        elif "Chamber" in series_desc:
            sub_type = "Chamber"

        new_subscription = {
            'id': sub_id,
            'season': season_desc,
            'sub_type': sub_type
        }

        #if this is the first time through the loop
        if len(people) == 0:
            add_person(group_id, new_subscription)
            continue

        #check if this person has already been recorded
        #if not, add the subscription to them and save the person
        if group_id not in people_ids:
            add_person(new_subscription)
            continue

        #check if this subscription has already been added to this person
        #use enumerate to get a key to search people
        for person in people:
            if person['id'] != group_id:
                person['subscriptions'].append(new_subscription)

I also shuffled the branches around, which together with continue
makes for less indented blocks.

If you're going to extend this, I'd recommend more factoring into functions, a
main function, etc.


3 textboxes with multiple value combinations to one output

If I understand correctly, you want to add up all the fields, and print the result. If this is the case, you are complicating things quite a lot. If you think of the problem in terms transformations it will be easier to reason about. You have a list of numbers that you want to add up, that's the problem at hand; the boolean logic expressions are not necessary, because zero doesn't add anything (it's an identity element), and addition is commutative. To prevent non-numbers from being entered, you'd check for NaN, and return identity (zero) if it is not a number, effectively doing nothing:

function sum() {
  var result = document.getElementById('result')
  var ids = ['Text1','Text2','Text3']
  result.textContent = ids
    .map(function(id) {
      // + casts a number from a string
      var n = +document.getElementById(id).value
      return isNaN(n) ? 0 : n // identity
    })
    // add up all numbers
    .reduce(function(x, y){return x + y})
}

Ideally you'd also cache the elements to not query them each time the function runs, but I doubt it would make a big difference in this case.

Demo: http://codepen.io/anon/pen/JIwHx


Passing objects atomically across threads without locks or data races for audio synchronization

keepAlive.reset is not thread safe. So your class as a whole cannot be thread safe.


Amalgamate two toggle functions into one

function toggleVisibility() {
    var temp = document.getElementById('regStart').style.visibility
    document.getElementById('regStart').style.visibility = document.getElementById('regPage').style.visibility;
    document.getElementById('regPage').style.visibility = temp;

    var suffix = "Gray.png";
    if ( 'hidden' === temp ) {
        suffix = "Depressed.ico";
    }

    document.getElementById('facebook').src = "/images/js project/Facebook" + suffix;
    document.getElementById('google').src = "/images/js project/Google" + suffix;
    document.getElementById('winlive').src = "/images/js project/WinLive" + suffix;
    document.getElementById('yahoo').src = "/images/js project/Yahoo" + suffix;
}

The first insight is that you want to swap the visibility settings for regStart and regPage.  So use the normal swap format with a temp variable.

The second insight is that your image paths have the same start for both cases of each image.  So the beginning can be a constant value for each image.

The third insight is that your image paths have the same ending for all images in a particular case.  So based on the value of temp (arbitrarily chosen as the shortest variable name), change the ending.

I also normalized the indentation.  It was inconsistent in your original functions.


Some notes:

  cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

Try to be less verbose: cell = "123456789".split() or cell = [str(n) for n in range(1, 10)]. Anyway, conceptually it's very dubious you initialize the board with its number instead of its state. Also, cell is not a good name, it's a collection, so cells.

board = '\n\t ' + cell[0] + ...

Don't write such a long lines, split them to fit a sound max width (80/100/...). Anyway, here the problem is that you shouldn't do that manually, do it programmatically (grouped from itertools):

board = "\n\t-----------\n\t".join(" | ".join(xs) for xs in grouped(cell, 3))

  return cell[0] == cell1 == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell1 == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8]== 'O

Ditto, use code:

groups = grouped(cell, 3)
any(all(x == 'O' for x in xs) for xs in [groups, zip(*groups)])

Note that you are not checking if a cell has already a piece.


Extract equally from X queues to one queue with Y elements

First off, you're code looks nice, but it can be improved in places:

I don't see why:

        $totSmsToSend = count($smsToSend);

Is indented so far, you should fix that. There's quite a few elements that have been over indented.

Your constant use of the word Sms like so, seems a bit silly, as it as an acronym, you should stick to SMS or sms but don't mix cases.
$tot, You shouldn't leave out two characters, just for the purpose of slimming when it makes it much less readable.
Your code seems really forced, so I think it could be improved in the method it goes about doing.

Your solution really just sounds like basic division:

Y / X, rounded down to a whole number
For leftover positions in Y queue, transfer X(1), X(2), ... X(X) and go through until you fill up the queue.


Step 1 is always to try it without the duplicated code and see what it might look like; then you can try to fill in the blanks to make the program compile again. So:

cout << "\nTotal (approx) travel distance = "
     << english_approximation(totalDistance) << " km\n" << endl;

And then you just have to write

std::string english_approximation(long long totalDistance)
{
    if (totalDistance < 1e3) {
        return std::to_string(totalDistance) + " million";
    } else if (totalDistance < 1e6) {
        return std::to_string(totalDistance / 1e3) + " billion";
    } else if (totalDistance < 1e9) {
        return std::to_string(totalDistance / 1e6) + " trillion";
    } else {
        assert(false);  // presumably?
    }
}

Are you at all concerned that 1e3, a.k.a. 1000, is not "a million", and so on?

It is unclear to me whether totalDistance is supposed to be measured in kilometers, or meters, or what. (Megameters would make the math come out right, I suppose, but that just seems crazy.) I strongly recommend that any time you're dealing with measurements or other "unit-ful" data, you encode the expected units into the variable name, unless the expected units are already encoded in the variable's type. For example:

std::chrono::milliseconds timeout;  // excellent
int timeout_ms;  // excellent
int timeout;  // horrible

boost::units::kilometers totalDistance;  // excellent (hypothetically; this isn't actually how Boost.Units works)
int totalDistanceKm;  // excellent
int totalDistance;  // horrible


filelist="$(
   IFS='
'
   echo "$*" | sed -n '$!H;${x;s/.//;s/\n/ /g;p;}'
   )"

to="$(
   IFS='
'
   echo "$*" | sed '$!d'
   )"

This should do, assuming there are no new lines in the parameter/s.

Your code assume there is only 1 word per argument. This have nearly no impact unless the last argument is a multi word (miss interpreted by your code taking the very last word and not argument).

For this reason:

Use another separator than standard white space/tab for passing the parameter to sed.

Use $* (and not $@) to have the shell separation on argument and not word.
Using IFS Internal Field Separator of the shell.
Using a sub shell to limit IFS scope to this function (hopefully already the case with "$(...)" used for assignation.

Adapt sed to separate argument with new line, and readapt the new line to white space for final value (sed by default work per line so need to load the lines in buffer before working on it at the end).


Minimizing CSS media queries for the page title?

If you have control over your html, give both headers the same class, for example .header-stretch.
For media queries - you actually can get rid of min-width. Yep, your code will be overriden for several times. But browser won't care rewriting the same parameter(font-size in this case - in any other you can do so) so it should be like this:

@media screen and (min-width: 951px) {
  .header-stretch {
    font-size: 36px;
  }
}
@media screen and (max-width: 950px) {
  .header-stretch {
    font-size: 24px;
  }
}
@media screen and (max-width: 749px) {
  .header-stretch {
    font-size: 22px;
  }
}
@media screen and (max-width: 569px) {
  .header-stretch {
    font-size: 20px;
  }
}
    @media screen and  (max-width: 321px) {
  .header-stretch {
    font-size: 18px;
  }
}


Random Number Generator from user touch input

This is a bad idea for different reasons. I'll short-list them and then go into details.

Your distribution isn't random. X and Y values are constrained to screensize, accordingly different devices have different possible randomness distributions, which is a "bad thing"™
User input is not random. "Guess a random number between 1 and 10" is not random and neither is "type on the screen randomly". Humans are really bad at faking randomness.

The x and y value constraints are a bad thing in the first place. Smaller devices have less entropy to generate, larger devices have repetition when the x and y coordinates "repeat", since you truncate any value larger than 8 bits.

Luckily screen-sizes are usually a nice multiple of \$256\times256\$ "tiles". The actually useful entropy you can currently extract accordingly is in one such tile.
Unfortunately this also means that "randomly" tapping similar areas in these tiles (as probably many non-technical people would do) will produce somewhat predictable bytes.

This directly brings us to the next point. The "Blue Seven Phenomenon". There's a metric ton of academic articles about the subject, but the bottom line is: Humans are bad at pretending to be random.
The brain is trained evolutionarily (and throughout our whole lives) to recognize patterns. True randomness doesn't actually exhibit those patterns. Any patterns we see in randomness are just ... imagination. Well not quite, but there's no actual meaning behind them.

The problem is when you ask users to provide "random" input, their brain will simply not be able to provide it, and instead you'll get a more or less pseudorandom pattern.

Long story short, you'll not receive something that I'd deem cryptographically secure.


Find out the 2 numbers which gives the highest product

Bugs

Your negative cases are wrong.

        if (arr[i] < 0) {
            secondNegMax = firstNegMax;
            firstNegMax = arr[i];

Here you always overwrite the current maximums...

            if (arr[i] > firstNegMax) {
                secondNegMax = firstNegMax;
                firstMax = arr[i];
            } else if (arr[i] > secondNegMax) {
                secondNegMax = arr[i];
            }

And here you check if a certain value is HIGHER than the max (which is negative, so 0 is higher than all negatives!). Neither of this is going to result in a good end result.

Aside from that, there seems to be no explicit check for verifying that you have at least an array of length 2 and that the output consists of either "two positive numbers" or "two negative numbers". Other than that, it's working fine.

Algorithm

I've got only one algorithmic improvement, and that's this one...

        if (arr[i] > 0) {
            if (arr[i] > firstMax) {
                secondMax = firstMax;
                firstMax = arr[i];
            } else if (arr[i] > secondMax) {
                secondMax = arr[i];
            }
        }

        if (arr[i] < 0) {
            secondNegMax = firstNegMax;
            firstNegMax = arr[i];
            if (arr[i] > firstNegMax) {
                secondNegMax = firstNegMax;
                firstMax = arr[i];
            } else if (arr[i] > secondNegMax) {
                secondNegMax = arr[i];
            }

        }

Here, you first check if the current element is positive... and then, later, you check if it's negative. Now, there's nothing wrong with that, but if you know that this element is positive, then there is no need for the negative check anymore. Use else-if here.

Naming

Your shorthand should be expanded, firstNegativeMax reads better than firstNegMax. max is well understood as "maximum", neg isn't as well understood. Aside from that, assigning arr[i] to a local variable with a name like "currentNumber" or "currentElement" would help readability. (Better yet, follow Martin R's advice and make it a for-each loop.)


This is mostly quite good, but has some issues.

The required answer to the Project Euler problem is not the values of \$a\$ and \$b\$, but their product. You could output that value rather than requiring another computation.
Your prime test could be speeded up by first calculating a table of primes, then only checking for divisibility against that.

primes = [2, 3]

def extend_primes(upto):
    """Pre-extend the table of known primes"""
    for candidate in range(primes[-1], upto + 1, 2):
        if is_prime(candidate):
            primes.append(candidate)

def is_prime(x):
    """Check whether "x" is a prime number"""
    # Check for too small numbers
    if x < primes[0]:
        return False
    # Calculate the largest possible divisor
    max = int(math.sqrt(x))
    # First, check against known primes
    for prime in primes:
        if prime > max:
            return True
        if x % prime == 0:
            return False
    # Then, lazily extend the table of primes as far as necessary
    for candidate in range(prime[-1], max + 1, 2):
        if is_prime(candidate):
            primes.append(candidate)
            if x % candidate == 0:
                return False
    return True

Whether this actually improves performance would have to be properly benchmarked.
Your longest is an list. Instead, you probably wanted to use a tuple:

longest = (0, 0, 0)
...
if count > longest[0]:
    longest = (count, a, b)
...
_, a, b = longestQuadraticPrime(...)

What is the difference? A list is a variable-length data structure where all entries should have the same type. In C, the rough equivalent would be an array. A tuple is a fixed-size data structure where each entry can have a different type. The C equivalent would be a struct.

However, I think it would be actually better to use named variables instead of indices:

longest_count = 0
longest_a = None
longest_b = None
...
if count > longest_count
    longest_count = count
    longest_a = a
    longest_b = b
...
return longest_a, longest_b
...
a, b = longestQuadraticPrime(...)

This is longer, but more readable.
Your code takes some nice shortcuts but fails to explain why you can take these shortcuts.

For example, you only test a \$b\$ if it's a prime. This follows from the \$n = 0\$ case where the expression can be reduced to \$b\$, which therefore has to be prime. This also allowed you to narrow the search space from \$(-1000, 1000)\$ to \$[2, 1000)\$. Just mention this in a comment instead of implying it.

If we pre-calculate a prime table, we could also iterate through those known primes instead of testing each number again and again:

extend_primes(blim)
for b in primes:
    if b >= blim:
        break
    ...

Your n and count variables are absolutely equivalent. Keep n, discard count.
Stylistic issues:

Variables and functions etc. should use snake_case, not camelCase or some quiteunreadablemess. If possible, they should consist of proper words rather than abbreviations, except for very common abbreviations like maximum as max.

alim → a_lim or a_max
isPrime → is_prime
longestPrimeQuadratic → longest_prime_quadratic (although this name doesn't convey very well what this function is doing)
ans → answer, but returning a tuple and destructuring this is probably cleaner.

Don't use one-line conditionals like if k < 2: return False. Instead, use all the space you need to make it as readable as possible:

if k < 2:
    return True

Put spaces around binary operators. math.sqrt(k)+1 becomes math.sqrt(k) + 1
alim * -1 would usually be written with an unary minus: -alim.


Average of multiple vectors with different length

Your code is O(NM) because it iterates through every value, for every id.

You need to iterate through the values once, adding the values to some structure which tracks the sum of every value for every id, and the number of values seen.

This lets you calculate average = (sum_values)/n_values in O(N+M), where N is number of values, M is number of ids.


Implementing a REST API in Go using gorilla/mux and Gorm

ID as a string is weird. I expect to see an int here to benefit of the auto increment feature.
your delete handler is weak. Suppose the GET ID parameter is set to a non existing ID value, the read operation will fail but the value of the ID property of the student variable will be an empty string. The next delete statement will delete the row with ID=="", which might exists and be a valid. The problem also exists for an integer PK where ID=0. You must check all errors.
the update handler has a similar problem, and it is not acceptable for as long as the api provides both add and update as different operations. Usually an update operation requires to check against a couple PK+LastUpdateDate to ensure acid transactions from UI POV. So, you might try to load the entity from the db, at the cost of an extra read. Or update with clauses. The latter might be done automatically by the db framework, this is unclear without a better knowledge of its internal.
the getAllStudents handler is a ddos. Obviously that always depends of the db size, but for a production system there must not exist any handler that loads the entire db in memory. So add Limit/Offset parameters, check they are valid and apply them to the query.
overall your code has too many level of indentations. You should practice the early return pattern to improve its clarity.

Here is an updated version of the code, so the reader can evaluate the return early pattern and appreciate various modifications as explained before.

Care was taken to demonstrate a proper startup/shutdown sequence to prevent connections misshandling.
http.Server is moved out so the handler is mountable onto alternatives http server implementation (httptest.*)
the db engine is switched to sqlite for demonstration
OP was missing the pgsql driver blank import

here is the code (it is still missing proper test suite!)

package main

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "log"
    "net/http"
    "os"
    "os/signal"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type student struct {
    ID   string `gorm:"primary_key" json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`

    // http://gorm.io/docs/conventions.html
    // gorm.Model is a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt.
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

type App struct {
    DB *gorm.DB
}

func (a *App) Handler() http.Handler {
    r := mux.NewRouter()
    r.HandleFunc("/students", a.getAllStudents).Methods("GET")
    r.HandleFunc("/students", a.addStudent).Methods("POST")
    r.HandleFunc("/students/{id}", a.updateStudent).Methods("PUT")
    r.HandleFunc("/students/{id}", a.deleteStudent).Methods("DELETE")
    return r
}

func (a *App) Open() error {
    db, err := gorm.Open("sqlite3", ":memory:")
    if err != nil {
        return err
    }
    a.DB = db
    return db.AutoMigrate(&student{}).Error
}

func (a *App) Close() error {
    return a.DB.Close()
}

func (a *App) getAllStudents(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    // see also a struct decoder to transform get params as struct.
    // https://github.com/gorilla/schema
    var offset, limit int
    {
        y := r.URL.Query().Get("Limit")
        if y != "" {
            x, err := strconv.Atoi(y)
            if err != nil {
                sendErr(w, fmt.Errorf("Limit argument, %v", err), http.StatusBadRequest)
                return
            }
            limit = x
        }
        y = r.URL.Query().Get("Offset")
        if y != "" {
            x, err := strconv.Atoi(y)
            if err != nil {
                sendErr(w, fmt.Errorf("Offset argument, %v", err), http.StatusBadRequest)
                return
            }
            offset = x
        }
    }
    if limit < 0 || limit > 30 {
        limit = 30
    }
    var all []student
    err := a.DB.Find(&all).Limit(limit).Offset(offset).Error
    if err != nil {
        sendErr(w, err, http.StatusInternalServerError)
        return
    }
    json.NewEncoder(w).Encode(all)
}

func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, err, http.StatusBadRequest)
        return
    }
    err = a.DB.Create(&s).Error
    if err != nil {
        sendErr(w, err, http.StatusInternalServerError)
        return
    }
    w.WriteHeader(http.StatusCreated)
}

func (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, err, http.StatusBadRequest)
        return
    }
    id := mux.Vars(r)["id"]
    if s.ID != id {
        sendErr(w, errors.New("invalid ID"), http.StatusBadRequest)
        return
    }
    s.ID = id                 // Why not read it from Body directly ?
    err = a.DB.Save(&s).Error //gorm does a proper job http://gorm.io/docs/update.html
    sendErr(w, err, http.StatusInternalServerError)
}

func (a *App) deleteStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    id := mux.Vars(r)["id"]
    s := student{}
    err := a.DB.First(&s, id).Error
    if err != nil {
        sendErr(w, err)
        return
    }
    err = a.DB.Delete(s).Error
    sendErr(w, err)
}

func sendErr(w http.ResponseWriter, err error, codes ...int) {
    if err == nil {
        return
    }
    if len(codes) < 1 {
        codes = append(codes, http.StatusInternalServerError)
    }
    response, _ := json.Marshal(map[string]string{"error": err.Error()})
    w.Header().Set("Content-Type", "application/json")
    http.Error(w, string(response), codes[0])
}

func main() {
    app := App{}
    if err := app.Open(); err != nil {
        log.Fatal("open failed", err)
    }
    defer app.Close()

    srv := &http.Server{
        Addr:    ":8080",
        Handler: app.Handler(),
    }

    err := make(chan error)
    go func() {
        err <- srv.ListenAndServe()
    }()

    select {
    case e := <-err:
        log.Fatal("listen failed", e)
    case <-time.After(time.Millisecond * 200):
        log.Println("app started at ", srv.Addr)
    }

    sigint := make(chan os.Signal, 1)
    signal.Notify(sigint, os.Interrupt)
    <-sigint
    log.Println("got signal")

    if err := srv.Shutdown(context.Background()); err != nil {
        // Error from closing listeners, or context timeout:
        log.Printf("HTTP server Shutdown: %v", err)
    }
    log.Println("properly shutdown")
}


Your presumtion that the future.get() method is called in another thread is wrong. The  constructor still executes in the same thread as the loop, its the run() method in the Updater class that is called in its own thread. Consider passing the whole future to the Updater and store a reference to the future internally. Then, once the value is really required (somewhere after the run method of Updater has been called), you can call get() on the future to retrieve its value.


There is no reason to use HashMap, you are not using the bools anywhere. So I think You could just use HashSet. Which you don't need to feed in foreach, instead simply pass the integers as constructor parameter.

var set = new HashSet(A);

You don't have to compare both i and j

i < A.length && j < A.length

if j is always one larger then i, just compare with j.

This condition is always true:

(a + b + delta) == sum

since that is the way it was obtained in the first place:

Integer delta = sum - (a + b);

This:

int[] result = {a, b, delta};
return result;

could be just

return {a, b, delta};

You are returning null where you claim to return int[], not sure if that's correct.

Anyway I think your implementation does not work as intended, because it only looks for sums of two consecutive and third anywhere. It fails for example on [5,1,2,1,8] looking for 15=5+2+8.


A few things to mention:

As has been mentioned, you're using 1-based indexing instead of 0-based indexing.  0-based is much more intuitive, since most implementations, of indexing in most programming languages, use 0-based indexing.

You're using the Arrays.asList twice for each iteration of the loop. This increases the inefficiency.

Calling indexOf inside the loop is basically creating another loop and doesn't gain anything a for loop wouldn't give you.

I think the name of your method could be better.  search indicates all you want is the value.  However you're returning the indexes.  Therefore indexesOf might be more appropriate, and more in fitting with similar methods in other collections.

Your method is hard coded for int.  This isn't very extensible.  A generic version would probably be more fitting.

You're returning an int[].  This doesn't really tell anyone what this is supposed to represent.  I would suggest a class(Indexes) to hold the indexes would allow you to represent them with a name that will immediately let the user know what it represents.

You haven't made any provision to handle failed searches.

It looks to me that the 2D array is basically a matrix.  Therefore I would suggest labeling the indexes as such(row,column).

The Indexes class would look like this:

public class Indexes {
    int row = 0;
    int col = 0;

    public Indexes(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public Indexes() {
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public int getCol() {
        return col;
    }

    public void setCol(int col) {
        this.col = col;
    }
    @Override
    public String toString(){
        return String.format("[%d, %d]",row,col);
    }
}

A generified version with the points I mentioned could look something like this:

public static<T> Indexes indexesOf(T[][] arr, T value){
    for(int row = 0; row < arr.length; ++row){
        for(int col = 0; col < arr[row].length; ++col){
            if(arr[row][col].equals(value)){
                return new Indexes(row,col);
            }
        }
    }
    return new Indexes(-1,-1);
}

EDIT Alternative code based on OP's comments

static final int DEFAULT_RETURN_VALUE = -1;
public static<T> Indexes indexesOf(T[][] arr, T value){
    for(int row = 0; row < arr.length; ++row){
            int col = indexOf(arr[row],value);
            if(col > DEFAULT_RETURN_VALUE){
                return new Indexes(row,col);
            }
    }
    return new Indexes(DEFAULT_RETURN_VALUE,DEFAULT_RETURN_VALUE);
}
public static<T> int indexOf(T[] arr, T value){
    for(int i = 0; i < arr.length; ++i){
        if(arr[i].equals(value)){
            return i;
        }
    }
    return DEFAULT_RETURN_VALUE;
}


Actually, it works. But I would like to know whether it is correct or
  not.

It works because you create new instance of parent and access it there:

this.a = new A( this );

The correct way (for inheritence) is to set child's prototype and constructor:

A.prototype = new B();
A.prototype.constructor = A;

For more explanation, have a look at this question.


If you look for performance, you'd better rely on the framework dictionary. You can use the Dictionary<string, List<object>> to do what you need. When you add a new key and value, look if the key already exists. If so, add the value to the array and don't add the key.


Creating an Entity, persisting it to the DB, and sending a welcome email

Just some thoughts:

1) parameters instead of properties - createUser function has various user data as parameters. I think it is better to have a single object with properties instead (e.g. $userData). If information is added to the user entity, properties are added, not extra parameters in the function.

2) auto mapping - in many cases members/properties must be copied from one object to another (e.g. data coming from a form into an object to be persisted in the database). This means tedious work for the programmers, so this one reason auto mappers were invented. For PHP, Nylle is one (never used, though).

A mapper is handling copying of data from an object to another based on property names, by default (a case of convention over configuration).

For your particular case, assuming that user data comes in a $userData instance and that it has the same properties, it should look like this:

$user = $mapper->Map(new \Affiliate(), $userData);

Of course, for several properties, it is overkill (and also the configuration is more repugnant that the bigger brother's one - .NET Automapper), but may be useful when dealing with more.

3) Separation of concerns - you can (should) separate notification sending from user creation, as they different things and also automatic tests should treat them differently (e.g. you can automatically create test users on some test database, but surely you do not want to send lots of test e-mails / mock e-mail sending):

createUser may return the newly created user
another function may use this instance to send the e-mail

4) Error logging - Db persist failure is handled only by returning false to the caller. It is recommended to log these failures using a logging framework or a custom one.


Legacy Data and Current System Data Merged together in a single SQL Database

Obviously table1 is not a very good name, so I'll leave that as that. The other thing that immediately jumps at me is the poor formatting.

It's hard to read multiple items strung across a single line. Doubly when they're aliased.

SELECT
    CaseParticipantTable.DOCK_NO AS CaseNbr, ActivityTable.JUDGMENT_DATE AS JudgmentDate, ActivityTable.AMOUNT_TYPE AS AmountType,
        ActivityTable.AMOUNT AS JudgmentAmount, CaseParticipantTable.FILING_NAME AS CaseParticipant

Is easier to read like this:

SELECT
    CaseParticipantTable.DOCK_NO AS CaseNbr,
    ActivityTable.JUDGMENT_DATE AS JudgmentDate,
    ActivityTable.AMOUNT_TYPE AS AmountType,
    ActivityTable.AMOUNT AS JudgmentAmount,
    CaseParticipantTable.FILING_NAME AS CaseParticipant

Similarly, I don't like having the entire JOIN...ON statement on one line. I usually put the ON statement on the next line, indented one tab.

FROM
    UJSJudgementQuery.dbo.CJ_SC_CASE_PARTICIPANT AS CaseParticipantTable
    INNER JOIN UJSJudgementQuery.dbo.CJ_SC_JUDGMENT_ACTIVITY AS ActivityTable
        ON CaseParticipantTable.DOCK_NO = ActivityTable.DOCK_NO

I do like how you start an indented new line after keywords, but you don't do it consistently. This WHERE suffers from that. I also recommend a new line for the items in your in List.

WHERE
    CaseParticipantTable.FILING_NAME IN (
                                    '/CountyName COUNT AUDITORS OFFICE',
                                    '/CountyName COUNTY AUDITOR',
                                    '/CountyName COUNTY AUDITOR''S OFFI',
                                    '/CountyName COUNTY AUDITORS OFFI',
                                    '/CountyName COUNTY AUDITORS OFFIC',
                                    '/CountyName COUNTY AUDITORS OFFICE',
                                    '/CountyName COUNTY TREASURER',
                                    '/CountyName County Treasurer',
                                    '/CountyName COUNTY/ AUDITOR',
                                    '/CountyName COUNTY/AUDITORS OFFIC',
                                    '/CountyName COUNTY C/O AUDITORS')
    AND AMOUNT > 0

You may have your reasons for it, but there's a lot of duplication in your IN statement. Consider whether or not a LIKE...OR...IN type statement would meet your needs. It will perform worse, so test it against your original to see how bad the performance hit will be.

WHERE
    CaseParticipantTable.FILING_NAME LIKE '/CountyName%COUNT%AUDITOR%'
    OR CaseParticipantTable.FILING_NAME IN(
                                    '/CountyName COUNTY TREASURER',
                                    '/CountyName County Treasurer')

This is an adhoc query now, but many many adhoc queries make their way into production use. Never should you Select * in a production query. It often forces a table scan where a more efficient query might be found otherwise.


Controller scope inside Directive with Angular

Now I'm using a function name defined inside ShopController in the Reclaim Directive... it seems like a bad practice.

Yep, this kind of code will be hard to debug and maintain.

You're depending on the existence of reclaim to be somewhere in the scope chain, on some controller enclosing your directive.
There's no indication whenever you use the directive that reclaim is missing in the scope. The directive will fail only if you click it.
Without proper tools like Batarang, in a highly nested controller structure, reclaim will be hard to find when you don't know which controller it resides.

If <reclaim-directive> isn't that huge, and is not used anywhere else independently, then it's contents should belong to <prize-directive>.

If <reclaim-directive> is big and independent enough to be a separate directive, then consider making it a sibling of <reclaim-directive>. That way, you avoid the extra nested level:

<div ng-controller="ShopController as shop">
  <prize-directive ng-repeat="prize in prizes"></prize-directive>
  <reclaim-directive></reclaim-directive>
</div>

Most importantly, instead of depending on implicit existence of reclaim in the scope, why not provide it to the directive explicitly? Construct a scope for the directive, which accepts a binding of reclaim. I believe this is the way to do it:

<prize-directive ng-repeat="prize in prizes" on-reclaim="reclaim"></prize-directive>

angular.module('app.directives').directive('prizeDirective', function () {
  return {
    restrict: 'E',
    templateUrl: 'js/directives/PrizeDirective.html',
    scope: {
      onReclaim: '='
    }
  };
});

<!-- onReclaim assigned to on-reclaim comes from the prizeDirective -->
<reclaim-directive on-reclaim="onReclaim"></reclaim-directive>

angular.module('app.directives').directive('reclaimDirective', function () {
  return {
    restrict: 'E',
    template: '<button ng-click="onReclaim(prize)">Resgatar</button>',
    scope: {
      onReclaim: '='
    }
  };
});