Simply implementing a repeating HTML form with a total

function doCalc(el) {
  price = document.getElementById("price").value;
  console.log("price", price);
  el.total.value = (price * el.quantity.valueAsNumber * el.wattage.valueAsNumber / 1000 * (el.minutes.valueAsNumber / 60) / 100).toFixed(2);
}

Don't forget to use var when declaring variables. Not doing so will cause JS to declare it in the global namespace, which anyone can clobber. There may even be a price global existing already, and you just replaced its value.
Use the browser debugger and plant breakpoints in the source code. It's better than peppering your code with console functions.
Notice that your HTML is littered with JS. Use addEventListener instead of inlining your event handlers. Keep JS just JS, and HTML just HTML.

function addRow() {

  var itm = document.getElementById("template");
  var cln = itm.cloneNode(true);
  document.getElementById("repeatafterme").appendChild(cln);

}

The problem I see with cloneNode is that it carries over some state from the cloned nodes, which can be a problem.

var container = document.createElement('div');
var template = document.getElementById('template').innerHTML;

container.innerHTML = template;
container.getElementByClassName('some-input')[0].value = '';
somewhere.appendChild(container);

One solution would be to create an empty
 using document.createElement, and populate it using innerHTML with a string form of the template. Look for the elements whose values need replacing, then append that div to the DOM.

function grandTotal() {
  t = document.getElementsByName("total");
  gt = 0.0;
  for (i = 0; i < t.length; i++) {
    console.log(t[i].value);
    gt = parseFloat(gt) + parseFloat(t[i].value);
  }
  console.log("Grand total:", gt);
  document.getElementById("grandtotal").value = gt.toFixed(2);
}

Same as before, don't forget var.
Same as before, don't use console.
When parseFloat receives an input that isn't starting with a number, it will return NaN. Further math with NaN will make the results NaN. You should always check the result of string-to-number conversion functions.

In the real world, nobody uses vanilla JS for this. I suggest you start looking into frameworks like Angular to do this repetitive task for you. With most frameworks, you only have to worry about operating with data and templates, and the frameworks do the heavy lifting.

// You worry only here. Angular binds the data so changes in the input
// automatically reflect in the object made as the model.
$scope.rows = [{ id: 1, name: 'washington', value: 19.99 }, ...];
$scope.grandTotal= function(){
  return $scope.rows.reduce(function(partial, value){
    return partial + value;
  }, 0);
}

// You don't have to muck around with DOM
Grand Total{{ grandTotal() }}

    <input type="text" model="row.id">
    <input type="text" model="row.name">
    <input type="text" model="row.value">

Moving down closer to lower-level code. In PHP, you can represent a nested, repetitive structure with some trickery in the form name.

<input type="text" name="foo[]" value="1">
<input type="text" name="foo[]" value="2">
<input type="text" name="foo[]" value="3">
// Becomes ["1", "2", "3"]

<input type="text" name="foo[a]" value="1">
<input type="text" name="foo[b]" value="2">
<input type="text" name="foo[c]" value="3">
// Becomes ["a" => "1", "b" => "2", "c" => "3"]

<input type="text" name="foo[0][a]" value="1">
<input type="text" name="foo[0][b]" value="2">
<input type="text" name="foo[1][a]" value="3">
<input type="text" name="foo[1][b]" value="4">
// Becomes [["a" => "1", "b" => "2"], ["a" => "3", "b" => "4"]]

We can do the same thing in JS with a few tools. First, we can use Mustache to render the template in the same manner. To get the values in their nested form, you can use the serializeObject plugin.

// var rows = [{ id: 1, name: 'washington', value: 19.99 }, ...];
// Mustache.render(template, { rows: rows });

<form name="item-form">

    {{# rows }}

      <input type="text" name="items[{{ id }}][id]"/>
      <input type="text" name="items[{{ id }}][name]"/>
      <input type="text" name="items[{{ id }}][value]"/>

    {{/ rows }}

</form>

// var data = $('form[name="item-form"]').serializeObject();
// { items: [{ id: 1, name: 'washington', value: 19.99 }, ...], }


Keep your imports grouped. From PEP 8.

Imports should be grouped in the following order:

  standard library imports
  related third party imports
  local application/library specific imports

Follow Python's EAFP principle instead of checking if something exists. Plus when it comes to folder creation it will also help you avoid race-condition.

import errno

try:
    os.mkdir(log_path)
except Exception as e:
    if e.errno != errno.EEXIST:
        # If error is something other than file
        # path already exists then handle it here.
        pass

Note my use of except Exception as e here instead of except Exception, e. The latter syntax is deprecated and has been removed in Python 3. Hence go for as based format.

Your try-except block is huge. Cover minimum statements at once, it will help you in narrowing down the actual problem easily and you will be able to show a much better error message to user. Have multiple try-excepts as long as they don't make the code too unreadable.

Instead of dealing with sys.argv you could use the arsparse module to handle command line args in much better way.

error_message = "" statement is not required. You can simply define it wherever you need it instead of defining a default value.

[1::] and [2::] can be simply written as [1:] and [2:] respectively.

The IndexError at the end is redundant because you're already checking for if not [1::] earlier and exiting the script right away, hence you would never hit that exception. Note that slicing never raises IndexError.

call.communicate("Running remote command...") returns both STDOUT and STDIN. You can consider using them separately.

Plus you could also check the status code by doing call.returncode. A non-zero exit code means an error.

log_path = "C:\\Users\\{}\\AppData\\pyshell".format(getpass.getuser())

A hard-coded path is not a good idea. Perhaps ask the user for a path?

You can also get path to user's home directory using os.path.expanduser.

log_path = r"{home}\AppData\pyshell".format(home=os.path.expanduser('~'))

Note that I also added r"" so that we can simply use a single backslash.


Instead of storing all the values you're trying to draw, it might be more efficient to just get the slope of the drawn line, and compute dashes at draw time.

Considering that there's a lot of mirrored code here, consider using a point class to handle both the x and the y values at the same time!

class Point:
    # constructed using a normal tupple
    def __init__(self, point_t = (0,0)):
        self.x = float(point_t[0])
        self.y = float(point_t[1])
    # define all useful operators
    def __add__(self, other):
        return Point((self.x + other.x, self.y + other.y))
    def __sub__(self, other):
        return Point((self.x - other.x, self.y - other.y))
    def __mul__(self, scalar):
        return Point((self.x*scalar, self.y*scalar))
    def __div__(self, scalar):
        return Point((self.x/scalar, self.y/scalar))
    def __len__(self):
        return int(math.sqrt(self.x**2 + self.y**2))
    # get back values in original tuple format
    def get(self):
        return (self.x, self.y)

def draw_dashed_line(surf, color, start_pos, end_pos, width=1, dash_length=10):
    origin = Point(start_pos)
    target = Point(end_pos)
    displacement = target - origin
    length = len(displacement)
    slope = displacement/length

    for index in range(0, length/dash_length, 2):
        start = origin + (slope *    index    * dash_length)
        end   = origin + (slope * (index + 1) * dash_length)
        pygame.draw.line(surf, color, start.get(), end.get(), width)


This should do it:

S = np.sum((east*a[:, None, None] + north*a[:, None] - tp)**2, axis=-1)

But if the east north and tp arrays are large it may actually perform worse, as it avoids looping but creates an intermediate array of a.size**2 * east.size items.

If you expand your expression, you could also do:

e2 = np.dot(east, east)
n2 = np.dot(north, north)
t2 = np.dot(tp, tp)
en = np.dot(east, north)
et = np.dot(east, tp)
nt = np.dot(north, tp)

a2 = a*a

S = (e2*a2[:, None, None] + b2*a2[:, None] + t2 +
     2*en*a[:, None, None]*a[:, None] - 2*et*a[:, None, None] -
     2*nt*a[:, None])

which should give the same result without the ginormous intermediate array.


Python exception handler to recommend package

An ImportError instance doesn't have a replace method.

You can use e.name instead of messy string replacements.

Instead of '%s' % x, it's recommended to use '{}'.format(x).

The example output is not what you posted, but actually this:

  'Error: Try sudo pip install Crypto'

That is, it's surrounded by single quotes, because you wrote as "'some text'".
Probably you want to remove those single quotes inside the string.

What does the message even mean?

This would make a lot more sense:

  Error: could not import 'Crypto'. Try installing with: pip install --user Crypto

Last, but most importantly, please don't recommend to install Python packages system-wide. This is a more sensible recommendation:

pip install --user the_package

This doesn't need sudo, as it will install the package in the user's home directory, not system-wide.

Putting it together:

try:
    import somename
except ImportError as e:
    sys.exit("Error: could not import '{0}'. Try installing with: pip install --user {0}".format(e.name))


Controller method to update properties of a request

I find the second aproach if better for these reasons:

You dont't have to specify all properties but only those that change
You immediately know if the specified Id is correct because

  If an entity with the given primary key values exists in the context, then it is returned immediately [..]. Otherwise, a request is made to the store for an entity with the given primary key values and this entity, if found, is [..] returned. If no entity is found in the context or the store, then null is returned.

You don't have to manually set the modified properties as modified (unless you've disabled tracking) becasue

  this entity, if found, is attached to the context

so EF will figure out the properties that changed. All you need is:

var model = _context.Requests.Find(request.Id);

// check if model == null and handle it apropriately

// update the properties
model.Status = request.Status;
model.AffiliationId = request.AffiliationId;
model.IssueId = request.IssueId;
model.RequestTypeId = request.RequestTypeId;
model.LastModificationDate = DateTime.Now;

// no need to attach it or set properties as modified
// EF already knows this model and can track changes

// save changes
_context.SaveChanges();

I'd say this is more secure as you work with an entity that really exists, in case someone tried to post an invalid Id. Less work becasue EF handles tracking and ataching the entity thus less error prone.

source: DbSet.Find Method


Find if a part of the integer from another integer is divisible by 7?

I'm not sure why you think the second one is "optimized"; the former at least looks faster to me.

Don't name variables temp - it tells you nothing about the actual job of the variable. q is also a bad name'; num_iters is clearer, and i is not used so just use an underscore instead.

Don't pre-initialize values, in this case temp. Assign to it only when you need to.

Don't use input - always use raw_input and explicit conversions.

Then you have

inp = raw_input()
num_iters = int(raw_input())

for _ in range(num_iters):
    l, r = map(int, raw_input().split())
    temp = int(inp[l - 1:r])

    if temp % 7 == 0:
        print "YES"
    else:
        print "NO"

which is simple enough to basically be ideal. A more advanced programmer might want to handle errors or put code into functions, but the advantages of those only really apply to larger programs.


Since your min() in your implementation returns an int, I would modify the type of Node.item to int.
Since we are dealing with a stack of (primitive) integers, I would rename MinElementInStack to IntStack.
Next, why not rename Node to IntStackNode?
Both the fields in Node can be specified as private final + you could add getters for the two fields.
You could define Node as an inner static class in your actual stack class.
pop() should return the integer datum associated with the popped node.
Both pop() and min() should throw EmptyStackException whenever the stack is empty.
I would add the field size to the stack, and the methods size() and isEmpty() which rely on the field size.
Instead of print(), I would override public String toString().
You are overkilling it in the push, mainly due to the fact that you create the new node more than once, and rename data to toBePushedInt.

Summa summarum

All in all, I had this in mind:

import java.util.EmptyStackException;
import java.util.Scanner;

public class IntStack {

    private static final String STRING_BEGIN = "[";
    private static final String STRING_END   = "]";
    private static final String SEPARATOR    = ", ";

    private static final class IntStackNode {

        private final int datum;
        private final IntStackNode previous;
        private IntStackNode previousMinimum;

        IntStackNode(final int datum, final IntStackNode previous) {
            this.datum = datum;
            this.previous = previous;
        }

        int getDatum() {
            return datum;
        }

        IntStackNode getPreviousNode() {
            return previous;
        }

        IntStackNode getPreviousMinimum() {
            return previousMinimum;
        }

        void setPreviousMinimum(final IntStackNode previousMinimum) {
            this.previousMinimum = previousMinimum;
        }
    }

    private IntStackNode top;
    private IntStackNode minimum;
    private int size;

    public void push(final int datum) {
        IntStackNode newnode = new IntStackNode(datum, top);

        if (isEmpty()) {
            minimum = newnode;
        } else if (minimum.getDatum() > datum) {
            newnode.setPreviousMinimum(minimum);
            minimum = newnode;
        }

        top = newnode;
        ++size;
    }

    public int pop() {
        if (top == null) {
            throw new EmptyStackException();
        }

        final IntStackNode ret = top;

        if (minimum == ret) {
            minimum = ret.getPreviousMinimum();
        }

        top = top.getPreviousNode();
        --size;
        return ret.datum;
    }

    public int min() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }

        return minimum.getDatum();
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        IntStackNode node = top;

        if (top == null) {
            return STRING_BEGIN + STRING_END;
        }

        final StringBuilder sb = new StringBuilder(STRING_BEGIN);
        sb.append(top.getDatum());
        node = top.getPreviousNode();

        for (int i = 1; i < size; ++i) {
            sb.append(SEPARATOR).append(node.getDatum());
            node = node.getPreviousNode();
        }

        return sb.append(STRING_END).toString();
    }

    public static void main(final String[] args) {
        final IntStack stack = new IntStack();
        final Scanner scanner = new Scanner(System.in);

        loop:
        while (true) {
            System.out.print("> ");

            final String command = scanner.next().trim().toLowerCase();

            switch (command) {
                case "push":
                    doPush(stack, scanner);
                    break;

                case "pop":
                    doPop(stack);
                    break;

                case "print":
                    System.out.println(stack);
                    break;

                case "min":
                    doMin(stack);
                    break;

                case "quit":
                case "exit":
                    break loop;

                default:
                    System.out.println("Unknown command: \"" + command + "\"");
            }
        }
    }

    private static void doPush(IntStack stack, Scanner scanner) {
        int datum;

        try {
            datum = scanner.nextInt();
        } catch (NumberFormatException ex) {
            System.out.println("ERROR: An integer is required.");
            return;
        }

        stack.push(datum);
    }

    private static void doPop(IntStack stack) {
        try {
            stack.pop();
        } catch (EmptyStackException ex) {
            System.out.println("ERROR: Popping from an empty stack.");
        }
    }

    private static void doMin(IntStack stack) {
        try {
            System.out.println(stack.min());
        } catch (EmptyStackException ex) {
            System.out.println(
                    "ERROR: Asking for minimum element from an empty stack.");
        }
    }
}

