React components to render two kinds of form elements

I think I have an understanding of what you are trying to do, but because select has children and and input does not it's a little tricky but this is what I came up with:

import React, { Component } from 'react'
import { render } from 'react-dom'

class FloatingLabel extends Component {
  render() {
    return (
      <div>
        <this.props.render option='Hello'  />
      </div>
    )
  }
}

class SelectDropDown extends Component {
  render() {
    return (
      <select>
        <option>{this.props.option}</option>
      </select>
    )
  }
}

class InputDropDown extends Component {
  render() {
    return (
      <input />
    )
  }
}

render(<FloatingLabel render={SelectDropDown} />, document.querySelector('#root'))

In this example you can create a <FloatingLabel /> component that can either take a SelectDropDown or a InputDropDown component as a prop. You can then render that prop in the FloatingLabel parent and pass whatever props that you need to pass down to the children.

Basically what you would be changing is the everything inside the div except for the label.


Get the brightest rectangle within an image

Performance

Here is one simple suggestion, which doesn't require any real thought, and is simple enough to implement. It will result in only calling GetPixel once per pixel, but obviously has some other costs.

Instead of convolving a whole w*h rectangle over the image, first compute the sum of each horizontal strip of length w and store it in a buffer (essentially the same size as the image). Then compute the average of each h tall vertical strip in this buffer, each of which represents a w*h rectangle in the original image.

My only hesitation with suggesting this, is that currently you seem to deliberately call Average on a collection of pixels, which could give you slightly different results owing to joys of float-point maths (assuming nothing about the implementation). Any such error would, however, be imperceptible, but we don't know what your application is, so it is not for us to say that this isn't an issue (but I would wager it isn't).

Because this is just as an example, and I don't know much about floating point maths, I'll follow suit with the OP and only ever perform additions: I'll keep a queue (e.g. ring buffer) of elements as we scan across and down. You could instead keep a running sum, instead of computing sums over a queue, which would make the algorithm complexity order 2 rather than order 3 (the code in the OP is order 4). This is probably the most sensible change if performance is a serious concern, but I'll let you work out the changes necessary.

I'll ignore the joys of considering the actual memory layout of bitmaps: it might be better to sum across the columns first, and then the width, but I can't remember.

int hSumWidth = bitmap.Width - rectWidth + 1;
int hSumHeight = bitmap.Height;
float[,] hSums = new float[hSumWidth, hSumHeight];

Queue<float> queue = new Queue<float>(rectWidth);

// I would never use `var` in a for-loop; makes it immediately obvious we are using ints and not floats
for (int y = 0; y < bitmap.Height; y++)
{
    for (int x = 0; x < bitmap.Width; x++)
    {
        // this is the only time we call bitmap.GetPixel(,)
        queue.Enqueue(bitmap.GetPixel(x, y).GetBrightness());

        if (x >= rectWidth)
        {
            hSums[x - rectWidth, y] = queue.Sum();
            // if the ring-buffer isn't fixed size, we may have to manually evict the old value at this point
            queue.Dequeue();
        }
    }

    queue.Clear(); // we don't need to do this, but it is much clearer if we do
}

Now we have our 2D buffer of sums of horizontal strips of width w. Now we perform a similar operation to scan down them, and find the 'brightest' rectangle.

I don't see any real reason to keep an actual record of all the rectangles; we can just remember the best as we go along. It will reduce the time complexity (from O(n^2 log(n)) to O(n^2)) and won't clutter the code too much.

queue = new Queue<float>(rectHeight);

float bestAverage = float.NegativeInfinity;
Rectangle bestRectangle = default(Rectangle);

for (int x = 0; x < hSumWidth; x++)
{
    for (int y = 0; y < bitmap.Height; y++)
    {
        queue.Enqueue(hSums[x, y]);

        if (y >= rectHeight)
        {
            float rectangleAverage = queue.Average();

            if (rectangleAverage > bestAverage)
            {
                bestRectangle = new Rectangle(x, y - rectHeight, rectWidth, rectHeight);
                bestAverage = rectangleAverage;
            }

            // if the ring-buffer isn't fixed size, we may have to manually evict the old value at this point
            queue.Dequeue();
        }
    }

    queue.Clear();
}

return bestRectangle;

I have tested this quickly against your test image, and it finds a rectangle in the same place (quick visual inspection, no promises). Your code has an order 4 time complexity; this only has order 3 time complexity, 2 if you replace the queues with a running count. There is really nothing clever going on, but I think it ought to work. A gist of the complete method is provided.

Other

I've changed width and height into rectWidth and rectHeight, so that there can be no confusion.

I think you have an off-by-one error:

for (var x = 0; x < bitmap.Width - width; x++)

Consider if you had a 1*1 image, looking for 1*1 rectangles. This loop would never run, no rectangle would be found, and .First() would crash on the last line.


Lights on: playing with buttons in Javascript

I'll just start by looking at what you have, and then I'll get to your questions. (Edit: Seems I'm retreading a lot of what SirPython already covered. Didn't see that answer before I posted. Apologies for boring the reader, and no plagiarism of SirPython intended. Don't mess with a knighted snake!)

The HTML

The doctype for HTML5 is just <!DOCTYPE html> - there's no 5 in the the doctype declaration.
You're missing a <body> opening tag.
I'd recommend you consistently use quotes around your attribute values. Right now you have id=3 with no quotes. It's perfectly valid to skip them (provided the attribute value doesn't have spaces in it), but more often than not, you end up needing the quotes around other values anyway, so for the sake of consistency: Always use quotes.
I'm not keen on using p elements for the button rows. Semantically speaking they're not really paragraphs, per se. I'd use divs, since they're semantically neutral and more geared toward pure layout concerns.
Avoid style attributes in the HTML. Especially here, as it all repeats verbatim for each button. I'd suggest putting CSS in a style element in the head:

<style>
  button {
    width: 150px;
    height: 150px;
  }
</style>

That'll take care of all of them.
Avoid onclick attributes. They're sooo last century. But seriously, it's generally considered better form to use addEventListener to attach event handlers via JavaScript, rather than having little bits of JS scattered all over the HTML.

If you do use onclick know that you can pass this to the function, i.e. onclick="switch_with_neighbors(this)". In an attribute, this refers to the button itself, so you don't have to go find it again in the function (or repeat the id attribute's value in the onclick attribute).

The JavaScript

The JS naming convention is camelCase, not snake_case. Right now, you end up having to mix the two, since the DOM already uses camelCase (e.g. getElementById) so consistency suffers.
You have a typo that seems to have been repeated (I'm guessing your editor auto-completed it for you): "neightbors". It's also in the HTML.
You have a couple of unintentionally global variables. If you neglect the var keyword, an variable assignment/initialization like foo = bar is interpreted as window.foo = bar, i.e. the variable becomes a property on the window object (which in browser JavaScript means it's a global variable).

The ones I spotted were button in invert_text() and nears in switch_with_neightbors().
The way you track and set a button's state is somewhat brittle, relying on its innerHTML, some type conversion, and manually changing its background color. I'd recommend using classes instead. You can check the presence of a class with someElement.classList.contains("someClass"), and use classList.add/classList.remove or simply classList.toggle to toggle the class on and off.

So for instance you could have a lit class, or more conventionally (though less domain-specific) an active class. The class would define background color, so adding/removing it from the classlist would cause all the effects you want.

Edit: I've added an example at the end of the answer.
There's are a few too many hardcoded bits in the code for my liking. Several hardcoded 9s, and of course the table of neighbors. I'd extract the 9 into a "constant", just so it's not a magic number floating around. As for the neighbors-table, you can work that out at runtime. You don't even need element IDs; a getElementsByTagName or querySelectorAll will return the elements in their document order. So you'll have an array (well, a NodeList instance but for our purposes it's the same) and with a little bit of index arithmetic you can work out the neighbors. It's more code though, so I maybe wouldn't bother too much. Still, the neighbors table just irks me a little.
Speaking of the neightbors (sic) table, note that object properties are always considered strings (more on that later), so using a number literal as a property name is suspect, e.g. { 3: someValue }. In fact, I wouldn't be surprised if some browsers choke on it, since it seems to be bordering on a syntax error (not that I know the ECMA spec by heart).

Basically, you can access object properties with dot notation - i.e. obj.property - or with subscripting like an array - i.e. obj[property]. The first option becomes impossible if you just have a number as the property name, since obj.3 is a syntax error.

It's often better for property names to follow the same rules as variable names, i.e. can't start with a number, have spaces, or just be a number. So e.g. button3 would be nicer.
For bonus points, shove everything inside an IIFE (immediately-invoked function expression):

(function () {
  // all your code
})();

This causes all of your functions to be defined in a local scope, rather than the global window scope. Thus you avoid polluting the global scope (i.e. accidentally overwriting an existing function, or risking other code doing that to you).

One gotcha is that you can't use onclick anymore, since you'd be referring to a function that's no longer in the global scope. There are ways to get around this of course, but again I'd rather not use onclick anyway.
You've got a stray console.log in there. It's not a big deal, but it's the sort of debug cruft that should be removed before you "ship" the code.

Questions

  I put HTML and JavaScript together. Would separating them improve readability?

Yes and no. For larger projects, I'd say use separate files. But for a little experiment like this, it's fine. I'd still avoid the onclick attributes, though, in favor of a cleaner separation.

Note that you can also put your script tag at the end of the body element, in which case you won't need to listen for the DOMContentLoaded event, since all the above will of course have been loaded when the script's evaluated.

  I generate 9 buttons by hand, and I copy-paste the size for each one. Can I avoid so much repetition?

For the button size, see the bit about CSS above. As for creating the buttons, you can do that in JS without too much hassle. And if you do, you can also stick the elements in an array, so you don't need to go through the DOM to find them again. The basic principle would be something like:

var buttons = [];

for(var i = 0; i < ROW_COUNT; i++) {
  var row = document.createElement("div");
  document.body.appendChild(row);

  for(var j = 0; j < COLUMN_COUNT; j++) {
    var button = document.createElement("button");
    button.addEventListener("click", handleClick, false);
    row.appendChild(button);
    buttons.push(button);
  }
}

Maybe you'll want to use a 2D array for the buttons, so it matches the layout (you'll have less index arithmetic to deal with when finding neighbors), but either thing can work.

  I am confused by the looping constructs of JavaScript. Is my use of the for .. in sensible?

Yes, you seem to using it correctly. Edit: Actually, no. I wasn't paying close enough attention. If you had been iterating the neightbors object it'd be cool (and that's what I thought you were doing), but you're iterating the nears array, which is not a job for for..in.

It's common mistake to use the for..in loop for arrays, since other languages use their for..in that way. But JS's for..in is designed to iterate object properties, specifically; not array elements. It'll (seem to) work, since array elements are properties on the array, and thus get iterated. But your intention is not to iterate them as though they were properties; you want to treat them as array elements.

So: Iterating an object? Use for..in. Iterating an array? Use a regular for (or the forEach function).

  I put the neighbours hash inside a function. Is this standard practice? Is this weird?

Well, it doesn't change, so it might as well be outside the function. Any JavaScript runtime from the last decade will no doubt optimize that away, though, so it's not like it's a performance issue or anything (even if it wasn't optimized away, it still wouldn't make a dent in performance). But from a structural standpoint, it's a little iffy to have an essentially constant value be a local variable that's declared and defined on each function invocation.

  I cast variables to different types all the time. Can you help me spot unnecessary conversions?

Yes: All of 'em look unnecessary :)

JS is very loose when it comes to type (sometimes it's just plain weird, but that's another story). So getElementById(3) and getElementById("3") are equivalent. And in the case of your neightbors table, there's a twist: As mentioned, all JavaScript property names are strings internally, so when you say neightbors[parseInt(current, 10)]; you're taking a string, turning it into a number, and then JS turns it back into a string again to do the lookup in the neightbors object's properties. So you're doing the opposite of what's "natural" - and yet it still works :)

Similarly, all DOM attribute values are strings by default (since HTML is all text). In your case you've used single digits as IDs (note: as with object properties it's better to assume that IDs should work as plain variable names and follow those rules), but they're rendered as strings. Funny thing is that a string that's just a plain number will be silently coerced to a number when needed. So for instance, an array lookup like [1, 2, 3]["1"] will return 2 just fine, even though array indices are numbers. And similarly, as you've already seen, object lookups will coerce stuff to strings: ({ 42: "foo" })[42].

The most common source of type-confusion is probably mixing strings and numbers. For instance, 2 + "2" yields the string "22", not the number 4. So in such a case, it's a good idea to explicitly cast/convert your variables - either to achieve to desired outcome (e.g. numeric addition), or just to clarify your intention (e.g. yes, I do want string concatenation).

  Is my code modular enough?

It's nicely divided into functions, but you do have some cross-coupling with the DOM elements (i.e. onclick) and some magic numbers/hardcoding.

Don't know if I'd call it "modular" because there's really only one "module": The game. I'd rather ask if it's "well-factored", and to that I'd answer, yeah, it's not bad at all. But of course, I have also written a huge review (see all of the above) for you to chew on :)

Edit: As requested, here's a simple one-button example of using a class to toggle and keep state:

document.querySelector("button").addEventListener("click", function () {
  // Toggle the "active" class on click
  this.classList.toggle("active");

  // An example of how to test the button's state (check the console)
  if(this.classList.contains("active")) {
    console.log("Button is now on");
  } else {
    console.log("Button is now off");
  }
}, false);
/* base styling */
button {
  width: 100px;
  height: 100px;
  background-color: red;
  outline: none; /* hides the "halo" that otherwise appears when you click the button */
}

/* active/lit styling */
button.active {
  background-color: green;
}
<button></button>


VBA Copy and Delete Rows loop optimisation

I've found that if you are deleting rows in a range you need to create a for loop that starts at the bottom and works your way up.  When you are using the for each loop and try deleting an item out of that range and keep looping it destroys the reference to that range.  The next iteration will throw an error.

Here's an example, (I'm just pulling this out of my head and haven't tested it, but it should get you in the right direction)

...
dim sh1Rows as integer
dim myCell as range

sh1Rows = sh.["A1"].end(xlDown).row

for i = sh1Rows to 1 step -1
    set myCell = sh["A1"].offset(0,i)
    if IsDate(myCell.value) and myCell.value < Date - 456 Then
        sh2.cells(1,sh2.["A1"].end(xlDown) +1).entirerow = myCell.entirerow.value
        myCell.entirerow.delete
    end if
next


URL pattern matching for request blocking

General considerations

You are writing a "denylist". There's some clean and simple denylist rules that can help rule out a lot of things already. One of these rules is denying URLs based on their scheme alone.

A few examples for schemes that you may not have considered:
steam://, file://, sftp://, chrome://, about://

Most of these are URLs you most likely want to block. In that case "inverted matching" behaviour is really useful.

Furthermore denylists usually tend to be used for "overblocking out of caution". I'm not sure how that's for your exact use-case, but if you want that to happen, making your patterns as general as possible is a great idea :)

URI vs. URL:
Something to additionally keep in mind here: URI stands for "Uniform Resource Identifier" and URL for "Uniform Resource Locator". Your code specifically exposes a Uri, not a Url overload for matching. This implies that one should be able to blacklist things like the following URIs:

git@github.com:username/repository.git
mailto:username@example.com
irc://#c-sharp@freenode

If your class is only intended to deal with URLs, you should only expose an overload for Url :)