Hope that helps.


Looking at the code, it is clear that you took a part from existing C code.
Overal the code is acceptable, although when I should accept it, I would recommend some changes.

As already indicated in another answer, you could use scoped enums. This would remove the L_ prefix, unfortunately if you would use <windows.h>, you have to find a new name for ERROR.

The log_colors variable uses some strings to color the terminal. A comment about the actual colors would be nice.  Separate variables with clear names even better.

vlk_log_internal accepts variadic arguments, which is really good. You could use forwarding references to prevent expensive copies.

The output variable looks strange outside of the if-statement, you could move it in or introduce early return instead.

std::fprintf, is strange in C++ code, I mostly try to get rid of it. This because you have to know the ugly syntax of format strings and it is easy to make mistakes as passing an std::string instead of the char-ptr.
This even leaks into your API.

Next up, you have a define which has to hide the function.
You even nicely put something at the end to allow a semicolon. I don't like, however the other constants force you.

PS: I don't see std::data


If you're about to perform division, you must first check for 0 as the given divisor.  To prevent this, it may be best to warn the user, and make sure they input a valid number before proceeding.

For the exponentiation, you can have a "shortcut" by returning 1 instantly if b is 0.  There's no need to attempt calculations since anything raised to the 0 power is always 1.  You should also handle negative powers in some way.  The code will break if the user inputs such a value for b.  This loop cannot handle all of these possible values.


Combining values corresponding to the same key

Indentation matters a lot in Python.  Please follow the PEP 8 standard, which is 4 spaces.

This code feels very procedural.  Python can be much more expressive than that, if you take advantage of features like list comprehensions.

You've used a lot of variables: line, row, l, keyvalues, items, item, key, value, i, prevval, cols, newvalue, newlist, j, newset — too many for me to keep track of what each represents.  You could reduce the mental load by eliminating variables for ephemeral expressions.  For example, you could eliminate items by writing for item in keyvalues.split(",").

I see that you considered using the csv module, but didn't.  If you did, you could have simplified

for line in sys.stdin:
  line = line.strip()
  row = line.split('\t')

… to for row in csv.reader(fileinput.input(), delimiter='\t').  I recommend fileinput instead of sys.stdin so that the user has the option of passing a filename on the command line.

The getVal(k) function can just be replaced by dict.get(k, None).  It would be better to avoid choosing dict as the name of a variable, since it shadows the dict() constructor.

Suggested solution

import csv
import fileinput

data = {}

for row in csv.reader(fileinput.input(), delimiter='\t'):
    values = [set(col.split(',')) for col in row]
    for key in values.pop(0):   # Numbers in column 0
        data[key] = [
            new_col.union(old_col)
            for new_col, old_col in zip(values, data.get(key, values))
        ]

for key, values in data.items():
    print '\t'.join([key] + [','.join(col) for col in values])


Reading the contents at three URLs using Promises

On the whole it does not look very elegant, especially new function, building functions in a loop and building the Promise array.

I would suggest you invest time in the bluebird Promise.map function and write something like this:

var indexes = [0,1,2];
Promise.map(indexes, function(index) {
    return new Promise(function(resolve) {
        makeRequest(resolve, index);
    });
}).then(function(result) {
    result.forEach(function(item) {
        console.log(item.bl.toString());
    })
});

Other than that, you seem very light on the failure handling, make sure to use catch and reject.


Your code is clean, and (based on my "literature research") your code is right. There are parts of your code though, that should be simplified, and an algorithmic change that should be applied to the way you iterate the doors. Let's go through these in detail...

Your primary loop is incrementing the step variable. You've implemented it like:

var step = 1

while (step != 100) {
  .....
  step = step + 1
}

That is OK, but it would be better to implement it using the range operator (semi-inclusive ... instead of inclusive ..) and a for-loop:

for (step in [1...100]) {
    ......
}

The next issue is algorithmic - you're looping over every door even when you only need to toggle every step doors. This code:

  var stepNextPoint = step
  for (door in doors.get) {
    if (count >= stepNextPoint) {
      door.changeState()
      stepNextPoint = stepNextPoint + step
    }
    count = count + 1
  }

should be inverted, and should become:

  var stepNextPoint = step
  while (stepNextPoint < 100) {
      doors.get[stepNextPoint].changeState()
      stepNextPoint = stepNextPoint + step
  }

These changes all make me realize that the value 100 is repeated in many places... the 100-value should be encoded as a variable, and the whole logic block should probably be expressed as a function call taking 100 as a parameter, and then just called from the main routine.


Some things:

By definition, an N-ary tree is a tree where any node must have no more than N children. However, you never allow the user to define that N, and nowhere do you specify the invariant that for any node, said node must have at most N children. Your tree is not an N-ary tree, it's just a "tree" (with an arbitrary number of children per node).

You're returning bool values in void member(T).

You should decouple traversal from the tree itself. Instead of thinking about traversal like tree.traverse() you should think like traverse(tree).

Reason: to separate and clear up responsibilities. A data structure holds data and nothing else. If you implement traversal behavior inside the tree, the user implementing his own would break any sort of consistency, unless he modifies the structure itself or extends it, which is not exactly desired in this kind of situations (class MySpecialPostOrderTraversalTree : Tree). Furthermore, separating the behavior from the data structure leaves room for other extensions (e.g. a generic traversal algorithm that works on your tree, and on some other kinds of trees, defined by your user).

You should definitely remove the console output from your tree, even if you leave traversal there. At least, you should allow your user to specify a method to call for each visited node. If he wants to print the content of the nodes, he can do it himself. You don't want to give someone a tree that randomly starts to print out stuff to stdout. Also see the concept of mapping functions over collections.

You keep working with values. For example, succ() returns a copy of the vector of children. On large trees this will have a negative effect, constantly copying vectors of elements which contain vectors of elements (and so on) is not exactly a good idea. Look into pointers, and base your tree on them. Start with std::unique_ptr and std::shared_ptr, don't use naked pointers.

See janos's answer for naming suggestions that I feel there's no need to duplicate here :)


Neat idea! Some suggestions:

__exit__ should try to commit or roll back based on whether there is an unhandled exception, should then close the cursor, and should finally unconditionally close the connection. This is one of the main reasons for using a context manager - it is expected to always clean up after itself, leaving the relevant parts of the system in the same state as before using it.
I would reuse the configuration section name as the keys in the dict. That way you don't need to maintain a mapping in your head or the code - what's in the configuration is what you get when you use the context manager.
Rather than opening all connections and then using only one of them, it should open the connection and the cursor with the name passed in. Otherwise you're wasting resources.


Filter to convert duration to hours — in controller or model?

It could go either way; controller or model. Or a service object, though that'd just be a cop-out.