Personal preferences

I personally very much prefer to use factory methods over constructors to validate arguments. YMMV, but I expect constructors to not throw exceptions.

I also prefer to add braces wherever they delimit a block. I can understand the omission for the argument checking though.

Implementation considerations

I like that you're using a lot of intermediate variables. Some minor naming nitpicks could be had there, but I think this code will get the most benefit from using tuples:

var (scheme, hostAndPath) = SplitSchemeHost(pattern);
var (host, path) = SplitHostPath(hostAndPath);

This allows you to push the index matching behaviour into these methods and keep it out of the constructor. (Minor nitpick: 3 is a magic number in the hostAndPath creation)

Aside from that this code is very clean already. I'd maybe not create the patterns within the interpolated strings, but given the simplicity here it seems appropriate to do so.


Nested if statements with 3 different parameters

Others are giving you refactoring ideas, so I will just focus on one statement in your original code that is repeated 4 times.

allCompleted = ((allCompleted) ? true : false);

Look at this. You are inspecting allCompleted. If the value is true,  you're setting it to true. If it is not true, you're setting it to false. You are setting it to what it already is in a sort of non-intuitive way. You could very well rewrite it as the below and have the exact same meaning.

allCompleted = allCompleted ? allCompleted : allCompleted;

Simplify that to

allCompleted = allCompleted;

And then simplify that to leaving it out altogether.

if(runPart1.Checked)
   if (cmdPart1 != "done")
      allCompleted = false;

Code can be complicated enough as it is. Try not to add further complexity by including code that can be non-obvious in the fact that it does nothing at all!


Scale the ingredients of a recipe up/down

I have edited your little code snippet and wrote it in ES6, cause sooner or later you will need it. Most tutorials are written in ES6.
Mostly you will use a build tool like webpack in building react apps.

Example structure:

dist/

js/

bundle.js

css/

style.css

index.html

src/

libs/ (js libs)
components/
  (one folder for every component to have all files together e.g. css with the use of css modules)

Ingredient/

Ingredient.jsx
Ingredient.css

Ingredients/

Ingredients.jsx
Ingredients.css

App.jsx
style.css

webpack.config.js

Some useful links:

https://github.com/srn/react-webpack-boilerplate
https://github.com/gaearon/react-hot-boilerplate
http://survivejs.com/
https://webpack.github.io/
https://github.com/css-modules/webpack-demo

const RECIPES = [{
    id: 'pasta-dough',
    name: 'Pasta Dough',
    serves: 4,
    ingredients: [
        {quantity: '4', unit: 'eggs'},
        {quantity: '4', unit: 'cups', item: 'flour'},
        // Note that the quantity below would normally be '1/4'.
        {quantity: '.25', unit: 'cup', item: 'olive oil'},
        {quantity: '1', unit: 'tablespoon', item: 'salt'}
    ]
}];

class Ingredient extends React.Component {
    render() {
        let quantity = this.props.quantity * this.props.scale;

        return (

              {quantity} {this.props.unit} {this.props.item}

        );
    }
}

class Ingredients extends React.Component {
    render() {
        return (

                {this.props.ingredients.map((ingredient, i) =>
                    <Ingredient key={i} scale={this.props.scale} {...ingredient} />
                )}

        );
    }
}

class Recipe extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            serves: this.props.serves,
            scale: 1
        }

        this.onChange = this.onChange.bind(this);
    }

    onChange(e) {
        const serves = Math.floor(Math.abs(e.target.value));

        this.setState({
            serves: serves,
            scale: serves / this.props.serves
        });
    }

    render() {
        return (

{this.props.name}

                    Serves
                    <input
                        type="number" min="0"
                        value={this.state.serves}
                        /* TODO: Smarter default step. */
                        step={this.props.serves % 4}
                        onChange={this.onChange}/>

                <Ingredients ingredients={this.props.ingredients} scale={this.state.scale}/>

        );
    }
}

class App extends React.Component {
    render() {
        return

            {RECIPES.map((recipe, i) => {
                return <Recipe {...recipe} key={i}/>;
            })}

;
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('recipes'));
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>


"One specific question I have deals with the unsigned integer I am adding and subtracting from the iterators to move to the next and previous values in the container. Since there is no way to get the type of container for the provided iterators, I do not see a way to get the size_type of the assumed container to add and subtract the correct types rather than just unsigned/signed integers."

I just found std::prev and std::next defined in #include <iterator> which I think would handle some cases of signed/unsigned mismatch I was talking about.

For other cases where you would need to perform more complicated arithmetic, such as division or multiplication, you would use:

std::iterator_traits<BdIterator>::difference_type

std::distance returns std::iterator_traits<BdIterator>::difference_type.

std::next and std::prev take std::iterator_traits<BdIterator>::difference_type as parameters.
Arithmetic on bidirectional iterator may go backwards.

"The fact that I am subtracting prevents me from declaring the minimal Iterator template type as forward iterators (We are moving the iterator backwards). Is there a better way around this or should I just stick to making the minimum BiDirectionalIterators?"

I failed to realize that regardless of whether I use std::prev or not, the algorithm itself relies on moving the iterators both forwards and backwards, and therefore requires BiDirectional Iterators.

There is a more efficient solution that relies on finding a hole and bubbling up the hole to then insert the value into its sorted hole.

// Shift/bubble each element toward the front into a sorted sub-array
template<typename BidirIt, typename Comparator = std::less<typename std::iterator_traits<BidirIt>::value_type>>
void sort_insertion(BidirIt first, BidirIt last, Comparator cmp = Comparator())
{
    using category = typename std::iterator_traits<BidirIt>::iterator_category;
    static_assert(std::is_base_of<std::bidirectional_iterator_tag, category>::value, "This algorithm requires bidirectional iterators.");

    // 1 element containers are sorted; 2 duplicate element containers are sorted.
    if (first != last)
    {
        // Make a hole by removing the element you are checking,
        // and move elements up to that hole until you find the correct position of the element removed.
        // ++cur: Assume the first element is sorted.
        for (BidirIt cur = first; ++cur != last;)
        {
            auto val = std::move(*cur);
            BidirIt next = cur, prev = std::prev(next);
            while (cmp(val, *prev))
            {
                *next = std::move(*prev);
                next = prev;
                if (prev != first) --prev;
                else break;
            }
            // insert value in its sorted hole.
            *next = std::move(val);
        }
    }
}


To build on what else has been posted, validating your inputs is necessary and you have a lot of functions and loops that can be removed.

String module

First, I would like to introduce you to the string module that is part of the python standard library. This module has string constants that you can import and use:

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

Using these would allow you to get rid of your first three functions (letter, upper_case, and special_char). Similarly to what Joe said, it would be better to make your character space a variable to avoid creating extra objects, and remove the all_char function at the same time.

create_password function

This function is clear and works okay, but can also be improved. As you are doing the same operation in each iteration of the loop (random.choice) this is and ideal scenario to use a list comprehension.

# Before
def create_password(password, n):
    for x in range(n):
        password += random.choice(all_char())
    return password

# After
def create_password(n):
    return ''.join([random.choice(all_char()) for _ in range(n)])

This works by creating a list where a random character is selected from all_char() and then joining them all together. The underscore is a 'throwaway' variable here, see here.

Alternatively, as we are already using the random module we could use random.choices (but only in python3.6 and above) as this will return a list of k size:

def create_password(n):
    return ''.join(random.choices(all_char(), k=n))

check_password function

In general, simple statements are better than complex statements. Therefore, I would change the first line of this function to be:

nletter, nupper, nspecial = 0, 0, 0

As this is clearer.

The for loop works, and could be improved by using the string module constants, though they would need to be made into lists.

for x in password:
    if x in list(string.ascii_lowercase):
        nletter += 1
    if x in list(string.ascii_uppercase):
        nupper += 1
    if x in list(string.punctuation):
        nspecial += 1

Another way to test if two strings overlap is to use sets; but this is getting more complex.

Altogether

import random
import string

def create_password(n, chars):
    return ''.join(random.choices(chars, k=n))

def check_password(password):
    nletter, nupper, nspecial = 0, 0, 0
    for x in password:
        if x in list(string.ascii_lowercase):
            nletter += 1
        if x in list(string.ascii_uppercase):
            nupper += 1
        if x in list(string.punctuation):
            nspecial += 1
    if nletter > 0 and nupper > 0 and nspecial > 0:
        return True
    else:
        return False

def main():
    characters = string.ascii_letters + string.punctuation
    n = 0
    while n < 5:
        try:
            n = int(input('Enter your password length (minimum 5): '))
        except ValueError:
            print('Not a number')

    password = ''
    while not check_password(password):
        password = create_password(n, characters)

    print('Generated password : {}'.format(password))

run = True
while run:
    try:
        main()
    except KeyboardInterrupt:
        run = False
        print('Ctrl+c caught exiting')


Find all classes A that implement B and aggregate both A and T to build a map out of them

Should we expect that there are services that have a different type parameter? Because otherwise just a Set of services may suffice, or you can simply remove the Service part of the name during the mapping. This is an obvious thing from the example, but I'm not sure how far the example matches your actual code.

What I often see when streams are used is that suddenly the split up into methods is forsaken. For instance, in my code I would first build a list of services and then create a map out of it. I don't think that an intermediate list would do much w.r.t. performance here (the number of services will be limited, loading the classes will take much more time, and the streaming will have intermediate representations as well), and the code would clearly be simplified. Method chaining can be nice, but please don't overdo it.

Similarly, a method that tests if a class implements an interface can be clearly split out:

Stream.of(serviceClass.getGenericInterfaces())
    .filter(ParameterizedType.class::isInstance)
    .map(ParameterizedType.class::cast)
    .filter(type -> type.getRawType().equals(NodeService.class))

And actually, if you do that and look for code you will find NodeService.class.isAssignableFrom(clazz). The part is well programmed but please do use library functions when they are available.

All of above may not do much with regards to performance, but taking it into account should definitely help with the readability. Currently you had to describe what the code does in the question description. That should not be necessary for well programmed / documented code.


Let's set up code to benchmark different approaches. Every word counter will implement this interface:

interface IWordCounter
{
    IDictionary<string, int> CountWords(string path);
}

And here's our benchmark runner:

var wordCounters = new IWordCounter[]
{
    // ...
};

foreach (var wordCounter in wordCounters)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();

    var sw = Stopwatch.StartNew();
    var wordCount = wordCounter.CountWords(path);
    sw.Stop();

    Console.WriteLine("{0}, {1} entries, {2}", wordCounter.GetType().Name, wordCount.Count, sw.Elapsed);
}

Timings were taken with a release build, on the test file provided, no debugger attached, on .NET 4.5.2.

Here's the original code:

class OriginalWordCounter : IWordCounter
{
    private static readonly char[] separators = { ' ' };

    public IDictionary<string, int> CountWords(string path)
    {
        var wordCount = new Dictionary<string, int>();

        using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
        using (var streamReader = new StreamReader(fileStream))
        {
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                var words = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                foreach (var word in words)
                {
                    if (wordCount.ContainsKey(word))
                    {
                        wordCount[word] = wordCount[word] + 1;
                    }
                    else
                    {
                        wordCount.Add(word, 1);
                    }
                }
            }
        }

        return wordCount;
    }
}

On my machine, this takes about 8.2s.

We see an improvement using Heslacher's suggestion to use TryGet:

class OriginalTryGetWordCounter : IWordCounter
{
    private static readonly char[] separators = { ' ' };

    public IDictionary<string, int> CountWords(string path)
    {
        var wordCount = new Dictionary<string, int>();

        foreach (var line in File.ReadLines(path, Encoding.UTF8))
        {
            var words = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            foreach (var word in words)
            {
                int count;
                wordCount.TryGetValue(word, out count);
                wordCount[word] = count + 1;
            }
        }

        return wordCount;
    }
}

This takes about 6.7s. (The use of File.ReadLines here doesn't seem to effect the timing, it's just a bit cleaner.)

We get another improvement with Parallel.ForEach together with a ConcurrentDictionary:

class ParallelWordCounter : IWordCounter
{
    public IDictionary<string, int> CountWords(string path)
    {
        var result = new ConcurrentDictionary<string, int>();
        Parallel.ForEach(File.ReadLines(path, Encoding.UTF8), line =>
        {
            var words = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var word in words)
            {
                result.AddOrUpdate(word, 1, (_, x) => x + 1);
            }
        });

        return result;
    }
}

This takes about 5.2s.

You might want to try some of the Parallel.Foreach overloads to see if you can get any further improvements, and remember to take these results with a grain of salt.


Generic queries and handlers without reflection

One objection I could raise is that your generic type constraint doesn't guarantee what you think it might guarantee. Eg. you could have:

// TSelf is actually not T of Self
public class HelloQuery : IQuery<GoodbyeQuery, string>
{
}

// This one is fine
public class GoodbyeQuery: IQuery<GoodbyeQuery, string>
{
}

In other words, TSelf doesn't actually have to be the T of the class itself. This is not horrible, especially since you seem to only be using the interface as metadata, but it can still lead to confusing results during dependency injection if you've accidentally screwed up a class definition.

However, as long as you're not a masochist and don't declare nonsensical types like this, there is nothing wrong with this. This is an established design pattern known as the curiously recurring template pattern.


I do not know python, so I should probably restrain from answering. But my initial observation by looking at your code is the repeated call to listToRange in the last for loop.

We can also skip the if len() > 1.

Rewrite:

for key, value in chromDict.iteritems():
    chrom_range = listToRange(value)
    chrom_len = len(chrom_range)
    for i in range(0, chrom_len):
        print(key, chrom_range[i][0], chrom_range[i][1], sep="\t")

Some other notes:

There is also the question about variable names. In your
listToRange(list), list is a python keyword.
import __future__  statements should be served before
anything else.
Comments and code should be within a width limit. I stay with the 80
rule.
Space after comma.

As you tag question with beginner I would also recommend PEP 8 – Style Guide for Python Code. It is one of those things that when one accumulate experience one better see where and when it is appropriate to deviate from. Start out strict and lax later if appropriate.

There is also a pep8 command line tool for easy validation.

As such I can add the bullet point:

Function names should be lowercase, with words separated
by underscores as necessary to improve readability.

That is: if this is not part of a bigger code-base where the norm is to use camel-case.

For file read with can be nice to use. I simply quote python.org by:

  It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

As noted, I do not know python, but add a simple writeup anyway, you might find some of it useful:

""" GENO TO BED """
# BED file format
# http://genome.ucsc.edu/FAQ/FAQformat.html#format1
# 1.chrom      - The name of the chromosome (e.g. chr3, chrY, chr2_random) or
#                scaffold (e.g. scaffold10671).
# 2.chromStart - The starting position of the feature in the chromosome or
#                scaffold. The first base in a chromosome is numbered 0.
# 3.chromEnd   - The ending position of the feature in the chromosome or
#                scaffold. The chromEnd base is not included in the display of
#                the feature. For example:
#    The first 100 bases of a chromosome are defined as
#    chromStart=0, chromEnd=100, and span the bases numbered 0-99.

from __future__ import print_function
from collections import defaultdict
from operator import itemgetter
from itertools import groupby
import sys

def list_to_range(list_):
    """ List to range """
    ranges = []
    for k, groups in groupby(enumerate(list_), lambda (i, x): i - x):
        group = map(itemgetter(1), groups)
        ranges.append((group[0], group[-1]))
    return ranges

def dump_bed(chrom_dict):
    """ Print BED to stdout """
    for key, value in chrom_dict.iteritems():
        chrom_range = list_to_range(value)
        chrom_len = len(chrom_range)
        for i in range(0, chrom_len):
            print(key, chrom_range[i][0], chrom_range[i][6], sep="\t")

def dict_from_file(filename):
    """ Generate dictionary from file """
    chrom_dict = defaultdict(list)
    with open(filename, "rU") as handle:
        next(handle) # Skip first line
        for line in handle:
            if line == "\n":
                continue
            try:
                key, val = line.split()[0:2]
                chrom_dict[key].append(int(val))
            except ValueError:
                # Here you likely want to print some error.
                # Use except ValueError, err: to get the
                # error description.
                pass

    return chrom_dict

def main():
    """ Main routine """
    chrom_dict = dict_from_file(sys.argv[1])
    dump_bed(chrom_dict)
    return 0

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("Missing filename.", file=sys.stderr)
        sys.exit(1)
    sys.exit(main())


Copy-and-Move Concept Using Smart Pointer

unique_ptr is fine here. It's used where you would have used a plain pointer before.

But don't use naked new — use make_unique.  Oh, and I think a unique_ptr of array types was not in C++11 but needs C++14.

Don’t use (void) for () in parameter lists!  That was never proper, even in c++98. (it was supported to allow compatibility with C headers, but in Bjarne’s own words it’s “an abomination”.

Don’t write an empty destructor.  Use =default to emphasize that it exists, or just leave it off completely.

Why have a private _swap static function instead of a non-member overload of swap that anyone can use?

Another important new feature you have not embraced yet is the range for loop.  Use that instead of the lagacy for loops you have that go over the whole array.


Showing information about states on a map when clicked

You could have a single if statement covering all your non-default cases, since all your $('info#children')... sequences are the same, except for the state clicked.

So, you could just say

$('#info-children').children(':not(#info-' + code + ')').hide('slow');

and

$('#info-children').children('#info-' + code + ')').show('slow');

So, you could just have one huge logical statement, checking if the code/state is tx, il, fl, ga, or pa. If that statement is true, run the above code; if not, run the default code.


Dependency injection with Factory pattern sample code

public class SerializersFactory
{
    readonly ISerializer _iserializer;

    public SerializersFactory(ISerializer iserializer)
    {
        _iserializer = iserializer;
    }

    public string Serialize<T>() => _iserializer.SerializeToString<T>();

    public object Deserialize<T>() => _iserializer.DeserializeFromString<T>();
}

Sorry to burst your bubble, but... this isn't a factory. In fact, it's rather confusing what purpose it serves, given how that serializer is implemented:

    public nSerializerJson(string inputString, object inputObject)
    {
        if (inputString == null)
            throw new ArgumentNullException(nameof(inputString));

        if (inputObject == null)
            throw new ArgumentNullException(nameof(inputObject));

        InputObject = inputObject;
        InputString = inputString;
    }

It's very confusing why you need to specify both the serialized JSON string and the deserialized object for the constructor to not throw an ArgumentNullException. Actually, it's very hard to understand why one would even need this constructor.

It's the methods that need the parameters; having them at instance-level seems to make the whole thing more or less useless - and confusing.

What's the role of the <T> type parameter here?

public string SerializeToString<T>()
{
    return JsonConvert.SerializeObject(InputObject);
}

Oh, I see:

string SerializeToString<T>(); // Need <T> because of the Xml serializer.

Since when do implementations dictate what abstractions look like? That T is clearly begging for a method parameter there, of type T.

Seems you need to stop and ask yourself what you're trying to accomplish, and why. Your system has a dependency on Newtonsoft.Json; your serializer is essentially wrapping the Newtonsoft API... in some awkward way.

I would have used something like this:

public interface ISerializer
{
    string Serialize<T>(T deserialized);
    T Deserialize<T>(string serialized); // <out T>
}

And the implementation would be something like this:

public class JsonSerializer : ISerializer
{
    public string Serialize<T>(T deserialized)
    {
        return JsonConvert.SerializeObject(deserialized);
    }

    public T Deserialize<T>(string serialized)
    {
        return JsonConvert.DeserializeObject<T>(serialized);
    }
}

What else would you need? I think everything else you got here, is over-engineered fluff that can be removed. There's nothing to DI here, ISerializer is the dependency.

As for the factory, there's no need for one, since any type that needs an ISerializer can just tell the IoC container it needs one, by specifying an ISerializer parameter in its constructor.


Lowest common ancestor in recursive tree traversal

You seem to be have a few misconceptions, as @rolfl points out.

First, the data structure you have described and illustrated does not fit the definition of a tree.  Rather, I would characterize your data structure as a graph of maximum in-degree 2.

Second, you seem to be under the impression that the TreeSet internally contains a tree that resembles part of your original graph.  Actually, a TreeSet is nothing more than a SortedSet; the fact that the SortedSet is implemented by using a tree internally is irrelevant to you.  nodeList1.descendingIterator() does not produce an iterator that walks from root to leaf.  Rather, it yields nodes reverse-sorted according to the value contained in the node.

As a result, the code does not work.


you should use auto properties where you don't need any validation. So all of your properties should use them like instead of

private bool isChecked;
public bool IsChecked
{
    get { return isChecked; }
    set { isChecked = value; }
}

you would use

public bool IsChecked { get; set; }

this example of really unnecessary tenary expression

IsChecked = IsChecked ? false : true;

should be replaced by

IsChecked = !IsChecked;

using braces {} for single if statement also would make your code less errorprone
you should extract your magic numbers into some meaningful aka good named constants ( 3.0f , 1.5f etc)
you should extract "\u2713" to some meaningful constant
you should extract new SolidBrush(tickColor) to a field, as the brush itself won't change.


Finding the last successful route by ID using Python

If I understand the problem correctly, the goal is still to parse all the available pages - you can initiate an endless loop and break it once the status code is not 200. And, we may reuse the same web-scraping session to improve on performance:

URL_TEMPLATE = 'http://cornpalace.com/gallery.aspx?PID={page}'

with requests.Session() as session:
    page = 1
    while True:
        response = session.get(URL_TEMPLATE.format(page=page), allow_redirects=False)
        if response.status_code != 200:
            break

         print("Processing page #{page}".format(page=page))

         soup = BeautifulSoup(response.text, "lxml")
         # parse the page

         page += 1


Extend jQuery with enable/disable function

Overall it looks quite nice.
Just a few points:

The parameter name is asking a question about the element, not making a statement of what to do. I would rename it to disable which enables the caller to better signify their intent.
In the same vein, I would also rename the function to ariaDisable as it performs an action as opposed to asking a question

Edit
Per m90's comment the loop is per jQuery plugin conventions as noted here


Handling GetTickCount() overflow in timeouts

Unsigned subtraction (and automatic mod 2^32) will always give currentMs - beginMs == elapsedMs, even when beginMs > currentMs, and as long as the actual elapsed time doesn't overflow the tick count (it isn't greater than 49 days).

So you could replace the original with the following code:

DWORD beginMs = GetTickCount();

// Create Process, omitted for brevity

while ((waitResult = WaitForSingleObject(pi.hProcess, DEFAULT_WAIT_MS)) == WAIT_TIMEOUT) {
    if (timeoutMs != INFINITE) {
        DWORD currentMs = GetTickCount();
        bool timeoutReached = currentMs - beginMs > timeoutMs;
        if (timeoutReached) {
            TerminateProcess(pi.hProcess, 0);
            break;
        }
    }
}