However, note that a "model" is just structured data and associated methods - it doesn't have to be in a database. It's just the most common use of models in a Rails app. But really, the MVC pattern itself doesn't care about databases; a model's a model.

But I'd say there are other issues to tackle first. Like line length. Also that the method is doing several things:

It's validating params
It's converting input
It's assigning values
It's redirecting

That's way too much, if you ask me, though the first two kinda go together. It's also got a magic number (though 3600 is a fairly well-known one), and a magic array.

You're also saying, in a comment, that it "converts time to minutes". But dividing seconds by 3600 yields hours - not minutes. So there's something weird there too.

Anyway, I'd do something like:

DURATION_UNITS = %w(day hour).freeze
SECONDS_PER_HOUR = 60 * 60

def reminder_duration
  duration = params[:store][:store_setting_attributes][:reminder_duration]
  unit = params[:store][:store_setting_attributes][:reminder_unit]
  if DURATION_UNITS.include? unit
    duration.to_i.send(unit).to_i / SECONDS_PER_HOUR
  end
end

You'll either get a number or nil back. You can then assign or redirect as you see fit.

Still not doing great on the line length, though.

I'd consider adding a (non-ActiveRecord) model called Store or Settings or something, and instantiate that with the params hash. Then let the class handle things from there. Something like:

class Store
  DURATION_UNITS = %w(day hour).freeze
  SECONDS_PER_HOUR = 60 * 60

  def initialize(params_hash)
    ...
  end

  def reminder_duration
    ...
  end
end

Then your controller might look like:

before_action :load_settings

def some_action
  if @settings.reminder_duration
    # do stuff
  else
    redirect_to ...
  end
end

private

def load_settings
  @settings = Store.new(params[:store]) # or something
end

Point is you add a level of abstraction and indirection. Your controller is no longer dealing with a complex params hash; that's all hidden away.

That being said, you've still got a really complex params hash, so that Store class (or whatever you call it) still risks becoming a ball of mud. There's only such much you can do to keep things straight; I'd recommend trying to pare that down to something more manageable first.


Send multiple REST requests at the same time. (node)

When you have multiple asynchronous requests to make, and you want them to operate in parallel, usually the appropriate tool to use is Promise.all. You can use it here to wait for the groups and the profile data at once, despite the fact that the two requests are pretty distinct from each other:
async function gatherUserInfo(userId) {
  try {
    const [groups, {username, name}] = await Promise.all([
      getGroups(userId),
      getProfile(userId),
    ])
    return {
      username,
      name,
      groups,
      statusText: await getStatusText(username),
    }
  } catch (err) {
    if (err instanceof NotLoggedInError) {
      return null
    }
    throw err
  }
}

This way, if any one of the Promises rejects, it will be being awaited at that time, so it'll be caught properly.

async function gatherUserInfo(userId) {
  try {
    const [groups, {username, name}] = await Promise.all([
      getGroups(userId),
      getProfile(userId),
    ])
    return {
      username,
      name,
      groups,
      statusText: await getStatusText(username),
    }
  } catch (err) {
    if (err instanceof NotLoggedInError) {
      return null
    }
    throw err
  }
}

async function getGroups(userid) {
  await wait(50)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return ['group A', 'group B'];
}

async function getProfile(userid) {
  await wait(30)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return { username: 'grinchMaster135', name: 'The Grinch' };
}

async function getStatusText(username) {
  await wait(30)
  return 'away'
}

class NotLoggedInError extends Error {}

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

// TEST //

;(async function() {
  console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }
  console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null
})()

You could also have fixed the unhandled rejection by adding a no-op .catch handler to the Promise that was created before awaiting the other Promise:
groupsRequest.catch(() => void 0);

But that makes the code less elegant - I think the Promise.all version is better.

async function gatherUserInfo(userId) {
  try {
    // Don't await yet, so this request can be sent at the same time as future requests.
    const groupsRequest = getGroups(userId)
    groupsRequest.catch(() => void 0);

    const {username, name} = await getProfile(userId)
    return {
      username,
      name,
      groups: await groupsRequest,
      statusText: await getStatusText(username),
    }
  } catch (err) {
    if (err instanceof NotLoggedInError) {
      return null
    }
    throw err
  }
}

async function getGroups(userid) {
  await wait(50)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return ['group A', 'group B'];
}

async function getProfile(userid) {
  await wait(30)
  if (userid !== 12) throw new NotLoggedInError('User not logged in')
  return { username: 'grinchMaster135', name: 'The Grinch' };
}

async function getStatusText(username) {
  await wait(30)
  return 'away'
}

class NotLoggedInError extends Error {}

const wait = ms => new Promise(resolve => setTimeout(resolve, ms))

// TEST //

;(async function() {
  console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }
  console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null
})()


A like/unlike system using MySQL and PDO

This design is a consequence of a poorly designed API. It looks like the client will hit one URL that will cause the like/unlike state to be toggled. But what if the user has multiple tabs open on the same page, then clicks "like" on each one? The user might believe that they are reiterating the "like", when in fact they are undoing it.

My advice is not to toggle the state on the server side. Offer "like" and "unlike" as two separate calls. The client should be responsible for deciding which API to call, based on the client-side state.


Decreasing complexity of loop & Find- VBA

I'll start with the main performance suggestions, but there are a few other issues as well

By far, the most important improvement to be made is to work in memory (arrays, dictionaries)
If moving data to arrays is not possible:

turn off the display, events, calculations, page breaks, etc
use With statements to cache the objects
loops: minimum amount of work necessary, and exit them as soon as possible
one of the few reasons to interact with the ranges is when changing formats for all cells

To illustrate the points I'll provide 2 versions and compare timings

v1 - your code
v2 - screen updating off
v3 - arrays

3 tests each, with 10,000 rows on both sheets:

  v1: 64.164 sec, 40.539 sec, 88.797 sec
  v2: 11.969 sec, 12.055 sec, 11.156 sec
  v3:  0.031 sec,  0.281 sec,  0.033 sec Arrays

Here is Version 2:

Public Sub UpdateData2()
    Dim ws1 As Worksheet, ws2 As Worksheet, r As Long, fr As Long, found As Range, t As Long

    t = Timer
    r = 6
    Set ws1 = ThisWorkbook.Worksheets("Sheet1")
    Set ws2 = ThisWorkbook.Worksheets("Sheet2")
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    With ws2
        Do While .Cells(r, "D").Value > 0
            Set found = ws1.Range("A1:A20000").Find(.Cells(r, "D").Value)
            If Not found Is Nothing Then
                fr = found.Row
                ws1.Range("E" & fr).Value2 = .Range("AA" & r).Value2
                ws1.Range("F" & fr).Value2 = .Range("AB" & r).Value2
                ws1.Range("G" & fr).Value2 = .Range("AC" & r).Value2
                ws1.Range("H" & fr).Value2 = .Range("Z" & r).Value2
                ws1.Range("J" & fr).Value2 = .Range("AG" & r).Value2
                ws1.Range("I" & fr).Value2 = .Range("AD" & r).Value2
            Else
                ' Function // Not done yet
            End If
            r = r + 1
        Loop
    End With
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    Debug.Print "Time: " & Format(Timer - t, "0.000") & " sec"
End Sub

Version 3 (Arrays and Dictionary):

  For dictionaries late binding is slow: CreateObject("Scripting.Dictionary")

  Use Early Binding: VBA Editor -> Tools -> References -> Add Microsoft Scripting Runtime

Public Sub UpdateData3()
    Const FIELDS = 6, MIN_WS2 = 6
    Dim ws1 As Worksheet, ws2 As Worksheet, search1 As Variant, search2 As Variant
    Dim max1 As Long, max2 As Long, ur1 As Variant, ur2 As Variant, uniques As Dictionary
    Dim maps(1 To FIELDS, 1 To 2) As Byte, r As Long, itm As Variant, fld As Long, t As Long

    t = Timer:          Set uniques = New Dictionary
    maps(1, 1) = 5:     maps(1, 2) = 27     'E to AA
    maps(2, 1) = 6:     maps(2, 2) = 28     'F to AB
    maps(3, 1) = 7:     maps(3, 2) = 29     'G to AC
    maps(4, 1) = 8:     maps(4, 2) = 26     'H to Z
    maps(5, 1) = 9:     maps(5, 2) = 30     'I to AD
    maps(6, 1) = 10:    maps(6, 2) = 33     'J to AG
    Set ws1 = ThisWorkbook.Worksheets("Sheet1"):    max1 = ws1.UsedRange.Rows.Count
    Set ws2 = ThisWorkbook.Worksheets("Sheet2"):    max2 = ws2.UsedRange.Rows.Count
    ur1 = ws1.Range(ws1.Cells(1, "A"), ws1.Cells(max1, "J"))
    ur2 = ws2.Range(ws2.Cells(1, "A"), ws2.Cells(max2, "AG"))
    search1 = ws1.Range(ws1.Cells(1, "A"), ws1.Cells(max1, "A"))
    search2 = ws2.Range(ws2.Cells(1, "D"), ws2.Cells(max2, "D"))
    For r = MIN_WS2 To max2
        uniques(Trim$(search2(r, 1))) = r
    Next
    For r = 1 To max1
        itm = Trim$(search1(r, 1))
        If uniques.Exists(itm) Then
            For fld = 1 To FIELDS
                ur1(r, maps(fld, 1)) = ur2(uniques(itm), maps(fld, 2))
            Next
            uniques.Remove itm
        End If
        If uniques.Count = 0 Then Exit For
    Next
    ws1.Range(ws1.Cells(1, "A"), ws1.Cells(max1, "J")) = ur1
    Debug.Print "Rows: " & max1 & "; Time: " & Format(Timer - t, "0.000") & " sec"
End Sub

Other notes related to your code

It's good to qualify references to sheets and ranges, but it's even better to use With statements for performance and maintenance
Select and Activate are almost never needed, and impact performance

Sheets("Sheet1").Select
  Set rgFound = Range("A1:A20000").Find...

should be replaced with Sheets("Sheet1").Range("A1:A20000").Find...

Variable names and sub names like Find, Index, and Row overwrite Excel built-in functions and properties like Sheet1.Row(1), WorkSheet/WorkBook indexes, etc
Make all ranges dynamic, as opposed to Range("A1:A20000") (determine last row and column at run-time)
The Do While loop makes the assumption that a value in column D will never be deleted or empty in the middle of the data
Cells().Value2 is a bit faster than Cells().Value if Currency and Date are not a factor


Comparing two partition functions in Python

These two functions are doing somewhat different tasks. The first one partitions a subrange of a list; the second one may only partition an entire list.

The use of enumerate is not justified in the first loop (index is not being used at all), and is quite suspicious in the second and third. Slices would achieve the same result more pythonically:

partition_point = len(less_than)
A[:partition_point] = less_than
A[partition_point:] = greater_than
return partition_point


Doctrine/Symfony WHERE clause for reports

I would suggest using the QueryBuilder

$em = $this->managerRegistry->getManager();
$qb = $em->createQueryBuilder()
    ->select('u')
    ->from(User::class, 'u')
    ->join('u.meta', 'um'); // doctrine generates the join condition automatically

if (!empty($accountNumber)) {
    $qb
        ->andWhere('u.accountNumber = :acc_number')
        ->setParameter('acc_number', $accountNumber)
}
if (!empty($companyName)) {
    $qb
        ->andWhere('u.companyName = :company_name')
        ->setParameter('company_name', $companyName)
}

// and so on...

return $qb->getQuery()->getResult();


A structure and helper functions for working with polar coordinates

Why the #ifdef guard? It’s not needed in Objective-C since we have the #import directive instead of #include.
Why have the whole thing in the header? The usual solution is to put the function declarations into the header and the implementations into the implementation file.
The difference between PolarEqualToPolar and PolarIdenticalToPolar is not clear to me. I mean, I could assert something from the implementation, but that’s not a good API if I have to.
Related to the previous point, do you realize you’re skating on thin ice when comparing the float components using plain equality (==)? The same disclaimer applies here as for any floating-point comparison, there are nasty suprises caused by precision issues. (See the classical article about What Every Computer Scientist Should Know About Floating-Point Arithmetic.) This is not necessarily a fault of your API or code, it’s just good to be aware of.
Do you really need the performance gains to write this in C instead of Objective-C? Always use high-level code unless the profiler tells you otherwise. Granted, polar coordinates are somewhat on the performant side, but then the modern hardware is so fast you could write the code in high-level Objective-C and still get very usable performance for many use cases.


node.js Syslog server recording to MS-SQL database

From a once over:

Comments should be worth the space they take up, my favourite offender is this one:

// open the database connection
sql.open(conn_str, function (err, conn) {

I want to point to is msnodesql maintained?
I also want to point out that storing uid/pwd in your script can be dangerous, I hope this is not a production database, which does not have sensitive data
As Nelson Menezes mentioned, you should look into using prepared statements
In this block, you should either use 1 comma separated var or semicolons:

var message = msg.toString().replace(/'/g, "''")
var src = rinfo.address.toString().replace(/'/g, "''")
var s = "insert into Incoming(Source,Message) values('"+src+"','"+message+"')";

In a script of this size I would consider merging some statements, this

console.log(s);
console.log(err);
return;

might as well be

return console.log(s, '\n', err);

});// end of sql.open() <- Overkill comments

Still, all in all a solid script.


php most efficient way to check if a variable contains only certain chars

No need for all that. Just use one bracket group, negate it (be prepending a ^), and use the return value directly:

function is_clean ($string) {
    return ! preg_match("/[^a-z\d_-]/i", $string);
}

Here's a quote from the PHP docs:

  Return Values
  preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

In the regex above, we're looking for any characters in the string that are not in the bracket group. If none are found, preg_match will return 0 (which when negated will result in true). If any of those characters are found, 1 will be returned and negated to false.


Throw exception in Spring when loading a file

My first idea was to load the file in the constructor of the class, but I do not know if that is a good practice for Spring.

It takes the lazy-loading out of the lazy-loader, but then you could ask yourself what the remaining uses of the class are.

  As you can see, everytime I have to call to getManifest I throw an IOException.

There are two main ways around this:

1. Use UncheckedIOException to wrap IOException:

    public Properties getManifest() {
      if (p == null) {
        p = new Properties();
        try {
          p.load(servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"));
        } catch (IOException ex) {
          throw new UncheckedIOException(ex);
        }
      }
      return p;
    }

This isn't my preferred approach, because all this does is evade the radar, basically. If you're in a pinch, though, this will do the trick. Mind: UncheckedIOException is not a type of IOException.

(On another note: you probably need to mark p as volatile!)

2. Move the loading to an initialization method:

    public Properties getManifest() {
      return p;
    }

    @PostConstruct
    public void init() throws IOException {
      p = new Properties();
      p.load(servletContext.getResourceAsStream("/META-INF/MANIFEST.MF"));
    }

This approach has the added benefit of being thread-safe: no need to fence access to p, and no risk of having a bean in an inoperable state, or filling the log with errors.


Legibility of code with ternary operators in Python

I think there is nothing wrong with using boolean-valued expressions to compute boolean results, instead of if/elif/else statements. However, it is still important to write these expressions clearly. Most of your expressions can be simplified, and none of your expressions actually require using the ternary operator.

If you write a ternary operator where the true-branch has the value True and the false-branch has the value False, then the ternary operator is superfluous.

If the condition is a boolean already, such as True if column['hidden'] != 0 else False, then you can simply write column['hidden'] != 0 as this will already be either True or False as required.

If the condition is not necessarily a boolean, e.g. True if my_list else False (not from your example) where my_list is a list and the condition tests if it is non-empty, then you can simply write bool(my_list) to calculate the boolean result you want.

When you have a condition like isCalendar or isString and not isFile which has both and and or, I recommend always using brackets to clarify the order of operations. Not everyone knows that and takes precedence over or, and even if they do know this, they may not know that you knew, and might trust the code less. Write isCalendar or (isString and not isFile) to make clear what this code does; or if you wanted it to be (isCalendar or isString) and not isFile, write that.

The expression for isReadOnly is very long, so I suggest splitting this over multiple lines. If an expression is inside (parentheses), then you can space it across multiple lines however you wish.

By the way, column['type_file'] is True is redundant, assuming column['type_file'] is always a boolean. If it's True, then True is True results in True, while False is True results in False; either way, the result is the same as the original value of column['type_file']. Imagine writing x + 0 where x is a number; it won't change the result, so you might as well just write x.


I meant to write one or two brief points when I started writing this, but erm, ended up a bit more :).  Anyway, some of the stuff is quite briefly explained, so if anything needs more elaboration/defense, let me know and I'll edit in more information.

SQL Injection

Your query that checks for the username is open to SQL injection.  You should use prepared statements.

Don't pass in the username

If you pass the username to check() instead of to the constructor, the object can be reusable.

public function check($username) { ... }

Allow configuration

You might as well allow $_minimumChars to be configured.  There's a lot of ways to go about this, but as long as it's only one configuration item, the easiest way would be an argument in the constructor:

public function __construct(mysqli $conn, $minimumChars = 8)
{
    $this->_conn = $conn;
    $this->_minimumChars = $minimumChars;
}

Be strict about types when possible (and reasonable)

If the signature is:

public function __construct(mysqli $conn, $minimumChars = 8)

And the object is created accidentally with something that is not an instance of mysqli, the error will be caught much sooner than if the strict check is not there.  Not particularly required, just there's not a very strong reason against it.

Break it up into more classes -- Part 1 - Validators

The benefit of this is very arguable with a small code base, however, later down the road, it will likely be nice.  Consider breaking each validation into its own class:

interface Validator {
    public function isValid($input);
    public function getErrors();
}

//Because I'm lazy :p
class Validator_AbstractValidator {

    private $_errors = array();

    abstract public function isValid($input);

    public function getErrors()
    {
        return $this->_errors;
    }

    protected function _addError($message) {
        $this->_errors[] = $message;
    }

}

class Validator_NoSpaces extends Validator_AbstractValidator {
    public function isValid($input) {
        //You would probably want to add a check that $input can be cast to a string
        if (preg_match('/\s/', $input)){
            $this->_addError("Spaces are not allowed");
            return false;
        }
        return true;
    }
}

class Validator_MinimumLength extends Validator_AbstractValidator {

    protected $_minLength;

    public function __construct($minLength)
    {
        if (!is_int($minLength) && !ctype_digit($minLength)) {
            throw new Validator_Exception("minLength must be an integer");
        }
        $this->_minLength = (int) $minLength;
    }

    public function isValid($input)
    {
        //Once again, should probably have some kind of validation that $input
        //can be cast to a string
        if (strlen($input) > $this->_minLength) {
            return true;
        } else {
            $this->_addError("Input must be at least {$this_minLength}");
            return false;
        }
    }

}

The advantage of this is that it allows you to abstract away the idea of validations, and it allows you to centralize the management of validation rules.  For example, suppose that your username and email address fields both had the requirement that they not contain spaces.

Now, what if you want to change the logic from the regular expression, to a more strict, strpos($input, ' ') === false?  If the validations are all abstracted away, you only have to change this code in one place.  If you've repeated the low level validations inside of your Db_CheckUsername, you have to change it in two places.  (This is one of the major aspects of DRY by the way.)

You may have noticed that the error messages are hard coded.  This would likely not be the desired behavior.  What you could do there is store the errors in some kind of array indexed by error type, and then instead of _addError adding a raw message, it would add an error type (which would map to an error).  (Note: this approach is 100% stolen from the Zend Framework validators :))

Break it up into more classes -- Part 2 - Element

This obviously leaves your code in a rather awkward spot, though the obvious solution of replacing the validations in the check method with the validators is essentially the solution.

What I would do is abstract away the idea of form element.  You could take the idea as far as a you want (rendering, data manipulation, so on), but I'll just focus on validation:

//We want the element to have an isValid method and a getErrors method()
//(you could make a separate interface for this, but really an element is
//just a collection of Validator instances)
interface Form_ElementInterface extends Validator { }

class Form_Element_AbstractElement extends Validator_AbstractValidator implements Form_ElementInterface
{

    protected $_validators = array();

    public function addValidator(Validator $validator)
    {
        $this->_validators[] = $validator;
    }

    public function getValidators()
    {
        return $this->_validators;
    }

    protected function _addErrors(array $errors)
    {
        foreach ($errors as $error) {
            $this->_addError($error);
        }
    }

    public function hasErrors()
    {
        return (count($this->getErrors()) !== 0);
    }

    public function isValid($input)
    {
        foreach ($this->_validators as $validator) {
            if (!$validator->isValid($input)) {
                $this->_addErrors($validator->getErrors());
            }
        }
        return !$this->hasErrors();
    }

}

class Form_Element_Username extends Form_Element_AbstractElement
{
    public function __construct($minLength = 8)
    {
        $this->addValidator(new Validator_NoSpaces());
        $this->addValidator(new Validator_MinimumLength($minLength));
        //...
    }
}

Some of the names have gotten a little bleh, but hopefully the concept is still there.  (I can never decide what to name interfaces/abstract classes...)

I don't particularly like the design of Form_Element_Username there.  I would probably just use the elements from the outside instead of creating a complicated graph of objects and dependencies (a mysqli would have to be passed through there for example).

$username = new Form_Element();
$username->addValidator(new Validator_NoSpaces());
$username->addValidator(Validator_UserNotExists($db));

Or if you decided to take the flexible error message route, it may look like:

$username = new Form_Element();
$username->addValidator(new Validator_NoSpaces(array(
    'messages' => array(
        Validator_NoSpaces::CONTAINS_SPACE => "Usernames cannot contain spaces"
    ),
)));
$username->addValidator(Validator_UserNotExists(array(
    'db' => $db,
    'messages' => array(
        Validator_UserNotExists::USERNAME_EXISTS => "The username provided already exists",
    ),
)));

Note that passing in an array of arguments instead of proper separate parameters is often bad practice.  (In fact, it's definitely bad practice here.)  It has the advantage though of allowing you to easily store data in config files and then construct validators based on that.

Break it up into more classes -- Part 3 - Form

(Not going to write code on this as the concept should be clear by now.)

Just as an Element is a collection of validations, a form is, in a lot of ways, just a collection of elements.  You could extend the idea of elements and validators to entire forms which would provide centralized management of form logic, and much cleaner use than the 10-20 lines it would take to make each element in the way presented above.

class Form_UserRegistration extends Form_AbstractForm
{
    //In the constructor or some kind of setup method (called by the abstract constructor),
    //you would want to a username element, a password element, and so on
}

Then the usage:

$errors = null;
$regForm = new Form_UserRegistration();

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    if ($regForm->isValid($_POST)) {
        //Create the user
    } else {
        //Render these under the form or something
        $errors = $regForm->getErrors();
    }
}

Design note

It's a bit of an odd design to mutate the errors array behind the scenes while only returning a bool from isValid.  In particular, it may be a bit cleaner design to directly return the array of errors.  I didn't go with this approach because it complicates use of the objects, and the framework I'm most familiar with does it with two separate methods, so it's just what I'm used to.

Basically, the isValid method could look like:

For completeness:

public function validate($input) {
    $errors = array();

    if (...) {
        $errors[] = "...";
    }

    return $errors;

}

//Usage:
$errors = $obj->validate($input);
if (count($errors)) {
    //errors
} else {
    //success
}

(Or you could return true in place of the empty array)

ZF Credit

I should mention that Validator and Element concepts are highly based on the Zend Framework Zend_Validate_Interface and Zend_Element_Abstract classes.


Search for names in a hard-coded list of contacts

Structure
It surprises me that promptUser() also performs the search.  Amongst other things, this makes it harder for you to test the prompting, and it makes it harder to re-use the function for something else.
I would expect main() to look like this:
public static void main(String[] args)
{
    String search_string
         = promptUser("Enter a name or characters to search for: ");
    searchAndDisplay(search_string);
}

We need to modify promptUser() to accept an argument and return a value:
public static String promptUser(String prompt) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println(prompt);
    String userSearch = keyboard.nextLine();
    keyboard.close();
    return userSearch;
}