And you could even go a step further and eliminate the variables currentMs and timeoutReached: if (GetTickCount() - beginMs > timeoutMs) {...


This is shorter, but not necessarily more efficient,

my $examine = shift; my $detect = 0;
for my $ProteinDB (@DB) {
    next if $ProteinDB->{'ID'} !~ /$examine/;
    $detect = 1;
    print "$_ $ProteinDB->{$_}\n\n"
      for grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB;
    print "SQ  $ProteinDB->{SQ}\n//\n";
}
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";

and if you push it little more,

my $examine = shift; my $detect = 0;
print map {
    $detect = 1;
    my $ProteinDB = $_;
    (
      (map "$_ $ProteinDB->{$_}\n\n", grep $_ ne "ID" && $_ ne "SQ", keys %$ProteinDB),
      "SQ  $ProteinDB->{SQ}\n//\n"
    );
  }
  grep $_->{ID} =~ /$examine/, @DB;
$detect or print "Error : For the ID $examine NO-Entry could be Found !\n";


Checking whether a graph is bipartite using BFS

Stop using std::list, which is a doubly linked list and does not support fast random access. You should use std::vector instead, supporting O(1) random access.

Instead of

list<int> *adj;

You can have a vector of vectors, which will be not only faster, but also memory-leak free.


Your variables listChaletss, listChaletp, and allPeriodes appear to be instance variables.  We can't tell whether you're leaking memory without further context — what is the expected lifetime of this object?  If this object only has a brief existence, then you probably don't have to worry about how it uses memory.  On the other hand, if it's a long-lived object, you have to be careful.

There is cause for concern, though.  You store the result of .getAllChalet() in instance variable listChaletss.  Why an instance variable?  Is listChaletss acting as some kind of cache?  If so, then the code would likely be:

public void post() {
    if (null == listChaletss) {
        listChaletss = chaletService.getAllChalet();
    }
    ...
}

… or better yet:

private Chalet[] getChalets() {
    if (null == listChaletss) {
        listChaletss = chaletService.getAllChalet();
    }
    return listChaletss;
}

public void post() {
    for (Chalet it : getChalets()) {
        ...
}

… or better yet, use a WeakReference.

On the other hand, if listChaletss is not meant to be a cache, then you should just make it a local variable so that you don't hang on to the result.  Unintentionally keeping a reference to the result leads to a "lingering" memory leak: you waste memory storing listChaletss, but you recover that memory the next time you call .post(), only to waste it again.

Similar considerations apply to your other two instance variables.


For every edge in your graph, you are doing a BFS of the tree on one side of the edge to sum all of its vertex weights. It is not hard to see that you are doing a lot of work over an over again. Imagine that every vertex in your tree was connected to only 2 other vertices, so that it basically looked like a doubly linked list. If we store the list in an array, your code would be doing something akin to:

def min_diff_cut(list_):
    total = sum(list_)
    best_diff = total
    for idx in range(1, len(list_)):
        best_diff = min(best_diff, total - sum(list[:idx]))
    return best_diff

This of course has \$O(n^2)\$ complexity, which is rarely a good thing. A much more efficient implementation running in \$O(n)\$ time would do something like:

def min_diff_cut(list_):
    total = sum(list_)
    best_diff = total
    subtotal = 0
    for value in list_:
        subtotal += value
        best_diff = min(best_diff, total - subtotal)
    return best_diff

How can you expand this idea to work on your possibly branched tree? Well, if instead of breadth first, you go depth first, you can recursively find out what the best diff and sum of weights down an edge is, and come up with a solution from there. This would look something like:

def min_diff_cut(graph, weights):
    total = sum(weights)
    visited = set()

    def subtree_total_weight(vertex):
        visited.add(vertex)
        subdiff = total
        subtotal = weights[vertex]
        for next_vtx in graph[vertex]:
            if next_vtx in visited:
                continue
            subt, subd = subtree_total_weight(next_vtx)
            subtotal += subt
            subdiff = min(subdiff, subd)
        return subtotal, min(subdiff, abs(2*subtotal - total))

    # We are assuming vertices are 0-based indices
    _, best_diff = subtree_total_weight(0)

    return best_diff

if __name__ == '__main__':
    print min_diff_cut({0: [1], 1: [0, 2, 4], 2: [1], 3: [4],
                        4: [1, 3, 5], 5: [4]},
                       [100, 200, 100, 500, 100, 600])


Displaying a wait cursor while we're waiting

Your intuition was correct, you're not doing asynchronicity the right way.

Take a look at this bit of code:

var getItems = new Task<IOrderedEnumerable<ToDoItem>>(() => GetItems());
getItems.Start();
Control.TodoItems = getItems.Result;

You're creating a new task, starting it and then you synchronously block the current thread by calling .Result. A new thread isn't created just by creating a Task object, that's what async/await is for.

Instead, change your method as such (omitting cursor and try/catch for clarity):

private async void RefreshToDoList(object sender, EventArgs e)
{
    Control.TodoItems = await Task.Factory.StartNew(() => GetItems());
}

private IOrderedEnumerable<ToDoItem> GetItems()
{
    // Everything else is the same here
}

This incorporates a few changes. First of all: I've made the event handler async void. This is the only situation where it is advised to do this, simply because there's no alternative: event handlers have the requirement to have a void return type whereas asynchronous methods work with Task.

In essence this means that you won't be able to await the event handler so if the caller finishes while the event's effects are still running, your program will exit without a regard of this still running code.

Another change is that I used Task.Factory.StartNew(delegate);. You can choose between this and Task.Run(delegate) but both are more fluent than creating a new Task object and then starting it.

You should always avoid calling .Result since it synchronously blocks the thread to wait for the result (which is the opposite of what you typically want in an asynchronous environment).

As shown in the docs:

  Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

The only reason I'm creating a new task from the caller is because GetItems() doesn't return one. Typically you want asynchronicity throughout the entire hierarchy but I didn't see where it would've been used in GetItems().
However, if you ever call an asynchronous method then it returns Task or Task<T> and you can simply use await MyMethodAsync().


Step 1: format it nicely

An IDE can automatically reformat code nicely to follow the standard:

int n = arr.length;

for (int k = 0; k < n - 1; k++) {
    for (int i = 0; i < n - k - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            int temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
    }
}

In Eclipse it's Control-Shift-f. It adds spaces around operators. Now the code looks like the standard, and it's easier to read and code review for everyone.

Step 2: extract to a method

In the current code you have a hardcoded array, and the main logic follows right after. It's hard to test this way. What if you want to see if the implementation works with a different set of numbers? You have to rewrite the array. Better to extract the main logic into its own, independent method:

void sort(int[] arr) {
    // ...
}

Now you can test with multiple different inputs easier:

arr = new int[]{2, 5, 1, 8, 12, 3, 7};
BubbleSort.sort(arr);
System.out.println(Arrays.toString(arr));

arr = new int[]{4, 3, 2, 1, 2};
BubbleSort.sort(arr);
System.out.println(Arrays.toString(arr));

Step 3: convert print statements to proper unit tests

The problem with print statements is that every time you change something and rerun, you have to re-verify the output of each statement. Unit tests can automate the verification step, and converting is easy enough to do:

@Test
public void testMixedValues() {
    int[] arr = {2, 5, 1, 8, 12, 3, 7};
    BubbleSort.sort(arr);
    assertEquals("[1, 2, 3, 5, 7, 8, 12]", Arrays.toString(arr));
}

@Test
public void testDecreasingValues() {
    int[] arr = {4, 3, 2, 1};
    BubbleSort.sort(arr);
    assertEquals("[1, 2, 3, 4]", Arrays.toString(arr));
}

@Test
public void testDecreasingWithDups() {
    int[] arr = {4, 3, 2, 1, 2, 3, 2};
    BubbleSort.sort(arr);
    assertEquals("[1, 2, 2, 2, 3, 3, 4]", Arrays.toString(arr));
}

Now you can make changes and the test cases will flag an error if something breaks. Unless you do something really horrible, typically only a few of the test cases will break, and you don't need to reverify the others that are still working, which makes debugging a lot easier.

Minor things

Instead of n, a better name would be length to cache the length of the array.

As for the loop variables, it's more traditional to name nested counter variables as i, j, k, in this order of nesting level, instead of k, i as you did. In any case, this is really not a big deal.

int length = arr.length;

for (int i = 0; i < length - 1; i++) {
    for (int j = 0; j < length - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
            int temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
        }
    }
}


Get all points on a uniform discrete grid inside a circle's radius

The code:

private static IEnumerable<Vector2> GetPointsInCircle(Vector2 circleCenter, float radius,
    Vector2 gridCenter, Vector2 gridStep)
{
    if (radius <= 0)
    {
        throw new ArgumentOutOfRangeException("radius", "Argument must be positive.");
    }
    if (gridStep.x <= 0 || gridStep.y <= 0)
    {
        throw new ArgumentOutOfRangeException("gridStep", "Argument must contain positive components only.");
    }

    // Loop bounds for X dimension:
    int i1 = (int)Math.Ceiling((circleCenter.x - gridCenter.x - radius) / gridStep.x);
    int i2 = (int)Math.Floor((circleCenter.x - gridCenter.x + radius) / gridStep.x);

    // Constant square of the radius:
    float radius2 = radius * radius;

    for (int i = i1; i <= i2; i++)
    {
        // X-coordinate for the points of the i-th circle segment:
        float x = gridCenter.x + i * gridStep.x;

        // Local radius of the circle segment (half-length of chord) calulated in 3 steps.
        // Step 1. Offset of the (x, *) from the (circleCenter.x, *):
        float localRadius = circleCenter.x - x;
        // Step 2. Square of it:
        localRadius *= localRadius;
        // Step 3. Local radius of the circle segment:
        localRadius = (float)Math.Sqrt(radius2 - localRadius);

        // Loop bounds for Y dimension:
        int j1 = (int)Math.Ceiling((circleCenter.y - gridCenter.y - localRadius) / gridStep.y);
        int j2 = (int)Math.Floor((circleCenter.y - gridCenter.y + localRadius) / gridStep.y);

        for (int j = j1; j <= j2; j++)
        {
            yield return new Vector2(x, gridCenter.y + j * gridStep.y);
        }
    }
}

Comments:

If step values in the gridStep aren't supposed to be close to each other, this method could be rewritten to select a dimension with the largest step's value for the outer loop.
I've used integer loop variables to avoid accumulation of errors.
This code has been successfully tested in comparison with the brute force method.
This method is ~20% faster on my machine. Efficiency of the method depends on the number of grid points inside a circle. More points - more efficiency.


Normally when parsing a String into an int, people expect it to be a static method

Having to create a class to do the computation is a bit bulky, and then you need to worry about synchronization (what happens if this class is shared across multiple threads?)

boolean isOverflow(int prev, int curr) {
    // prev = value at last iteration
    // curr = value after current iteration
    if (curr/10 == prev) {
        return false;
    }
    return true;
}

This method is already a great candidate to become static, it only relies on its two inputs to figure out if an overflow happened

boolean isNegative = false;
int i = 0; // string iterator position

void checkSign(String str) //uses i and isNegative

int signSolution(int solution) //uses isNegative

These are slightly more tricky, int signSolution(int solution) can just take another parameter: static int signSolution(int solution, boolean isNegative)

void checkSign(String str) would need to be included as part of the myAtoI method or be rewritten a bit

If we treat + as whitespace, then it would only need to worry about handling -

static boolean checkSign(String str, int i)
{
    return str.charAt(i) == '-';
}

And calls to checkSign(str); would instead be if(checkSign(str)) i++;

Be consistent.  You're mixing for and while loops of similar structure

while (i < str.length() && str.charAt(i) == ' ')
    i++;
[...]
for (; i < str.length(); i++) {
    [...]
}

They can either both be for loops, or both be while loops, but mixing is unexpected

for(; i < str.length() && str.charAt(i) == ' '; i++);
[...]
for(; i < str.length(); i++)
{
    [...]
}

vs

while(i < str.length() && str.charAt(i) == ' ')
    i++;
[...]
while(i < str.length())
{
    [...]
    i++;
}

Checking "whitespace" currently only checks spaces

Instead of using str.charAt(i) == ' ', you can offload complicated functionality to another method (and be easier to change later)

static boolean isWhiteSpace(char c)
{
    return c == ' ';
}

Then if you'd like to include all whitespace (and + and mentioned above)

static boolean isWhiteSpace(char c)
{
    return Character.isWhitespace(c) || (c == '+');
}

Instances of if(bool) return true; else return false; are the same as just return bool;

if (curr/10 == prev) {
        return false;
}
return true;

Can be simplified to just

return curr / 10 != prev;

OptionalA:

Another way to check for overflow is to store the output as a long, and check if it overflows

public static int myAtoI(String str)
{
    long solution = 0;
    [...]
}

private static isOverflow(long num)
{
    return num == (int)num;
}

OptionalB:

Instead of adding the values and then flipping the result, you could subtract values if it's a negative number


LeetCode Count number of set bits solution

(Because of the way Code Review works, only your code can be reviewed.  Therefore, I will not say anything on the code written by "one gentleman".)

The first thing I see is: use consistent indentation and add spaces.  Your code becomes much more readable if you format it like this:

int hammingWeight(uint32_t n) {
    int count = 0;
    while (n > 0) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

Also, it is probably a good idea to use std::uint32_t instead of uint32_t in C++.

You can make this function constexpr and noexcept.  Simple computations like this can be done at compile time, and benefit from inlining.

This function can also be generalized to take any unsigned integer type.  A template version may look like:

template <typename T, std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T>>>
constexpr int hammingWeight(T n) noexcept
{
    // the implementation is the same
}

The implementation is good enough and very readable IMO.  You don't have to get very creative unless measuring reveals the necessity of optimization.

In C++20, we have a standard function for this — std::popcount, in header <bit>.


Bash script for tagging the current git workspace including uncommitted changes

With the input of @EtanReisner, I found a possible way to the solution:

That's our current situation:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   c
    new file:   e

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    c
    modified:   e

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    d

I try now to stash all this:

$ git stash --all

Now we can get the hash of it:

$ git rev-parse refs/stash
9a208ed215032b4e47cb1493fc5f16a4a5ea78c1

Or tag it directly (this works)

$ git tag tagged-workspace-01 refs/stash

Now I unstage everything

$ git stash pop --index

This worked quite well:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   c
    new file:   e

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   e

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    d

As you can see, under some (very unusual) conditions it happens that the revert is not 100% perfect (the not-staged removal of the file c which is also in the index as a new file), but so far it's the best solution I've found.


Originally I thought you must have been doing something wrong, but no: the scipy.stats implementation of mode scales with the number of unique elements, and so will behave very badly for your test case.

As long as your objects are hashable (which includes your three listed object types of strings, floats, and ints), then probably the simplest approach is to use collections.Counter and the most_common method:

In [33]: import scipy.stats

In [34]: li = range(50000); li[1] = 0

In [35]: scipy.stats.mode(li)
Out[35]: (array([ 0.]), array([ 2.]))

In [36]: timeit scipy.stats.mode(li)
1 loops, best of 3: 10.7 s per loop

but

In [37]: from collections import Counter

In [38]: Counter(li).most_common(1)
Out[38]: [(0, 2)]

In [39]: timeit Counter(li).most_common(1)
10 loops, best of 3: 34.1 ms per loop


I am writing (my first) jQuery plugin.

Congratulations!

  The user can provide a JSON object to configure the plugin when they initialise it.

Terminology is wrong here. JSON is the transport format that looks like a JS object, but serialized into a string. What you use is just a JS object. They look the same because JSON was modeled after the JS literal notation, which (historically) was easily "unserialized" (turned back into an object) with eval. Proper parsers came in later on.

//check to see if options are provided and extend if required.
$.fn.hide_and_peek.custom = function(){
    if(typeof options === "undefined"){
        return $.fn.hide_and_peek.custom;
    }else{
        return $.fn.extend($.fn.hide_and_peek.custom,options);
    }
}();

//merge defaults and custom options
var oOptions = $.fn.extend({}, $.fn.hide_and_peek.defaults, $.fn.hide_and_peek.custom);

So I assume custom is another level of options, maybe set during setup and globally for all instances of the plugin. You don't need to check if it's undefined. You can just merge it in. jQuery will take care of it being undefined and will just skip over it.

// Last will take precedence
var oOptions = $.fn.extend({}, defaults, custom, options);


Determine the ratio of the contents of a pot to the (metal) volume of of the pot

You could get rid of many temporary variables, by returning the result right away:

import math
pi = math.pi
class Pot:
    """create a pot with contents, determine the ratio between the contents and the pot"""

    def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.wall_width = wall_width
        self.inner_radius = inner_radius
        self.outer_radius = self.inner_radius + self.wall_width
        self.base_thickness = base_thickness
        self.height = height
        self.content_height = content_height

    def get_cylinder_volume(self,radius,height):
        return pi * (radius ** 2) * height

    def get_pot_wall(self):
        inner_cylinder = self.get_cylinder_volume(self.inner_radius,self.height)
        outer_cylinder = self.get_cylinder_volume(self.outer_radius,self.height)
        return outer_cylinder - inner_cylinder

    def get_pot_base(self):
        return self.get_cylinder_volume(self.inner_radius,self.base_thickness)

    def get_pot_volume(self):
        return self.get_pot_base() + self.get_pot_wall()

    def get_content(self):
        return self.get_cylinder_volume(self.inner_radius,self.content_height)

    def get_ratio(self):
        return self.get_content()/self.get_pot_volume()

    def check_ratio(self,desired):
        if (self.get_ratio() < desired):
            print ("too small")
        else:
            print (self.get_ratio())

Also, many of your variables are already determined when you initialize the class. Unless you want to change the shape of the pot on the fly (for this I would create a new instance of Pot with the new dimensions), the only thing I would expect to change is the amount of content in the pot. So, pot_wall, pot_base, pot_volume can all be calculated in init and set to variables of the instance:

def __init__(self,inner_radius,wall_width,base_thickness,height,content_height):
        self.inner_radius = inner_radius
        self.content_height = content_height
        outer_radius = inner_radius + wall_width

        self.pot_volume = self.get_cylinder_volume(inner_radius,base_thickness) + self.get_cylinder_volume(outer_radius,height) - self.get_cylinder_volume(inner_radius,height)

...

def get_ratio(self):
    return self.get_content()/self.pot_volume

This would allow you to get rid of get_pot_wall, get_pot_base, get_pot_volume. Or at least the first two, if this is too much inline calculation for you.


Should I add the "fetch_group" method to my user class or should I create a separate class for group

Logical inconsistencies

You create a User object expecting a user_id to be passed to setup the object, id object to this design but im sure you've got it covered, but then later on you ask for a user_id to run a query?

I would leave it in the constructor and use type hiniting (php 7.0 +) to make sure it passed on creation

public function __construct(int $userId) {
    $this->userId = $userId;
    $this->get_user_by_id();
}

But the type hint should make sure an exception is thrown if it isn't provided correctly!

PSR2

The PSR2 is a great coding style guide for php it says you should use camelCase for variable names & function names you should look into it.

Returning early

You should return early where you can this makes your code easier to read and less indentation levels

private function get_user_by_id($id)
{
    if ($id) {
        return false;
    }

    $data   = $this->db->row("SELECT user_id, realm, user_name, display_name, created, last_seen, deleted, ignored, blacklisted, whitelisted, blocked, filtered FROM users WHERE user_id = :id", array('id' => $id));

    if ( !$data ) {
        return false;
    }

    $this->data($data);

    return $this;
}

Adding more functions to setup a user

I would create a Service class for your user as your current class is doing both Model work (connecting to the database) and being a "Object".

<?php

namespace SomeNamespace\Services;

use SomeNamespace\Models\Users\GetUserDetails;
use SomeNamespace\Models\Users\GetUserGroupDetails;

class User
{
    // Properties list

    public function __construct(
        GetUserDetails $getUserDetails,
        GetUserGroupDetails $getUserGroupDetails
    ) {
        $this->getUserDetails = $getUserDetails;
        $this->getUserGroupDetails = $getUserGroupDetails;
    }

    public function populateData(int $userId)
    {
        $userDetails = $this->getUserDetails->get($userId);

        if(empty($userDetails)){
            throw new \Exception("Missing user for id $userId", 1);
        }

        $groupDetails = $this->getUserGroupDetails->get($userId);

        $this->setupUserDetails($userDetails);
        $this->setupUserGroupDetails($groupDetails);

        return $this;
    }

    private function setupUserDetails($userDetails)
    {
        $this->someUserDetails = $userDetails["something"];
    }

    private function setupUserGroupDetails($groupDetails)
    {
        $this->someGroupDetail = $groupDetails["something"];
    }
}

// GetUserDetails.php

namespace SomeNamespace\Models\Users;

class GetUserDetails
{
    public function __construct()
    {
        $this->db = some::db::factory();
    }

    // Lots of sql queries
}

// GetGroupDetails.php

namespace SomeNamespace\Models\Users\Groups;

class GetUserGroupDetails
{
    public function __construct()
    {
        $this->db = some::db::factory();
    }

    // Lots of sql queries
}

I may be wrong as you seem to be using factories to construct objects instead of dependency injection, but im sure you see where im going with it!


Minimize the number of workers/test rigs, with a capacity constraint, using Excel VBA Solver loop

Let's talk about simple things that can be fixed by tools and then let's talk about performance:

I ran your code through Rubberduck's Online Analyzer [1] and got a lot of results. Most of them were related to the missing definitons for SolverAdd, SolverReset, SolverSolve and SolverOk but there were some more results:

You're not using Option Explicit. This means you could mistype variable (and function/sub) names and only realize at runtime. This is especially dangerous with variables, since VBA just "on-the-fly" declares that mistyped variable as a Variant.
You're using implicit references to ActiveSheet and ActiveWorkbook in your calls to Range and Sheets
Sheets may contain elements you don't expect. Generally it's more correct to use WorkSheets instead
Optimization is "implicitly public". While this is probably exactly what you need, it's usually a better idea to be upfront about this and explicitly declare it as public.

Additionally the code inside the Sub is not indented by one level, which makes it hard to distinguish the Sub from surrounding procedures. Furthermore Rubberduck should've flagged the use of Call, which is obsolete.

Since we've cleared about everything that can be easily addressed by more or less intelligent tools, let's get into the meat of the code and start optimizing:

First things first, we stop working with ActiveSheet and Select, because they are slow and can result in really funny undesired behaviour:

Dim optimizationSheet As Worksheet
'still references ActiveWorkbook, but I don't know what your workbook is called :/
Set optimizationSheet = Worksheets("Optimization")

Then we can make the clearing of "working ranges" a bit cleaner and faster:

With optimizationSheet
    .Range("Worker_All[[1]:[15]]").Clear
    .Range("TestRig_All[[1]:[15]]").Clear
    .Range("Worker_787[[1]:[15]]").Clear
    .Range("TestRig_787[[1]:[15]]").Clear
End With

This is minimally faster, because VBA knows it can reuse the optimizationSheet reference. In addition to that it doesn't access the ActiveSheet anymore, which is really good.

The interesting part of optimization comes now. Unfortunately you did not provide the code for your Solver, which is most probably the actual bottleneck of this, but even so we can get some minor speed out of this by declaring the variables we use with their proper types.

The true improvement will lie within the fact that you're abusing the EXCEL-Sheet as a holder for your variables. Instead of doing that (which is degrading performance more than you might imagine) the Solver should be rewritten to perform it's task on Arrays instead of taking the Address of a Range on the sheet and then use the cells of the Worksheet.
A general rule is to avoid using the Worksheet whenever you can, because it's so mindbogglingly slow.

I strongly recommend that you post the code of the solver after refactoring it to not use the Worksheet as data storage for a proper review ;)

  [1] I'm involved in Rubberduck as Translator and occasional Dev


Find duplicates for mixed type values in dictionaries

Your code reads well, and has good documentation. It is pretty pleasant to read.

You could just simplify a bit faithfulrepr by using generator expression and removing the need for the deepcopy:

def faithfulrepr(ds):
    if isinstance(ds, collections.Mapping):
        res = collections.OrderedDict(
            (k, faithfulrepr(v)) for k, v in sorted(ds.items())
        )
    elif isinstance(ds, list):
        res = [faithfulrepr(v) for v in ds]
    else:
        res = ds
    return repr(res)

However this method will fail when fed dictionaries that have variable types as their keys (like {1: 'one', 'two': 2}).

An other take on the problem would involve more computations but can compare elements with the equality operator (which seems to be what you are really interested on). It involves maintaining two lists, one for the list of keys and one for the values, and searching in the list of values if the current one already exist. This is done using index which, unfortunately, is \$O(n)\$ but compares using __eq__:

def tupelize_dict(ds):
    keys, values = [], []
    for key, value in ds.items():
        try:
            index = values.index(value)
        except ValueError:
            values.append(value)
            keys.append([key])
        else:
            keys[index].append(key)
    return dict(zip(map(tuple, keys), values))
    # or the more readable return {tuple(k): v for k, v in zip(keys, values)}


Don't use a dictionary. You can just refer to the attrs of a class by their name. Something like:
import tkinter as tk
from tkinter import filedialog
from typing import Optional

class View:
    def __init__(self, parent: tk.Tk):
        self.parent = parent
        self.working_dir: Optional[str] = None
        self.dest_dir: Optional[str] = None

        self.menu('Working', 'working_dir')
        self.menu('Dest.', 'dest_dir')

    def menu(self, title: str, attr: str):
        def browse():
            setattr(self, attr, tk.filedialog.askdirectory())

        button = tk.Button(
            self.parent,
            text=f'Choose {title} Folder',
            command=browse,
        )
        button.pack()

if __name__ == '__main__':
    root = tk.Tk()
    View(root)
    root.mainloop()

Notes:

Do not add a () suffix to your class
Do not assign those buttons as members on your class
Centralize the creation of the buttons and the associated command
For the command handler, use a simple closure
To target a specific member variable, accept a parameter that's used with setattr
Use type hints


Pandas filter dataframe on multiple columns wrt corresponding column values from another dataframe

You need to merge dataframes like done here in Pandas Merge. You also need to read on dataframe joins which is a common topic in learning databases.Here I have not done any tweaking with indices i.e, whether to keep left ones or right ones but you can check the docs for better information on here Merge Docs Pydata
import pandas as pd

columns = "a b c d e f".split()
data = '''1 1 1 x 1 5
1 1 1 x 1 6
1 1 1 y 1 5
1 1 1 y 1 7'''.split("\n")

data = list(map(lambda x:x.split(), data ))

left = pd.DataFrame(columns = columns, data=data)

    a   b   c   d   e   f
0   1   1   1   x   1   5
1   1   1   1   x   1   6
2   1   1   1   y   1   5
3   1   1   1   y   1   7

right = pd.DataFrame(data = ["1 1 1 x 1 5".split()], columns=columns)

    a   b   c   d   e   f
0   1   1   1   x   1   5

pd.merge(left, right, how="right", on=["a", "b", "c", "d"])

    a   b   c   d   e_x f_x e_y f_y
0   1   1   1   x   1   5   1   5
1   1   1   1   x   1   6   1   5

pd.merge(left, right, how="right", on=["a", "b", "c", "d"], suffixes=["", "_"] ).drop(["e_", "f_"], axis=1)

    a   b   c   d   e   f
0   1   1   1   x   1   5
1   1   1   1   x   1   6


Proper way of handling exceptions while reading user input from file

I agree with @skiwi on the File input value. hardcoding the file name in this method is not helpful. I disagree with some of the Exception suggestions though...

IOExceptions are a special breed. If you cannot read the file, then you have to report it as an IOException. It irritates me that FileNotFoundException is an IOException though... so, I handle that one specially..... Otherwise, I tend to let IOExceptions 'escape' method calls. and the calling code should handle them... it's a bigger problem than the function.

Additionally, there is no reason to catch the broader Exception, and wrap it as a RuntimeException. There are no other thrown exceptions from the readLines method that are not RuntimeExceptions anyway....

Also, MalformedInputException is an IOException anyway... may as well handle them together.

Finally, your check to make sure the maze is square, does not. It should be checking the line-length to make sure it matches the expected size.... but it does not.

(Edit: Use StandardCharsets.UTF_8)

Here's how I would write your method:

/**
 * Reads the maze from plain text and converts it to char[][]
 * Marks the start (B) and end (F) coordinates if found, if not throws exception
 * Expects each line to have the same length as the the first line, throws exception if not
 *
 * @return maze as char[][]
 */
private char[][] readMazeFromFile(Path mazeFile) throws IOException {
    if (!Files.isRegularFile(mazeFile) || !Files.isReadable(mazeFile)) {
        throw new IllegalArgumentException("Cannot locate readable file " + mazeFile);
    }
    List<String> stringList = Files.readAllLines(mazeFile, StandardCharsets.UTF_8));

    char[][] charMaze = new char[stringList.size()][];
    for (String line : stringList) {
        if (line.length()  != charMaze.length) {
            throw new IllegalArgumentException("Expect the maze to be square, but line " + i + " is not " + charMaze.length + " characters long";
        }
        if (line.contains("B")) {
            startX = i;
            startY = line.indexOf("B");
        }
        if (line.contains("F")) {
            endX = i;
            endY = line.indexOf("F");
        }
        charMaze[i] = line.toCharArray();
    }
    if (startX == -1 || startY == -1)
        throw new IllegalArgumentException("Could not find starting point (B), aborting.");
    if (endX == -1 || endY == -1)
        throw new IllegalArgumentException("Could not find ending point (F), aborting.");
    return charMaze;
}


Shopify monitor that utilizes redis for caching each product

const axios = require('axios'),
      fs = require('fs'),
      redis = require('redis');

Personally, I discourage the use of a single var/let/const for declaring a variable. Firstly, they're not portable. Let's say you want to move fs somewhere else. Instead of copy-pasting the entire line, you end up copying that line and tacking on var/let/const anyways.

Next, say you already had redis. if you wanted to add axios, the Git changelog will look like:

- const redis = require('redis');
+ const axios = require('axios'),
+       redis = require('redis');

or this:

- const redis = require('redis');
+ const redis = require('redis'),
+       axios = require('axios');

Instead of just this:

+ const axios = require('axios');
  const redis = require('redis');

or this:

  const redis = require('redis');
+ const axios = require('axios');

You never touched redis, yet it's highlighted in the commit. This is because you had to add the ,. This ends up being unnecessary noise in the commit, and annoying in code reviews and pull requests.

Next up, I recommend a const-first policy. The priority should be const first, then let if the variable has to mutate (e.g. loop counters). Then var if you absolutely have to have a function-scoped variable defined in some nested block for whatever reason.

This block-scoped variables reduce cognitive overhead, avoiding having to remember that what variables exist in the upper scopes, and to avoid accidentally clobbering a variable elsewhere. Small change in process, but has big benefits down the line.

Node.js has native support for async/await. So you no longer have to deal with the clunky syntax of promises.

Additionally, if you have functions that use the Node-style callback API (an async function that takes a callback whose first argument is an error and the second being the result), Node has utils.promisify() which returns a promise-based version of it.

for (let i = 0; i < sites.length; i++) {
    getProducts(sites[i]).then(products => {
       products.forEach(product => {
           cache(product)
       });
    }).catch(err => console.log(err));
}

You can replace this with an array.map() and Promise.all(). Put the promises returned by getProducts() in an array, pass that array to Promise.all() which returns a promise, await that promise to listen for the completion.

setInterval(() => checkStock(), 5000);

I'd wait for checkStock() to complete first before launching the next run. You wouldn't want to hammer the site every 5 seconds. They might not respond in time, and your requests may accumulate. You might be rate-limited or worse, blocked, before you know it.

Here's how I'd write it:

const axios = require('axios')
const fs = require('fs')
const redis = require('redis')

const trackingF = fs.readFileSync("../tracking.json")
const proxiesF = fs.readFileSync("../proxies.json")

const client = redis.createClient()
const clientGetAsync = utils.promisify(client.get)

const toLower = x => x.toLowerCase()

const keywords = JSON.parse(trackingF).keywords.map(toLower)
const sites = JSON.parse(trackingF).sites.map(toLower)
const proxies = JSON.parse(proxiesF).proxies;

const rProxy = () => proxies[Math.floor(Math.random() * Math.floor(proxies.length))]

const getProducts = async url => {
  const response = await axios.get(`${url}/products.json`, rProxy())
  return response.data.products
}

const cache = async product => {
  try {
    const reply = await clientGetAsync(product.id)
    if (reply) return
    client.set(product.id, JSON.stringify(product))
    console.log("NEW PRODUCT: " + product.id)
  } catch (e) {
    console.error(e)
  }
}

const checkStock = async delay => {
  console.log("[MONITOR] CHECKING")

  const promises = sites.map(async site => {
    try {
      const products = await getProducts(site)
      await Promise.all(products.map(cache))
    } catch (e) {
      console.error(e)
    }
  })

  await Promise.all(promises)

  setTimeout(() => checkStock(delay), delay)
}

checkStock(5000).catch(e => console.error(e))


For single-quoted attributes, use htmlspecialchars($text, ENT_QUOTES).

Depending on what this does, you might want to implement some sort of protection against CSRF attacks.

You might also want to check $_SERVER['SCRIPT_NAME'].

Other than that, this code seems reasonable.


Symbolic Constants
This code could use some symbolic constants:
struct context {
    size_t freq[256];          /* char -> frequency */
    unsigned char sorted[256]; /* index -> char */
    unsigned char order[256];  /* char -> index */
} table[256];

void init()
{
    opt_k = 3;

    for (int p = 0; p < 256; ++p) {
        for (int i = 0; i < 256; ++i) {
            table[p].sorted[i] = i;
            table[p].freq[i] = 0;
            table[p].order[i] = i;
        }
    }
}

The use of symbolic constants would make this code easier to write and maintain. For example if there was a symbolic constant for 256 the size of the table and the loop controls could be changed with a single line edit.
Global Variables
In the function init() above, it is obvious that global variables are being used, table is on global variable and opt_k is another global variable.
Global variables are generally considered a bad programming practice, they make the code hard to write, debug and maintain. They also make it very easy to introduce bugs.
In the C programming language if the program consists of multiple files, it is possible that global variables can cause the program not to link if they are declared in multiple files.
Using assert() in C
If at some point the code is going to be compiled for release using the optimizing feature of the compiler, then the assert() statements will be optimized away. If the error checking provided by the asserts is required it will be better to replace the asserts with if statements.


Selecting users with biopsies in a given country for charting

Some notes on your code:

User.all.where -> User.where.
The moment you write group_by you are not using SQL anymore, performance will suffer.
The line starting with sum is very confusing, the indentation make you think it's the continuation of map but in fact it's part of its inner expression. Indentation should reflect the structure of an expression.
map + flatten -> flat_map.
|pair, something| and then pair[0]. You can de-structure arrays using the syntax |(k, v), something|.

On a first refactor, I'd write:

@nation_biopsy = User
  .where(country: @nation)
  .group_by { |u| [u.institute_type, u.biopsy] }
  .flat_map do |(institute_type, biopsy), users|
    ["name" => institute_type, "y" => User.where(id: users.map(&:id)).sum("biopsy")]
  end.to_json

On a second refactor, I'd try to make it work with SQL. Something like this:

@nation_biopsy = User
  .where(country: @nation)
  .group(:institute_type, :biopsy)
  .select(:institute_type, "SUM(biopsy) AS biopsy_count")
  .flat_map { |group| ["name" => group.institute_type, "y" => group.biopsy_count] }
  .to_json

Now, if you want to write something fancy use Arel, it allows you to write it without SQL fragments, which looks kind of cool:

users = User.arel_table
@nation_biopsy = User
  .where(users[:country].eq(@nation))
  .group(users[:institute_type], users[:biopsy])
  .select(users[:institute_type], users[:biopsy].sum.as("biopsy_count"))
  .flat_map { ["name" => group.institute_type, "y" => group.biopsy_count] }
  .to_json


Multiple serial URL requests in Objective-C / iOS

Create several instances of NSOperation
Set dependencies so that one runs after another.
Add to a private NSOperationQueue.
Cancel all operations in a queue if a match is found.


What improvements can I make to this table filtering jQuery Plugin?

You have:

this._defaults = defaults;

This is redundant as the declaration :

var pluginName = "filterTable",
    defaults = {
    };

Can be accessed anywhere in your plugin.
Declare all variables that you use. This is a really good practice to have change lines like:

 $el = $(this.element);
 $table = $('#' + $el.data('filtertable'));

to:

var $el = $(this.element);
var $table = $('#' + $el.data('filtertable'));

JavaScript will let you use them without but you'll run into issues otherwise.
Variables need meaningful names so their lives don't seem meaningless and they despair.

  Invective! Verb your expletive nouns!

$table.find('th').each(function (i)
{
    for (j in filterColumnNames)
    {
        if ($(this).text().trim() == filterColumnNames[j])
        {
             filterColumns.push(i + 1);
        }
    }
 });

What is i? index? columnIndex?
What is j? currentColumnName?


Python implementation of Back Propagation Algorithm without bias

First, I wouldn't rely on flatten from a module like setuptools. Its purpose isn't in line with the interface of the module, so it's likely an "implementation detail". There isn't necessarily any guarantee that it will exist in the future.
Also, if you check its definition, you'll be pointed to a better option:
flatten = itertools.chain.from_iterable

It's simply a alias for from_iterable on itertools.chain.

Please respect Python's naming conventions. Normal variable names should be in snake_case.

I would try and split this up into functions. Even if done simply, a procedure of
def main():
    initialize_net()
    propagate()
    backpropagate_errors()

makes it a lot easier to immediately understand the flow of the program and what code is a part of what step. That would also make it easier to control when the code in the script runs. You don't necessarily want the whole thing to run just because you loaded the file into your IDE.

Sorry, I wish I had the energy to do a good review of this. I remember my first NN from scratch. That was a fun project.


Alternative code to classes in Javascript?

A short review;

In stacktraces, person will be a nameless function, use function person(){} instead
There is no good reason to have different names (first->firstName) for your attributes. Using the same name allows you to use some nifty JS syntax
Your code will create a new function for each instance of person, unless you have a smart VM, that could be heavy on memory
I would extend the .prototype of person for fullName to prevent that memory issue
I also strive to name functions with a <verb><thing> scheme so I would call it getFullName()
Ideally functions that are akin to a class are capitalized, so person -> Person

So, all in all, this is my counter proposal:

    function Person(firstName, lastName, age, gender){
      Object.assign(this, {firstName, lastName, age, gender});
    }

    Person.prototype.getFullName = function personGetFullName(){
      return this.firstName + " " + this.lastName;
    }

    const John = new Person("John", "Anderson", 21, "Male");
    const Mary = new Person("Mary", "Smith", 32, "Female");
    console.log(John.firstName);
    console.log(Mary.getFullName());


After reading over the code snippets you included, it looks pretty simple.

The only concern I have is that if the switch statement reaches the default case, then res.status(400).send() is called , and then just after the switch statement, res.send() is called... If a 400 status is sent, then it doesn't seem appropriate to send the response data (even though transformed wouldn't be assigned in the default case.

One other improvement I see is that the 400 Bad Request response could be made consistent by moving that into a function and calling it in the two places where a 400 response is sent. So in the example below, that is defined as the function badRequest() inside the callback to router.get(), or that could be moved outside the callback and would then likely need to accept the response object as a parameter.

router.get('/:type', (req, res) => {
    function badRequest() {
        res.status(400).send({ error : "Bad API request" });
    }
    const type = req.params.type;

    axios.get('http://example.com/api/' + type)
        .then((response) => {

            let transformed = {};

            switch(type) {
                //..omitting lines for brevity
                default:
                    badRequest();
                    return; //stop the function, since 400 response sent
            }

            res.send({original: response.data, transformed: transformed });
        })
        .catch( () => {
            badRequest();
        });
});


The assignment mentions private fields. In Python those are created (faked, really) by prefixing the field with two underscores, as in __make.
Interactive command line programs are a scourge, because they are a pain to automate (including for testing purposes). Have a look at argparse to create a non-interactive program which would be called for example as ./automobile.py add "My car". In general there are no input calls in 99.998% of production code.
I'm not sure whether this recommendation is Pythonic, but I prefer creating a pretty-print method rather than overriding __str__ for printing the object in a user readable format.
The edit method takes a parameter which shadows an existing name. This is a common source of confusion and bugs.
add_vehicle should be inlined into __init__. It doesn't actually add a vehicle (which would mean adding it to something, such as vehicle_list), but rather initializes the vehicle fields, making it effectively a constructor.
Your code does not print the existing fields of a vehicle before replacing it. This may or may not be outside the scope of the assignment, but it is a usability issue.
The user variable serves no purpose and can be inlined.
edit asks for a one-offset index but when deleting a vehicle you use a zero-offset. You can use one or the other (ideally zero-offset for libraries and one-offset for user facing stuff) but it should be consistent.
Use with open(...) to guarantee closing the file cleanly.


Do prime factorization

Your current phi() function is correct but slow.  You would do better by finding the prime factorization of n and using the prime factors to calculate phi.  Your current phi() takes \$O(n)\$ time, but a prime factorization takes \$O(\sqrt n)\$ time.

Stop at one

At some point, if k is large, you will reach n of 1.  At that point you can stop because phi(1) = 1.  Actually if at any point k >= n, the answer should be 1 because phi(n) reduces n by at least 1.