I hope you see how it has become more reusable.
Data structure
We would like to be able to separate the search and display parts of searchAndDisplay() (because one day, we'll want to search and update, or search and remove).  That's hampered at the moment because each record is scattered across two lists (and we have a weakness that the two lists need to be kept aligned with each other).
Instead, it will be easier to work with a single list of records.  Let's define a Record structure that looks something like:
public class Record
{
    String name;
    String phone;
}

Now, if we have a list of Record, we can have a search() function that returns a Record and a display() function that accepts a record and prints it.  I'll let you fill in the rest of Record - you'll want at least a constructor, and probably accessors and a bool matches(String substring).
String comparison
Comparing strings by converting both to lower case usually works for English names, but less well in other languages.  For example, it will prevent AMELIE from matching Amélie in French (where accents are not usually kept on upper-case words), and it will miss Groß when searching for GROSS.  There are a couple of Stack Overflow answers that address this (and probably better than my very rusty Java knowledge):

How to check if a String contains another String in a case insensitive manner in Java?
Case-insensitive storage and unicode compatibility

Beware that there are quite a few bad answers on those questions, mostly recommending toLower() or toUpper() as you have now.
You probably want something like
    Pattern search_re = Pattern.compile(userSearch, Pattern.CASE_INSENSITIVE | Pattern.LITERAL | Pattern.UNICODE_CASE);
    for (int i = 0;  i < names.length;  i++) {
        if (p.matcher(name).find()) {
            System.out.println(names[i] + ":  " + phone[i]);
        }
    }

(where Pattern is java.util.regex.Pattern - you'll want to import that).
Obviously you'll need to adapt that a little once you're storing Record objects rather than separated names and phones.


Parsing notification information from distribution lists

The only change I would make would be to remove the two statements where you create the lists sms and email.  They are redundant: by adding the EmailAddress and MobileNumber to the query where you are creating the initialList, you can do a select on the initialList.

var initialList = (from j in JunctionTable
                where listBoxItems.Contains(j.DistributionName)
                join c in contacts on j.ContactID equals c.ContactID
                select new { c.ContactID, c.Surname, c.EmailAddress, c.MobileNumber,
                                j.DistributionName, j.EmailFlag, j.SMSFlag }).ToList();

I changed these more because I like this syntax better than the SQL like Linq.

var emailAddresses = initialList
    .Where(l => l.EmailFlag)
    .Select(l => l.EmailAddress).Distinct().ToList();

var smsMobileNumbers = initialList
    .Where(l => l.SMSFlag)
    .Select(l => l.MobileNumber).Distinct().ToList();


If I were presented with that solution as an answer to an interview question, I would definitely question your judgement and taste, even if the solution worked correctly — which it doesn't.

The value for range, 2147483647, is a magic number, better written as Integer.MAX_VALUE.  However, even if (A > 0) && (A <= range) is true, the reversed result might not fit in an int, in which case Integer.parseInt(…) would throw a NumberFormatException.

I have previously advised you to avoid using floating-point operations when dealing with integer arithmetic.  If your goal is to handle int overflow, then use long.

In any case, using StringBuilder.reverse() is, in my opinion, a bad idea.  CPUs are very efficient at arithmetic, but less adept at handling strings.  Both String.valueOf(int) and Integer.parseInt(String) do a lot of work behind the scenes.  Though the inefficiency is quite tolerable for all practical purposes, I would consider the solution to have missed the mark, if judged as an interview solution.

I'd be happier with a purely arithmetic solution like this, which should be far more efficient, and that demonstrates your ability to write a loop:

public int reverse(int a) {
    long reversed = 0;
    while (a != 0) {
        reversed = 10 * reversed + (a % 10);
        a /= 10;
    }
    return (reversed == (int)reversed) ? (int)reversed
                                       : 0;    // int overflow detected
}

Note that the overflow detection is also much simpler.  There are no special cases — we simply check whether downcasting from long to int can be safely done.  Also note that (a % 10) produces a negative result when a is negative, so that no special handling is needed for negative numbers either.


Optimizing the performance of a nested for loop over millions of messages from SQLite Query - v2

You could save a lot of comparisons if you wouldn't throw away the information where the last comparison ended (at 'break'). What you do is a sort of sliding window: you start at msg[k] and compare at index k+1, k+2,...k+f until the timestamp leaves the 24h range. You do this sequentially, or you could do that with a binary search - the time reduction depends on how big the 'frequency' is on average.

My suggestion to improve deals with the next iteration: instead of comparing at least f-1 values again, do this:

drop the last starting point, i.e. frequency -= 1
skip all the values k+1...k+f as you have counted them already in the last iteration
start comparing at index k+f+1, either sequentially or with binary search. Increment the last value of 'frequency' for each valid comparison.

f in this case is available in 'frequency'.
Think of a sliding window where you advance the window by 1 to the right: drop the leftmost and start comparing one after the rightmost element. This should save you a lot of time (the more, the higher the frequency is on average).


C program to delete each character in s1 that matches any character in s2

This compiles cleanly with no warnings, so a positive there.

You may find it easier to use command-line input rather than fgets() for the following reasons:

You don't need to decide on a maximum input size in advance
You can have any character (including newline) in your strings

On the flip side, you do have to be able to write the strings as single arguments; you'll have to be comfortable with your shell's quoting and character escapes.

I would re-write the main() like this:

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s string chars-to-delete\n", argv[0]);
        return EXIT_FAILURE;
    }

    delete_str(argv[1], argv[2]);
    puts(argv[1]);
}

Two other things I changed:

Error message should go to stderr.  Your use of EXIT_FAILURE is perfectly right, and I've kept that (though I find plain return simpler than exit(), and in C++ it may be better to ensure destructors get called).
We don't necessarily have a terminating newline in the string (as we did with fgets()), so we can use puts() instead of printf("%s", s1) - but well done for avoiding the trap of printf(s1) which would be wrong and dangerous.

Turning now to delete_str itself, you might want to change s2 from char* to const char*, as we're not modifying the second argument.  That helps clarify which argument is which, too.

The first thing I note is that the array indexing *(s1+i) is usually written s1[i], and doing so will make your intent clearer to other C programmers:

void delete_str(char *s1, const char *s2)
{
    for (int i = 0;  s1[i] != '\0';  ++i) {
        for (int j = 0;  s2[j] != '\0';  ++j) {
            if (s1[i] == s2[j]) {
                for (int n = i;  s1[n] != '\0';  ++n) {
                    s1[n] = s1[n+1];
                }
                --i;
                break;
            }
        }
    }
}

One thing that will slow your program down is that each time you delete any of the matched characters, you copy the whole of the rest of s1 to close up the gap.  Instead of doing that, you can keep track of two positions: the next character to be read and the next character to be written.  These will start off at the beginning of s1, but each time a character is skipped, the read position will advance, and the write will not.  I'll call these src and dest, and I'll make them pointers (rather than indexes into s1).  We get to replace the inner (n) loop:

void delete_str(char *s1, const char *s2)
{
    char *dest = s1;
    for (const char *src = s1;  *src != '\0';  ++src) {
        *dest++ = *src;
        for (int j = 0;  s2[j] != '\0';  ++j) {
            if (*src == s2[j]) {
                --dest;
                break;
            }
        }
    }
    *dest = '\0';
}

We can also lean on the standard library.  There's strchr(const char *s, int c), which will return a pointer into s if it contains c, or a null pointer if not.  So we can test if *src is in s2 with a simple call (replacing the j loop):

#include <string.h>

void delete_str(char *s1, const char *s2)
{
    char *dest = s1;
    for (const char *src = s1;  *src != '\0';  ++src) {
        if (strchr(s2, *src) == NULL)
            *dest++ = *src;
    }
    *dest = '\0';
}

We can do better: the standard library also contains strspn and strcspn which tell us how many characters to skip and how many to copy.  We can use that to copy whole chunks of input, like this:

void delete_str(char *s1, const char *s2)
{
    char *dest = s1;
    for (const char *src = s1;  *src;  src += strspn(src, s2)) {
        int n = strcspn(src, s2);
        memmove(dest, src, n);
        dest += n;
        src += n;
    }
    *dest = '\0';
}

I note also that we never use s1 again, so we could just use that in place of dest.

My version

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void delete_str(char *s1, const char *s2)
{
    for (const char *src = s1;  *src;  src += strspn(src, s2)) {
        int n = strcspn(src, s2);
        memmove(s1, src, n);
        s1 += n;
        src += n;
    }
    *s1 = '\0';
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s string chars-to-delete\n", argv[0]);
        return EXIT_FAILURE;
    }

    delete_str(argv[1], argv[2]);
    puts(argv[1]);
}

It is possible (and perhaps faster) to use a table-based approach.  Create an array of booleans (i.e. any integer type, but probably uint_fast8_t from <stdint.h> for speed, or char if size is most important), and toggle each position that's mentioned in s2 (remember to convert to unsigned, as plain char may or may not be a signed type).  You might want to benchmark to see which is faster, and for which inputs:

#include <limits.h>
#include <stdint.h>
#include <string.h>

void delete_str(char *s1, const char *s2)
{
    typedef uint_fast8_t flag_type;
    flag_type allowed[1 << CHAR_BIT];
    memset(allowed, 1, sizeof allowed);
    while (*s2)
        allowed[(unsigned char)*s2++] = 0;

    for (const char *src = s1;  *src;  ++src) {
        if (allowed[(unsigned char)*src])
            *s1++ = *src;
    }
    *s1 = '\0';
}


An M field is never pushed. It may only happen as a result of an unfortunate click. Testing for board[r][c] == 'M' in the loop is a waste of time. Test it once, if board[click[0]][click[1]] == 'M', before the loop.
Similarly, you should not bother with neighbors if the field is not blank. A test for board[r][c] == 'B' happens too late. As implemented, for other fields code still compute neighbors - and does nothing with them.
The tests for 0 <= dr < m and 0 <= dc < n may also cause performance issues, and do not look Pythonic. Ask forgiveness not permission, e.g.

    try:
        if board[dr][dc] == 'M':
            mines += 1
    except IndexError:
        pass

Quite a few fields are pushed and inspected multiple times. I am not sure wether it is a bottleneck; however the right-hand and scanline methods of flood fill algorithm do worth investigation.


Try module-pattern, or somewhat like the module pattern, using an IIFE

In your case:

(function(ns){

  ns.showMessage = function(message){
    var el = document.getElementById('example1');
    el.innerHTML = message;
  }

}(this.script1 = this.script1 || {}));

window.onload = function() {
  script1.showMessage('Hello world!');
};

Here's the explanation

//basically, an IIFE is a function that executes itself
(function(ns){

  //in here, ns is a reference to our this.namespace

  //also, this IIFE provides us with a local scope
  //we can declare functions and variables that only this scope, by default, sees

  //a "private" variable
  var priv = "I can only be seen in the module";

  //a "private" function
  function privFn(){
    console.log('I am only usable in the module');
  }

  //a "public", or more accurately, an "exposed" variable
  //we attach it to the namespace
  ns.foo = 'I am an exposed value';

  //an exposed function
  ns.bar = function(){
    console.log('exposed!');
    //with an exposed function, we can also call a private function
    privFn();
  }

//this line creates the namespace or uses an existing one
//it then executes the function, passing the created/existing namespace
}(this.namespace = this.namespace || {}));

And so, using our module:

//we can use the exposed entities
namespace.bar();
//exposed!
//I am only usable in the module <- since bar called privFn, it also prints
namespace.foo === 'I am an exposed value'


It doesn't look very complex to me but the variable names could use some attention, as they're not very descriptive. I'd suggest:

textHidden instead of flag
timesBlinked instead of i
targetElement instead of divID (it's not an id anymore, but the element referred to by the id)

I would also toggle the element visibility instead of removing and adding the text for several reasons, one of them being that removing text can also change the element's height and/or width, which can cause problems with the layout.

if( textHidden ) {
    targetElement.style.visibility = 'visible';
} else {
    targetElement.style.visibility = 'hidden';
}

textHidden = !textHidden;  // flip the flag


Spring service for playing Rock Paper Scissors

SOLID Principles

Single responsibility principle

  A class should have one, and only one, reason to change.

This class should take a PlayerRequest and update the state of the corresponding Players.

The public void play method does more than that, by changing the state of the current game, creating a new round or pushing the latest turn. It would be easier to read the code if the play method was just updating the states and no more. The management of the current Round and Turn should be delegated to a different dependency. Since the Responsibility of the Service class is to update the states, it would be acceptable to have another method wait changing the states to State.WAITING.

Creating unit tests for this class would be then much easier, as we would need only to test the expected change of states and everything else would be mocked.

Open-Closed Principle

  You should be able to extend a class’s behavior, without modifying it.

This block of code, even if moved to another class, could violate the Open-Closed Principle:

      Turn turn = new Turn(player, Enum.valueOf(Move.class, playRequest.getMove()));
      if (currentSession.rounds().isEmpty()) {
        createNewRound(turn, currentSession);
      } else if (!currentSession.rounds().isEmpty()) {
        Round latestRound = currentSession.latestRound();
        if (OVER.equals(latestRound.getState())) {
          createNewRound(turn, currentSession);
        } else if (PLAYING.equals(latestRound.getState())) {
          latestRound.pushLatestTurn(turn);
        }
      }

It is not clear from the code if there are more possible Round States than OVER and PLAYING, but if the Game was extended and there was a new State to be handled (e.g. an EXTRA round), this code block would need to be changed to address it. The solution is to depend upon an abstraction to handle the Round management. Concrete classes will then handle the implementation for the different possible Round States.

Liskov substitution principle

  Let \${\displaystyle \phi (x)}\$ be a property provable about objects \${\displaystyle x}\$ of type T. Then \${\displaystyle \phi (y)}\$ should be true for objects \${\displaystyle y}\$ of type S where S is a subtype of T.

Following this principle will be a consequence of the abstraction made for the previous principle. The derived classes will have to not alter the expected behavior of their parent classes. This principle will be ensured by adding the correct assertions (postconditions) in the unit tests.

Interface Segregation Principle

  Make fine grained interfaces that are client specific.

As @RoToRa suggested, we would need to see the injected interfaces. They should be fine grained in order that the clients (derived classes) will only implement the methods they really use.

Dependency Inversion Principle

  Depend on abstractions, not on concretions.

Here it is pretty straight-forward: the injected dependencies of the GameplayService class should be abstractions (i.e. abstract classes or interfaces). Then it would be easy to change the behavior of the class in case the rules of the Game are extended.

General comments

The best way to check if your code is clean and well-written is to cover it by Unit Tests, even better if it is done using TDD. The complexity of the entire class would be then reduced and the feel of adding collaborators and mocking their behavior would come easier.

Any possible null pointer exceptions, bugs or redundancies in the code would also be avoided during Unit Testing, like this unnecessary if condition of the else branch:

else if (!currentSession.rounds().isEmpty())

I would also use lambdas when working with Optionals and typical Java 8 features, e.g.:

resultOptional.ifPresent(result -> {...})


Multi-client TCP server with a thread for each client and DB connection pool

I am not sure how QThreads work:

Is it a wrapper around an OS thread?
Are QThreads pooled?

Assuming a QThread is a wrapper and not pooled.

Then this technique is actually very limiting. The trouble is that threads are relatively expensive to create, in reality you can only run a handful of them simultaneously without cost (creating more than 2x the processors is probably a bad idea), In socket programming most of the threads are idle (network is very slow compared to the speed of the processor).

There is a famous paper on the top c10k. Basically given current network speeds and processor speeds you should easily be able to support 10 thousand simultaneous connections. But using this model you will top out supporting a couple of hundred simultaneous connections.

Basically you want to design your server around a single thread model and use pselect() (though this is now outdated by better options poll(), epoll() and finally LibEvent). Don't bother experimenting with the older versions just jump to LibEvent.


1. You have classes but you do not effectively need them because they do not keep any state (even the applied field is actually unused). In C# you do not have much options (unless they're local) but in JavaScript you can use functions anywhere:

const ruleAddE = (text) => text + "E";
const ruleAddNumberOne = (text) => text + "1";

And so on. Now let's go to the core of your algorithm: the Producer class. Do you need e class here? From the code you posted it seems you don't and again a function is enough. Let me assume that rules is accessed from outside the class then it makes sense to keep it in-place.

constructor. I'm not sure if you want to discard starterString, repeately calling produce() will always work on latest produced string. If this is the intended behavior then you can let it as-is.

createRules. If this is a private method I like to prefix it with _. It's not a rule, not everyone agrees with this and - unlike Python - it does not change method visibility/accessibility. I like it because it's self-documenting and I won't, by chance, use externally a private method (which is an implementation detail). You do not even really need this function because code is reduced to:

this.rules = [ ruleAddE, ruleAddNumberOne ];

Note that your original code is broken because there isn't a method Array.add() but Array.push().

produce. This may be simplified, the same way you'd do in C# using some LINQ:

produce() {
    this.producedString = this
        .rules.reduce((text, rule) => rule(text), this.producedString);

    return this.producedString;
}

2. In short, your code might be:

const ruleAddE = (text) => text + "E";
const ruleAddNumberOne = (text) => text + "1";

class Producer {
    constructor(starterString) {
        this.producedString = starterString;
        this.rules = [ ruleAddE, ruleAddNumberOne ];
    }

    produce() {
        this.producedString = this.rules
            .reduce((text, rule) => rule(text), this.producedString);

        return this.producedString;
    }
}

Note that for undefined and null inputs the result is pretty odd (undefined is converted to a literal string) while you may expect an empty string in this case. If that's your case then change declaration to:

this.producedString = starterString || "";

We're not using Rule class hierarchy but, in general, remember that in JavaScript there isn't a (easy) syntax to enforce an object with a specific base class then, unless, it adds something, you can simply drop it.

3. To answer the question about "do you need a class for Producer?": if you don't need to call produce() multiple times on the same object then you don't even need a class and everything may be reduced to:

const ruleAddE = (text) => text + "E";
const ruleAddNumberOne = (text) => text + "1";

function produce(starterString) {
    const rules = [ ruleAddE, ruleAddNumberOne ];
    return rules.reduce((text, rule) => rule(text), starterString);
}

In general in JavaScript you can use classes when you want to carry state and behavior on the same object but for everything else you may well use plain functions (and if you use modules you do not even need to use classes as namespaces).

4. If you're using a class only to give a chance to the caller to specify a different set of rules:

function produce(starterString, rules = [ ruleAddE, ruleAddNumberOne ]) {
    return rules.reduce((text, rule) => rule(text), starterString || "");
}


Python persistant cache for non-pythonic objects

It seems rather inefficient to reload the cache file on every cache miss. The last part of wrapper() saves the file whenever the cache is updated, so the cache and file should always be in synch.  Loading the file could be moved into outer().


Premature optimization is a bad idea.  Before you try to optimize anything, run a profiler to measure where your bottlenecks are.  Unless you are running this function in a tight loop, it's unlikely that this function will be a bottleneck.

The special cases that you would introduce don't come for free:

The more line of code you write, the more bugs you are likely to have, statistically.
Your unit tests also have to address the special cases.
There is a bit of overhead in checking whether your special cases apply.

Taking all that into consideration, it's almost certainly not worthwhile to add special cases.

The assertion assert args.length > 0 might be inappropriate.  Considering this code in a vacuum, there is nothing to guarantee that that assertion is logically true.  Rather, it's a runtime validation check.  Validation failures should throw an IllegalArgumentException.  They shouldn't be assertion failures.  (Assertions can be disabled, defeating your check.)

If this were a non-public method, and you are sure that you've written your code such that all call sites have at least two arguments, then an assertion might be appropriate.

Here's a philosophical question: should checkNTrue(0) be true or false?  I think it should be true.


You can abstract out the thing that changes, the comparison expression, into a predicate for a template function.

class PriorityMatch
{
    int priority_;
public:
    explicit PriorityMatch(int priority)
        : priority_(priority) {}

    bool operator()(const Job& job)
    {
        return job->priority == priority_;
    }
};

class DescriptionMatch
{
    std::string substring_;
public:
    explicit DescriptionMatch(const std::string& substring)
        : substring_(substring) {}

    bool operator()(const Job& job)
    {
        return job->description.find(substring_) != std::string::npos;
    }
};

template<class Predicate>
int Queue::remove(Predicate predicate)
{
    // Loop through the queue list
    if (predicate(current_job)) {
        // Remove job.
    }
    // Return the amount of removed jobs.
}

int Queue::remove(const string& substring)
{
    return remove(DescriptionMatch(substring));
}

int Queue::remove(int priority)
{
    return remove(PriorityMatch(substring));
}

Or in C++11:

template<class Predicate>
int Queue::remove(Predicate predicate)
{
    // Loop through the queue list
    if (predicate(current_job)) {
        // Remove job.
    }
    // Return the amount of removed jobs.
}

int Queue::remove(const string& substring)
{
    return remove([](const Job& job){
        return job->description.find(substring) != std::string::npos;
    });
}

int Queue::remove(int priority)
{
    return remove([](const Job& job){
        return job->priority == priority;
    });
}


ES5 class to handle analytics fetching and caching

First of all, why restrict to ES5? Unless you're running/targetting Node < 4 (which is a security hazard, a story for another time), just write using the syntax available to the Node version you're running. Restricting your syntax is unnecessary overhead.

Now you don't need to go OOP on this one. I find that once people resort to OOP, the code usually ends up very boilerplate-y, contains lots of indirection, you worry about what this is. You can simply have a global cache keyed by file name and holds the data and expiry. Keep it simple.

data = data.trim().split('\n').map(function(entry) {
  entry = JSON.parse(entry);
  entry.country = geoip.lookup(entry.ip).name;
  return entry;
});

Why are you storing multiple JSON data inside one file separated by newline? The split by \n can be brittle. If it happens that your writer newlines the data in the middle, this will blow up. If you want to keep this data together, consider writing them in a stringified array instead. Stringified arrays are perfectly valid JSON.

Use promises. Callbacks are so 2 years ago, and are very clunky. There's a module called fs-extra that promisifies fs operations.

And Date.now() is available since ES5 to get the current millisecond timestamp.

const fs = require('fs-extra')
const geoip = require('geoip-native')
const cacheKeepTime = 3600000
const cache = {}

exports.getAnalytics = function(path){
  const currentTime = Date.now()
  const cacheHit = cache[path] && cache[path].data && cache[path].expiry < currentTime

  return cacheHit ? Promise.resolve(cache[path].data) : fs.readFile(path, 'utf8').then(contents => {
    const data = JSON.parse(contents) // Error in a callback rejects the promise
    const expiry = currentTime  + cacheKeepTime

    // Update cache
    cache[path] = { data, expiry }

    return data
  })
}

// Usage
const analytics = require('./analytics')
const someAnalyticsFile = 'path/to/analytics.json'

analytics.getAnalytics(someAnalyticsFile).then(data => {
  // We got data
}, error => {
  // Something blew up
})


Code Style

Although not the most important aspect of programming, I'd recommend using a bit more spaces in your code.

Just a few random example lines:

dp[level][index]=tri.get(level).get(index);
if(dp[level+1][index+1]!=0){
    right=dp[level+1][index+1];
dp[level][index]=tri.get(level).get(index)+Math.min(left,right);

(Note that these four lines do not belong together in the original code)

These would look better as:

dp[level][index] = tri.get(level).get(index);
if (dp[level + 1][index + 1] != 0) {
    right = dp[level + 1][index + 1];
dp[level][index] = tri.get(level).get(index) + Math.min(left, right);

This does improve readability quite a bit, and is the Java conventions.

Exceptions for exceptional cases

if(triangle==null){
    return -1;
}

Instead of returning the special value -1 here, which could be a valid output if your input contained some negative numbers, it is better to throw an exception.

if (triangle == null) {
    throw new NullPointerException("triangle cannot be null");
}

Or, using a Java method call as of Java 7:

Objects.requireNonNull(triangle, "triangle cannot be null");

Last index

When checking if an index is the last index in a list:

if((level+1)==tri.size()){

Then it is more common to compare the actual index, rather than the size:

if (level == tri.size() - 1) {

And as you see, you can remove one set of parameters as well.

Initialization

As all int-arrays are initialized to zero by default, this code does absolutely nothing:

for (int i = 0; i < triangle.size(); i++) {
    Arrays.fill(dp[i], 0);
}

Working backwards

Sometimes when faced with a challenge, it can be a good idea to think: What if I work backwards? Sometimes working from the other direction can be a big advantage. A different approach to this problem would be to work backwards.

     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]

Start at the bottom row. On this row, we can find that the 8 is irrelevant as it is right in the middle of two much smaller numbers that can be reached instead, from the same parents that can reach the 8. The same way, we can see that the 4 is a much worse choice than the 1. So the information we want from that row is [*, 1, *, 3].

Now on to the next row! [6, 5, 7]. We find out that the 6 is totally irrelevant as the 5 can also be reached from the same parent (the 3 above). Additionally, the only child of 5 is 1, but the child of 7 is 3. As 1 + 5 < 3 + 7, 1 + 5 does seem like a better route so far. But to be safe, I would store the sum for each of the current 'nodes'. So for the 5, store 1 + 5 = 6. For the 7, store 3 + 7 = 10.

On to the next row! [3, 4]. Here we can find out that the 3 is much better, as the only way the 4 is relevant is because 3 + 7 = 10. But as 1 + 5 + 3 = 9 is smaller than 3 + 7 + 4 = 14, and the 3 and 4 are neighbors, we can totally forget about the 3 + 7 + 4 = 14 path, as it is now irrelevant thanks to our superior 1 + 5 + 3 = 9 path.

Last row, [2]. Here we don't have any choice, so we just add the 2 to our current 1 + 7 + 3 = 9 path and we end up with 11.

Edit: after some debugging of your code, your approach is actually quite fast and very similar to what I started doing here. We just don't use the same order when iterating over the triangle. But if you want to see what I ended up with, take a look at my question.

The fact that I thought your code was slower than it actually was might be an indication about the readability of your code. I think that by getting rid of the recursion the way I did the actual algorithm used is more apparent, and thus it is more clear that the time complexity is not \$O(2^n)\$ which it looks like at first glance.


Excel VBA object with validated bounds for an interval

As for the first issue

  Is there a way to restrict access to the clsLoad objects in the
  clsLoadStep object to read-only while still letting the definition of
  the clsLoad class have both read and write properties?

I'd say there's only one way to go: remove all Public Property Get ... As clsLoad and substitute them with a couple of Property Get each, as follows:

'''''''''''''''''''''''''
' Max property
'''''''''''''''''''''''''

'''Public Property Get Max() As clsLoad '<--| remove it and replace with MaxValue and MaxSource
'''    Set Max = pMax
''''    UpdateMaxMin
'''End Property

Public Property Get MaxValue() As Double '<--| this will let the user of 'clsLoadStep' class to get the 'Value' property of 'Max' 'clsLoad' object
    MaxValue = GetValue(pMax)
End Property

Public Property Get MaxSource() As String '<--| this will let the user of 'clsLoadStep' class to get the 'Source' property of the 'Max' 'clsLoad' object
    MaxSource = GetSource(pMax)
End Property

where I used the following helper functions:

'helpers
Function GetValue(p As clsLoad) As Double
    If Not p Is Nothing Then GetValue = p.Value
End Function

Function GetSource(p As clsLoad) As String
    If Not p Is Nothing Then GetSource = p.Source
End Function

of course you have to act similarly for Min and Occ properties

As for the second issue

  The clsLoadStep object still needs to be able to tell if the clsLoad
  object's values have changed

I'd put this functionality inside a helper function like follows:

Sub SetIt(load As clsLoad, newLoad As clsLoad, oldLoad As clsLoad, name As String)
    Set load = newLoad '<--| set the object
    If Not oldLoad Is Nothing Then '<--| if there was a "previous" object
        If oldLoad.Value <> load.Value Then MsgBox name & " changed" '<--| check if value changed
    End If
    Set oldLoad = load '<--| update the "previous" object
End Sub

of course you have to set some new fields:

Private pMaxOld As clsLoad
Private pMinOld As clsLoad
Private pOccOld As clsLoad

and exploit it as follows:

'''''''''''''''''''''''''
' Max property
'''''''''''''''''''''''''
Public Property Set Max(ByVal newLoad As clsLoad)
    SetIt pMax, newLoad, pMaxOld, "Max"
    UpdateMaxMin
End Property

and the likes

Finally the clsLoadStep Class code would be:

Option Explicit

Private pMaxOld As clsLoad
Private pMinOld As clsLoad
Private pOccOld As clsLoad
Private pMax As clsLoad
Private pMin As clsLoad
Private pOcc As clsLoad
Private pSource As String

'*****************************************************************
'P R O P E R T I E S
'*****************************************************************

'''''''''''''''''''''''''
' Max property
'''''''''''''''''''''''''
Public Property Set Max(ByVal newLoad As clsLoad)
    SetIt pMax, newLoad, pMaxOld, "Max"
    UpdateMaxMin
End Property

'''Public Property Get Max() As clsLoad
'''    Set Max = pMax
''''    UpdateMaxMin
'''End Property

Public Property Get MaxValue() As Double
    MaxValue = GetValue(pMax)
End Property

Public Property Get MaxSource() As String
    MaxSource = GetSource(pMax)
End Property

'''''''''''''''''''''''''
' Min property
'''''''''''''''''''''''''
Public Property Set Min(ByVal newLoad As clsLoad)
    SetIt pMin, newLoad, pMinOld, "Min"
    UpdateMaxMin
End Property

'''Public Property Get Min() As clsLoad
'''    Set Min = pMin
'''    UpdateMaxMin
'''End Property

Public Property Get MinValue() As Double
    MinValue = GetValue(pMin)
End Property

Public Property Get MinSource() As String
    MinSource = GetSource(pMin)
End Property

'''''''''''''''''''''''''
' Occur property
'''''''''''''''''''''''''
Public Property Set Occ(ByVal newLoad As clsLoad)
    SetIt pOcc, newLoad, pOccOld, "Occ"
End Property

'''Public Property Get Occ() As clsLoad
'''    Set Occ = pOcc
'''End Property

Public Property Get OccValue() As Double
    OccValue = GetValue(pOcc)
End Property

Public Property Get OccSource() As String
    OccSource = GetSource(pOcc)
End Property

'''''''''''''''''''''''''
' Source property
'''''''''''''''''''''''''
Public Property Get Source() As String
    Source = pSource
End Property
Public Property Let Source(ByVal Val As String)
    pSource = Val
End Property

'''''''''''''''''''''''''
' UpdateMaxMin sub - Swap max and min objects if max is less than min
'''''''''''''''''''''''''
Private Sub UpdateMaxMin()
    Dim tmpLoad As clsLoad
    If pMax Is Nothing Or pMin Is Nothing Then Exit Sub
    If pMax.Value < pMin.Value Then
        Set tmpLoad = pMax
        Set pMax = pMin
        Set pMin = tmpLoad
        Debug.Print "Max less than min. Swapped max and min."
    End If
End Sub

'''''''''''''''''''''''''
'helpers
'''''''''''''''''''''''''
Sub SetIt(load As clsLoad, newLoad As clsLoad, oldLoad As clsLoad, name As String)
    Set load = newLoad
    If Not oldLoad Is Nothing Then
        If oldLoad.Value <> load.Value Then MsgBox name & " changed"
    End If
    Set oldLoad = load
End Sub

Function GetValue(p As clsLoad) As Double
    If Not p Is Nothing Then GetValue = p.Value
End Function

Function GetSource(p As clsLoad) As String
    If Not p Is Nothing Then GetSource = p.Source
End Function

an example of usage of this class is the following:

Option Explicit

Sub main()

    Dim load1 As clsLoad, load2 As clsLoad, load3 As clsLoad
    Dim loadStep As clsLoadStep

    Set load1 = New clsLoad
    Set load2 = New clsLoad
    Set load3 = New clsLoad

    load1.Source = "source1"
    load1.Value = 1

    load2.Source = "source2"
    load2.Value = 2

    load3.Source = "source3"
    load3.Value = 3

    Set loadStep = New clsLoadStep
    With loadStep
        Set .Max = load1
        Set .Min = load3 '<--| this will trigger the "swap" functionality inside 'clsLoadStep' class
        Set .Max = load2 '<--| this will trigger the check against the previous 'Max' 'clsLoad' object of 'LoadStep' class
        Set .Occ = load2
        MsgBox .MaxValue '<--| this will return '2'
        MsgBox .Max.Value '<--| though still allowed by Intellisense, this will not compile
    End With

End Sub


How can I decrease code length?

You could split your big for loop into 2 smaller ones. The first one would print all diagonals up to the main one, and the other one the remaining ones.

For instance, let's say there's a matrix like:

1 2 3
4 5 6
7 8 9

Then, your first loop would print 1 4 2 7 5 3 and the second one 8 6 9. The code would look conciser and more readable too:

for (int i = 0; i < N; i++) {
    for (int j = 0; j <= i; j++) {
        printf("%d ", pixel_array[i - j][j]);
    }
}

for (int j = 0; j < N - 1; j++) {
    for (int i = N - 1; i > j; i--) {
        printf("%d ", pixel_array[i][N - i + j]);
    }
}

  How can I improve the efficiency of this program?

I don't think it's possible to make it more efficient than O(n²) as you have to go through all matrix elements to print them diagonally. So, the suggested solution is efficient enough.

  Any other programming practices to be implemented

Rather than using an int type for defining a size of your array, you could use uint32_t (or uint16_t or uint64_t - it depends on your requirements). Your size cannot be negative, anyways. So, change int N = 5; to const uint32_t N = 5.

Rename your array to squareMatrix because you're actually dealing with square matrices in your app.

Also, create a method out of your algorithm block - but I'll leave it up to you.


Review of java interface for constructing brain model

I would consider making this code:

// construct Retina
VisionCell[][] visionCells = new VisionCell[65][65];
for (int x = 0; x < visionCells.length; x++) {
    for (int y = 0; y < visionCells[0].length; y++) {
        visionCells[x][y] = new VisionCell();
    }
}

a factory method on Retina (passing in the dimensions of the cell array) as it will probably be a common thing to create.
Call chains like these nervousSystem.getPNS().getSNS().getRetina() are a code smell. You could model your nervous system as some kind of repository where you can query the individual components like this:

nervousSystem.getRetina();
nervousSystem.getBrain();

or fully generic (additional bonus points ;))

nervousSystem.get<Retina>();
nervousSystem.get<Brain>();

More complex components like Brain can then be modeled in the same way:

nervousSystem.get<Brain>().get<Neocortex>();

This alleviates the caller from having to know the internal structure.
I find it quite weird that your ctor for the NervousSystem only takes some very specific components of individual subsystems. From the looks of it the NervousSystem is composed out of PNS and CNS with SNS being part of  the PNS and Brain being part of the CNS etc. so I'm wondering why the NervousSystem is not being built like that but gets some very specific subcomponents instead.

I would have thought the setup should look something like this (I haven't checked the code on github so the class names are purely guesswork):

Neocortex neocortex = new Neocortex(...);
CerebralCortex cerebralCortex = new CerebralCortex(neocortex, ...);
Cerebrum cerebrum = new Cerebrum(cerebralCortex, ...);

LateralGeniculateNucleus lgn = new LateralGeniculateNucleus(...);
Thalamus thalamus = new Thalamus(lgn, ...);

Brain brain = new Brain(cerebrum, thalamus, ...);
CNS cns = new CNS(brain, ...);

Retina retina = new Retina(...);
SNS sns = new SNS(retina, ...);
PNS pns = new PNS(sns, ...);

NervousSystem nervousSystem = new NervousSystem(cns, pns);

For wiring individual components up you could pass a WiringStrategy into the NervousSystem which decides how things are wired up (so you can simulate broken wiring for example).


__repr__ for a binary tree whose constructor has default arguments

One thing you can simplify is this subexpression:

repr(self.left) if self.left else None

to just:

repr(self.left)

since repr(None) == str(None) == 'None'. Just saves some typing.

Furthermore, when you are doing:

'({}, {}, {})'.format(repr(a), repr(b), repr(c))

that is equivalent to just repring the tuple:

repr((a, b, c))

Other than that, is it worth the added complexity of the replaces? It's not the end of the world that:

repr(BinaryTree(2)) == 'BinaryTree(2, None, None)'

I'd say just keep it simple:

return '{}{}'.format(
          self.__class__.__name__,
          repr((self.value, self.left, self.right)))


return array element if it exists, otherwise null

For the question title, there indeed a null coalescing operator introduced in PHP7:

return $array[$key] ?? null;

which is a shorthand for

return (isset($array[$key])) ? $array[$key] : null;

however, in your code you are using empty() which is different from isset() and for this code there is no shorthand in PHP.

with empty(), your code will also return null if $array[$key] exists but contains an empty-like value, like false, 0, empty array and such


How to improve performace of this Map Reduce function, Python mrjob

Since the reduce function in this case is commutative and associative you can use a combiner to pre-aggregate values.

def combiner_count_words(self, word, counts):
    # sum the words we've seen so far
    yield (word, sum(counts))

def steps(self):
    return [self.mr(mapper_init=self.init_mapper,
                    mapper=self.mapper,
                    mapper_final=self.final_mapper,
                    combiner= self.combiner_count_words,
                    reducer=self.reducer,
                    reducer_final=self.final_reducer)]


There are some obvious targets for refactoring, such as Array.new.push(val) instead of [val], but to me this entire code block stinks. The most obvious smell is the type checking necessitated by a lack of duck typing.

Can you explain more about the tensions that lead to this design? I suspect the best solution is further up the context stack than what you have provided.


Determining if a set of 2d vectors is a valid function

To start, if y == y1 then True else False can be simplified to y == y1:

valid' (((x,y),(x1,y1)):xs) = valid' xs && if x == x1 then y == y1 else True


Removing folders from my rails app with rake

As mudasobwa's comment says, your using the case statement backwards. And wrongly.

You're checking if input contains letters that are not n or N, and if that's true, you delete stuff. So I could type foobar, and it'd delete files. Bad.

Even if I type exit or quit or whatever else to stop the task, it'll happily delete stuff. Even typing cancel would be interpreted as "yes, please delete stuff", since - though it contains an "n" - it contains lots of letters that are not "n".

You also have a (dead) branch for not typing y or Y, though that makes no sense. And you don't have an else branch - not that you need one, but it'd make more sense.

You have a fixme you haven't fixed. Your indentation is missing or wrong. Your message ("About to remove the tmp/letter_opener folder.") doesn't match what the code does.

In all, it's not great.

All you need is this:

namespace :cleanup do
  desc 'Deletes the emails inside tmp/letter_opener folder.'
  task letter_opener_emails: :environment do
    puts "Remove tmp/letter_opener? [yn]"
    if STDIN.gets.chomp =~ /^y$/i
      FileUtils.rm_r("tmp/letter_opener")
    else
      puts "Aborting"
    end
  end
end