Sorting the array of strings on their lengths in Java , Using Maps, ascending order....

I think you can use the Arrays.sort with Comparator to make this simple. just Override the comparator to compare the length of the array like this

public static String[] sortStrArray(String[] array){
   //sort arrays by length before returning
    Arrays.sort(array, new Comparator<String>() {
        @Override
        public int compare(String a, String b) {
            return Integer.compare(a.length(),b.length());//specifying compare type that is compare with length
        }
    });
     return array;
}

///Main Method here

String[] str = {"James","Ana","Michael","George","rose"};
    System.out.println(Arrays.toString(sortStrArray(str)));

Output:

  [Ana, rose, James, George, Michael]

with Java 8

 public static String[] sortStrWithLam(String[] array){
    //sort arrays by length before returning
    Arrays.sort(array,(a,b) -> Integer.compare(a.length(),b.length()));
    return array;
}


A class for solving a system of linear equations using Gaussian Elimination

Enumerable.Count() vs count access

One problem that slows your program's performance is that you call

Coefficients.Count()

In a few places while you are using array instead of an IEnumerable<T> where this is the only way to count the elements and as you can see this is a method rather than being a property. Instead you should simply call Coefficients.Length.

Edit

As @t3chb0t pointed in the comments and discussed here C# will simply return the Count property of the collection even when you call the method .Count() which means Coefficients.Count() & Coefficients.Length are almost equivalent in performance since the method has to do a type checking.

Nevertheless when possible, you should always prefer using your collection's specific functions and properties, rather than the generic ones. In your case Coefficients.Length.

Properties vs fields

Ideally you should always use properties instead of fields

public decimal[] Coefficients;
public decimal Result;

Can become

public decimal[] Coefficients { get; }
public decimal Result { get; set; }

You properties should be as restrictive as possible the less your class exposes the better.

Indexer with public backing collection ?

This doesn't makes much sense. Usually when a class has a indexer it's used internally with a private backing collection, but you have an iterator + a public collection.

In your case I don't see any reason why would you use an indexer here the public array Coefficients is more than enough and it's a lot more readable, so you should remove that indexer and just access the array like this :

public void AddCoefficients(LinearEquation pivotEquation, decimal factor)
{
    for (int i = 0; i < this.Coefficients.Length; i++)
    {
        Coefficients[i] += pivotEquation.Coefficients[i]*factor;
        if (Math.Abs(Coefficients[i]) < 0.000000001M)
            //Because sometimes rounding errors mean it's not quite zero, and it needs to be
        {
            Coefficients[i] = 0;
        }
    }
    this.Result += pivotEquation.Result*factor;
}

Redundant this qualifier

While I do agree that this is up to a personal preference I don't like it. You don't need a single this qualifier in your code it would be better to remove it it's just extra text to read..

Expression bodied properties + LINQ

public int IndexOfFirstNonZero
{
    get
    {
        for (int i = 0; i < Coefficients.Length; i++)
        {
            if (Coefficients[i] != 0)
            {
                return i;
            }
        }
        return -1;
    }
}

public int NonZeroCount
{
    get
    {
        int count = 0;
        for (int i = 0; i < Coefficients.Length; i++)
        {
            if (Coefficients[i] != 0) count++;
        }
        return count;
    }
}

You can really shorten those get only properties using LINQ :

public int IndexOfFirstNonZero
{
    get
    {
        int value = (int) Coefficients.FirstOrDefault(x => x != 0);
        return value == default(int) ? -1 : value;
    }
}

public int NonZeroCount => Coefficients.Count(t => t != 0);


Python Simple Range and Bearing Calculator using Complex Numbers

Keyword-only parameters
You are not using **kwargs correctly.  **kwargs should be used when you can accept any number of keywords, but you don't know what the keywords will be, such as dictionary creation.  If you only accept 2 keyword parameters, you should list those keyword parameters explicitly:
    def __init__(self, *, a_e=None, a_n=None):
        """
        :param a_e: initial easting
        :param a_n: initial northing
        """

        self.a_e = a_e
        self.a_n = a_n

That * marks the end of positional parameters.  a_e and a_n can be specified by keyword only.  Since both default to None, both are optional.  Any other keywords is reject with an error message, instead of silently being ignored.
Operator Precedence
        if self.a_e and self.a_n is not False:

This statement does not do what you think it does.  is not is higher precedence than and, so it reads:
        if self.a_e and (self.a_n is not False):

thus, if a_n is never given as False, the result of is not will be True, and the and will always result in the truthiness of a_e only.
You probably intended the evaluation to be:
        if (self.a_e and self.a_n) is not False:

which tests the truthiness of both a_e and a_n.  Sort of.  There are very few ways of getting something for which is not False is not true out of that expression.  The only way to get to the else expression is if a_e == False, or if a_e held a truthy value and a_n == False.  Again, since if the values are not given, they are defaulted to None, and since None and None evaluates to None, and None is not False is a true statement, the if clause would be executed.
So you probably wanted to write:
        if self.a_e is not None and self.a_n is not None:

Why not Zero?
If you used 0 as the default for a_n and a_e, then
            new_easting = self.a_e + delta_easting
            new_northing = self.a_n + delta_northing

new_easting would simply become delta_easting and new_northing would become delta_northing, and you could always do the addition and return `new_easting, new_northing.
    def __init__(self, *, a_e=0, a_n=0):
        """
        :param a_e: initial easting
        :param a_n: initial northing
        """

        self.a_e = a_e
        self.a_n = a_n

    def complex_randb(self, r, b):
        """
        An equation that using imaginary numbers to calculate the coordinates of a new
        point from a range and bearing of an old point
        :param r: range from original coordinate to new coordinate
        :param b: bearing from original coordinate to new coordinate
        """

        # -b is required as geodetic bearings are opposite to mathematical bearings
        t = complex(cos(radians(-b)), sin(radians(-b))) * complex(0, r)
        delta_easting = t.real
        delta_northing = t.imag

        new_easting = self.a_e + delta_easting
        new_northing = self.a_n + delta_northing

        return new_easting, new_northing

Naming
Your parameter names a_e, a_n, r, and b are too short and cryptic.  You should used easting northing, range, and bearing.
complex_randb is also confusing.  The input is real, the output is real.  The fact that complex numbers are internally used is an internal detail irrelevant to the caller.  What is randb, some kind of random b?  Oh, range_and_bearing!  But it is not a range and bearing function, it is a new coordinate function:
    def new_coordinate(self, range, bearing):
        """Doc-string without the complex number internal detail mentioned"""
        ...

The class name CmO is also quite cryptic.  Is that "C minus O" because it runs "C-O" calculations?  You need a better class name.


CSS Optimization? How can I clean my code

Use classes instead of ids

#even
#odd
#a, #b, #c, #d, #e

These are clearly repeating patterns that might happen several times in the same page.
An id is supposed to be unique on the page.

Use better names

The id or class of an HTML element, like a class or function name when programming, is supposed to describe it.
#a, #b, etc, are bad names. If your HTML and CSS are small, it's not complicated to figure out what they do. But if they grow, or if someone else picks up your code, it might start to get tricky to figure out what each class/id is about.

Clear nomenclature is better.

Use relative sizes

Your body defines font-size as 12px. Your h3, 13px.
If you change the body's font-size, you will have to hunt down all other definitions and update them - e.g. the h3.

If you define the first font-size absolutely (body: 12px) and then define all others relatively (h3: 110%), when you update the body's font-size the others adjust automatically.
This has the added advantage of being friendlier to people using user styles, e.g. people that use larger font-sizes to be able to read better.

Misc

On the hr, why not style the border instead of clearing the border and using background-colour?
I see too many negative margins. It feels somehow wrong.

"Two different tables"

I would first style them exactly the same, and then if necessary just add extra styles to differentiate them - perhaps change the colour of the borders or the background of the headers.
I'm not sure what you are asking there.


First you should not create on function for each column.
In place of :

var col0 = $("<fieldset />"),
    col1 = $("<fieldset />"),
    col2 = $("<fieldset />"),
    col3 = $("<fieldset />"),
    col4 = $("<fieldset />");

You should use :

var col_type  = "<fieldset />";

var cols      = {}

And then add it to your JSON :

cols["col"+ i % 5]  = $(col_type)...

So, you'll get a JSON object of this form :

{
  "col0":   <YOUR_jQuery element>,
  "col1":   <YOUR_jQuery element>,
  "col2":   <YOUR_jQuery element>,
  "col3":   <YOUR_jQuery element>,
  "col4":   <YOUR_jQuery element>
}

JSON are not support in jQuery for after() iteration. You must use an Array.

cols.push($(col_type)...)

And you won't need one variable for each new column.

Could you give a sample of your data.allLocales ?
And a sample of your HTML code ?

And no if(data.hasOwnProperty("allLocales")) is needed

Described :

for( column in data["allLocales"] ) {
  var name = data["allLocales"][column].name

  $("form legend").after(
    $("<fieldset />")
    .append(
      $("<label />")
      .text(name)
      .prepend(
        $("<input type='checkbox' />")
        .attr("value", name)
      )
    )
  )
 .end()
 .find("span.submit")
 .css({display: "block"});
}

Shorter :

for( column in data["allLocales"] ) {
  var name = data["allLocales"][column].name
  $("form legend").after($("<fieldset />").append(
    $("<label />").text(name).prepend($("<input type='checkbox' />").attr("value", name)))).end().find("span.submit").css({display: "block"}
  )
}


Faster way to render XML (10MB) file, loop the content and display output

There is no error handling.  Loading a remote resource is somewhat likely to fail.  Unfortunately, simplexml doesn't make error-handling easy.

Instead of filtering the XML using PHP code, I suggest selecting exactly the nodes you want using an XPath query.  The XPath library is more likely to be optimized than your PHP code.  In any case, it is certainly simpler to maintain one string describing the relevant nodes than a bunch of nested PHP statements.

I've chosen to use PHP templating for rendering, as it is easier to see that it is output.

<?php
$xml = simplexml_load_file('http://www.example.com/example.xml');
foreach ($xml->xpath("//comment[ProdNid = '" . htmlspecialchars($productId) .
                     "'][PostedOn][PostedBy][comment_text][position() <= 5]") as $comment) {
?>

      <?php echo htmlspecialchars($title);
      ?><?php echo htmlspecialchars($comment->comment_text);
      ?><?php echo htmlspecialchars($comment->PostedBy);
      ?>,<?php echo htmlspecialchars($comment->PostedOn); ?>

<?
}

All of those output strings probably need to be escaped to prevent, for example, cross-site scripting.  I've used htmlspecialchars() for that.


Python implementation of Conway's Game of Life

I think you have a couple of subtle bugs in the way you implement Conway's rules.
See my comments in the code for details:

for i in range(N):
    for j in range(N):
        # I changed the range of the extent of the sum, note +2 rather than +1 !
        total = grid[(i-1) % N:(i+2) % N, (j-1) % N:(j+2) % N].sum() - grid[i, j]
        if grid[i, j] == 1:
            if(total < 2) or (total > 3):
                newGrid[i, j] = 0
            # allow for survival in case of total = 2 or 3
            else:
                newGrid[i, j] = 1
        # allow for reproduction if cell is empty
        else:
            if total == 3:
                newGrid[i, j] = 1

With these edits the glider should glide :)


I think you need to document your assumptions and/or intended use cases a little better. Right now, I don't see how anything based on setjmp/longjmp could actually implement a coroutine, since longjmp can only ever jump upward in the call-stack, never downward. (Really, it can't jump "downward" because there is no "downward": the only things below us on the call-stack are things that have already finished executing, and things which will execute in the future.)

Notice that "things which will execute in the future" includes "interrupt handlers". You might want to check whether your implementation plays well with Unix signal handlers — I suspect it does not.

alloca(top - (stack_ + N));

This is a red flag: you're calling alloca without assigning the result anywhere. A sufficiently smart compiler will just optimize away this useless call. (Yeah, I kinda get what you're trying to do... but the compiler is under no obligation to get it.) What you really need to do here is heap-allocate a buffer for your stack, and then somehow get the saved stack pointer in the jmp_buf to point to it.

And I only kinda see what you're doing here, anyway. Are you assuming that the coroutine object itself must be allocated on the stack? What happens if I make a global or static coroutine object?

[this, f = ::std::forward<F>(f)](A&& ...a) __attribute__ ((noinline))

The __attribute__((noinline)) here is another red flag. This time I don't get what you're trying to do. What would break if this lambda's operator() got inlined?

Also, style nit: I've never seen anyone put a space after the word __attribute__ before.

Other style nits:

auto running() const noexcept

auto is a strange way to spell bool. It's not saving you any bytes.

// else do nothing

The above comment is highly misleading, in that it's followed by 13 lines of really dense code — hardly "do nothing"! I'd delete that comment.

auto top(reinterpret_cast<char*>(&top));

I'm actually amazed that this works, given that the decltype of &top is not known at the time the RHS is parsed. ...Oh wait, yeah, it doesn't work. Both GCC and Clang reject this code.

for (int i{}; i != 3; ++i)

Kudos for using prefix increment. Everything else about this for-loop is pretty unusual, though. I strongly recommend looping over the range [0,3) like this instead:

for (int i = 0; i < 3; ++i)

API design suggestions:

Empty angle brackets suck. I'd recommend something more like

template <size_t N> class coroutine_with_size { ... }

using coroutine = coroutine_with_size<4096>;

It's unfortunate that your coroutine has to do all its own I/O; a better design would be like the one found in Javascript (and Python), where coroutines can yield values. Unfortunately, the ability to yield values causes a cascade of API changes. Look:

c.run([](auto&& c) {
    for (int i = 0; i < 3; ++i) {
        c.yield(i);
    }
});

while (c.running())
{
    int ii = c.resume();
    std::cout << ii << std::endl;
}

Well, unless c is somehow "looking ahead" to determine the value it's going to return next time, c.running() doesn't really make sense anymore. We've got to have c.resume() do all the hard work, at which point we need a way to say "okay, no more data, please stop iterating". That is, we need a way for c.resume() to terminate execution but not return a value. This smells like an exception. So:

c.run([](auto&& c) {
    for (int i = 0; i < 3; ++i) {
        c.yield(i);
    }
});

while (true)
{
    try {
        int ii = c.resume();
        std::cout << ii << std::endl;
    } catch (const coroutine::done&) {
        break;
    }
}

But now what is c.run() actually doing? It can't be actually starting to run the provided lambda, because there's nowhere for us to stash the yielded result yet (we haven't gotten to ii's declaration). So all it's really doing now is constructing the coroutine object and then returning immediately. That smells like a constructor. So:

auto c = coroutine([](auto&& c) {
    for (int i = 0; i < 3; ++i) {
        c.yield(i);
    }
});

while (true)
{
    try {
        int ii = c.resume();
        std::cout << ii << std::endl;
    } catch (const coroutine::done&) {
        break;
    }
}

And unfortunately now we've got move-constructible coroutine objects, and your entire implementation strategy falls apart even more than it had been. Crap!

...Speaking of which, your current implementation provides defaulted copy and move constructors! You should definitely delete those:

coroutine(const coroutine&) = delete;
coroutine& operator=(const coroutine&) = delete;
// move operations get deleted implicitly due to the above;
// but I wouldn't object to deleting them explicitly as well

Getting back to the API-design example: the next step in a Javascript-like design would be allowing c.resume() to take input values, as well as yielding output values. Mind you, I'm not sure what the implementation for this would look like in C++. It might not be 100% possible. :)

auto c = coroutine([](auto&& c, int step) {
    for (int i = 0; i < 3; i += step) {
        step = c.yield(i);
    }
});

while (true)
{
    try {
        int ii = c.resume(1);
        std::cout << ii << std::endl;
    } catch (const coroutine::done&) {
        break;
    }
}

EDIT: Okay, I think it's not 100% possible — not without templating the coroutine class on the "inputs" and "outputs" (args-to-resume and args-to-yield) that it expects. I've done my own toy implementation here for comparison. Muddling through that implementation also helped me understand the undefined-behavior magic about which I complained at the top of this review.

At least in the trivial case you started with — a coroutine used only as a generator, and whose c.resume() takes no input values — it would make sense to provide a sort of coroutine_generator_iterator so that one could write simply

for (int ii : coroutine_generator_iterator(c)) {
    std::cout << ii << std::endl;
}

This coroutine_generator_iterator concept wouldn't be very useful for coroutines that were actually used as coroutines, e.g. passing control back and forth. But it's definitely a good idea if you're just trying to do Python-style generator functions in C++.


Route structure for multiple associations in Rails

This is probably fine, though there are other ways to do it like passing filters to /recipes (?category_id=x or ?book_id=x). Your controller action is probably fine too, though I may have considered making multiple controllers.

Though i'm not sure why you're doing find_by_category instead of the a find_all_by_category or the same .where as you're doing for book_id. Also, Recipe.all is more rails 3.


Throttling duplicate requests in an HttpModule

Semaphore has a bigger overhead than a traditional lock pattern, aside being too complex for what you need. You could use a class such as this:

public class DeDuper : IDisposable
{
    private static readonly ConcurrentDictionary<String, Object> currentRequests = new ConcurrentDictionary();
    private string _hash;

    public DeDuper(string hash)
    {
        _hash = hash;
        var lockable = currentRequests.GetOrAdd(hash, () => new Object());
        Monitor.Enter(lockable);
    }

    public void Dispose()
    {
        object lockable;
        if(currentRequests.TryGetValue(_hash, out lockable) && Monitor.IsEntered(lockable))
        {
            Monitor.Exit(lockable);
        }
    }

    ~DeDuper()
    {
        Dispose();
    }
}

Then your class can simply be written as:

private async Task ProcessImageAsync(HttpContext context)
{
    using(new DeDuper(hash))
    {
        // do awaitable task
    }
}

You will have a class that only allows a single hash to be run at any one time, with the added side effect of not having to release the Semaphore ;)

Not sure if this would work, i'd need to benchmark but, you could reduce the amount of memory further by reducing the commonality before you hash, eg:

http://mydomain.com/path1/part1   becomes   path1/part1
http://mydomain.com/path1/part2   becomes   path1/part2

Update

I thought that you might be able to use Interlocked.CompareExchange to do the job that you want, but it turns out AutoResetEvent works better. Here is a working sample:

Actual locking code

public class LockAcquisition<T> : IDisposable
{
    private static readonly ConcurrentDictionary<T, LockWrapper> currentRequests = new ConcurrentDictionary<T, LockWrapper>();
    private readonly LockWrapper _currentLock;

    public LockAcquisition(T key)
    {
        _currentLock = currentRequests.GetOrAdd(key, new LockWrapper());
        _currentLock.AcquireLock();
    }

    public void Dispose()
    {
        if (_currentLock != null)
        {
            _currentLock.Dispose();
        }
    }

    ~LockAcquisition()
    {
        Dispose();
    }

    private class LockWrapper : IDisposable
    {
        private readonly AutoResetEvent _locker = new AutoResetEvent(true);

        public void AcquireLock()
        {
            _locker.WaitOne();
        }

        public void Dispose()
        {
            _locker.Set();
        }

        ~LockWrapper()
        {
            Dispose();
        }

    }
}

Wrapped to use a string as the key

public class LockAcquisition : LockAcquisition<String>
{
    public LockAcquisition(string key)
        : base(key)
    {
    }
}

Testing code

internal class Program
{
    private static void Main(string[] args)
    {

        Run();
        Console.ReadKey();
    }

    private static async void Run()
    {
        const string hash = "123456";
        const string hash2 = "1234567";

        using (new LockAcquisition(hash))
        {
            using (new LockAcquisition(hash2))
            {
                using (new LockAcquisition(hash)) // This will deadlocked
                {
                }
                await Task.Delay(TimeSpan.FromSeconds(2));
                Console.WriteLine("Done 2");
            }
            await Task.Delay(TimeSpan.FromSeconds(2));
            Console.WriteLine("Done 1");
        }
    }
}


HTML5 Local Storage toggle and save multiple classes

The following are all acceptable ways to set/get values to/from localStorage (or sessionStorage for that matter):

// set
localStorage.key = 'value';
localStorage['key'] = 'value';
localStorage.setItem('key', 'value');

// get
value = localStorage.key;
value = localStorage['key'];
value = localStorage.getItem('key');

I think from a practical standpoint though, you might see explicit setItem() or getItem() method calls used most frequently, as oftentimes one might find themselves working with dynamic key names, which would eliminate the first usage example from each of the the sets above.  Oftentimes developers choose to simply be consistent and use the getter/setter methods rather than mix direct property access when key names are known vs. getter/setter or "array-like" access when the key names are dynamic.

More complex applications may also abstract out direct access to localStorage and sessionStorage altogether, especially when dealing with browsers that do not support web storage (and therefore may need cookie-based fallback).  In such cases, you would absolutely not be able to have hard-coded key names when interacting with the underlying web storage, because you might have a usage pattern like:

myStorage.set(key, value, inSession) {
    if (typeof Storage !== undefined) {
        // we have local and session storage available
        if(inSession === true) {
            sessionStorage.setItem(key, value);
        } else {
            localStorage.setItem(key, value);
        }
    } else {
        // fallback
    }
}


Overview
It's a mistake to be using RAW pointers you should definitely be using some form of smart pointer here.
It does two things for you:

It will greatly simplify your code.
It will remove the bugs !!!

If you have owned RAW pointers in your class then you MUST implement the rule of three. You do (have owned RAW pointers) but your don't (implement the rule of three). As a result your code is broken.
{
    Inventory   a;
    a.createNewInventoryItem("Wine");

    Inventory   b(a); // You did not implement the copy constructor
                      // nor did you disable it, so the default version
                      // is generated. So this copy is allowed.
                      //
                      // Both a and b have a copy of the same RAW pointer
                      // internally.
}
// b is destoryed (which destroys the pointer)
// a is destroyed (which also destroys the pointer) but that is UB as
// it has already been destroyed.

There are several other things that go wrong but you get the drift.
If you had used std::unique_ptr<> this would have prevented the Inventory object from being copied. If you had used std::shared_ptr<> copying would have been allowed (not sure if the semantics would be correct).

I would point out that you only need to store pointers and have dynamic allocation if you have polymorphic types. Otherwise you can simply store the object directly in the container:
//  This will handle most situations.
std::vector<InventoryItems>    m_items;
                 ///     ^^^ note: No pointer

You do need pointers for polymorphic types:
class Animal { /* Stuff */}
class Cat: public Animal { /* Stuff */}
class Dog: public Animal { /* Stuff */}

std::vector<Animal*>            m_items;
// Here we need pointers because we may store a Cat or a Dog
// So the object stored is not an Animal and we don't know how
// large it is at compiler time.

Interface Design:
class Inventory
{
public:
    void createNewInventoryItem(/*Stuff*/);
    void deleteInventoryItem(int posInVector);
    InventoryItems* getItem(int posInVector);
};

Sure you have a create/delete here and a get.
But when you create an item you don't know where in the container it is. So you can not directly get it back. You could use something about the input parameters that you could reuse (like the item name) or I would expect the create to return some identifier that can be used by the delete and get.
Alternatively your interface simply displays all the items and then you manipulate it from there. To do this you need to loop over all the items. But how many items do you have to loop over? In this case I would expect the class to provide some way to know the range of items available. It could be a size() method or alternatively you could provide iterators of the class so you know how to loop over the inventory.

Representation of the Inventory:
I can create two inventory items that have the same name:
    Inventory   a;
    a.createNewInventoryItem("Wine");
    a.createNewInventoryItem("Wine");

There are now two wine items in the inventory. This does not make sense to me. When you add a new item you should check to see if it already exists. If it does then you need to combine the data (or throw an error). You can do this with std::vector but there are other containers that will help you (maybe std::map).
Code Review
    void createNewInventoryItem(std::string itemName = "", unsigned int maxQuantity = 0, unsigned int orderThreshold = 0, double price = 0.0, int quantityInInventory = 0);

You can create an inventory item without specifying anything! If you pass no parameters it still works and you get an item with no name and no value.

When you create an inventory item it does not return anything. So how do you know what item to delete?
    void deleteInventoryItem(int posInVector);

You can randomly delete items (but there is no understanding of what item will be deleted (unless you get every item first and examine it).
Personally I would index items by their itemName. I would then allow both getItem() and deleteInventoryItem() to work by passing the name.

Don't return a pointer from a get(). I would return a reference to the object. Just because you store it as a pointer does not mean you need to expose that fact to the users of your class.
    InventoryItems* getItem(int posInVector);

Don't use std::endl here; prefer to use "\n" instead.
    std::cout << "Inventory created" << std::endl;

The difference between these two is that std::endl in addition to outputting the newline character it forces the stream to flush. There is no need to flush the stream as this happens automatically when it needs to happen. The problem with forcing a manual flush is that it can be inefficient and cause the application to slow down if there is to many flushes.
If you look at questions on SO asking why writing to standard output in C++ is so slow the actual solution is simply to stop using std::endl and allow the stream to flush itself (and the code magically speeds up).

Sure you can loop like this:
    for (int i = 0; i < m_inventory.size(); i++) {
        deleteInventoryItem(i);
    }

But I would note that this is broken because you call deleteInventoryItem() which not only deletes the item but removes it.
Imagine you have a vector with 4 items.

You call delete on item 0. This deletes the item and removes it. Thus moving everything in the vector down one item (new length is 3)
You increment i (i is now 1)
You call delete on item 1. This deletes the item and removes it. Thus moving everything in the vector down one item (new length is 2)
you increment i (i is now 2)
You exit the loop.

You only deleted two items.
But a vector is a range. So you can use the range based loop:
    for (auto& item: m_inventory) {
        delete item;
    }

    m_inventory.clear();

Why do you have a two phase creation of a InventoryItems?
    InventoryItems* newItem = new InventoryItems;
    newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price, quantityInInventory);

You should pass all those parameters to the constructor.

One thing I would add is that you don't know the number of items in the inventory. So you just have to loop over them until you get an exception thrown. It may be worth adding a size() function so you can get the size so you know the limit of the number of items.

You don't even need to use pointers here. There is no polymorphic objects involved. You should simply have used normal objects in the vector and it would have worked as expected.

Don't use unsigned integer types. In most situations they will cause you a lot of headaches. If that extra bit is something you need then you are already at the boundary of your system and should upgrade the integer type to the next larger type to get a bunch more bits.
Save the unsigned integer types for flags.

Don't use double for monetary units. Not all values can be represented exactly and you are going to run into rounding errors when you start adding things up.
Rather use an integer type. If you are using dollars in a double then simply use an integer but store the number of cents.

Potential Solution
How I would do it:
#include <map>
#include <iostream>

#include "InventoryItems.h"

class Inventory
{
    using Container = std::map<std::string, InventoryItems>;
public:
        Inventory();

        void createNewInventoryItem(std::string itemName,
                                    int maxQuantity = 0,
                                    int orderThreshold = 0,
                                    int price = 0,
                                    int quantityInInventory = 0);

        void deleteInventoryItem(std::string const& itemName);
        InventoryItems& getItem(std::string const& itemName);

        using iterator = typename Container::iterator;

        iterator begin() {return m_inventory.begin();}
        iterator end()   {return m_inventory.end();}

    private:
        Container    m_inventory;
};

Inventory::Inventory()
{
    std::cout << "Inventory created" << std::endl;
}

void Inventory::createNewInventoryItem(std::string itemName,
                                       int maxQuantity,
                                       int orderThreshold,
                                       int price,
                                       int quantityInInventory)
{
    auto find = m_inventory.find(itemName);
    if (find == itemName.end()) {
        m_inventory.emplace_back(std::piecewise_construct,
                                 std::forward_as_tuple(itemName),
                                 std::forward_as_tuple(maxQuantity, orderThreshold, price, quantityInInventory));
    }
    else {
        // I don't know how your inventory works.
        // This is just s guess/suggestion.
        find->second.setMax(std::max(maxQuantity, find->second.getMax());
        find->second.setOrderThreshold(std::max(orderThreshold, find->second.getOrderThreshold());
        find->second.setPrice(price);
        find->second.increaseInventory(quantityInInventory);
    }
}

void Inventory::deleteInventoryItem(std::string const& itemName)
{
    m_inventory.erase(itemName);
}

InventoryItems& Inventory::getItem(std::string const& itemName)
{
    auto find = m_inventory.find(itemName);
    if (find == m_inventory.end()) {
        throw std::outofbound("Or something like that");
    }
    return find.second;
}


Manhattan Distance + Linear Conflicts scoring function for sliding tile puzzle solver

Bug: if statement always false

I'm confused about this if statement:

            if (goalRow[j] == row && b._tiles[i] > b._tiles[j] &&
                    goalRow[i] < goalRow[j]) {
                md += 2;
            }

and in particular the last condition goalRow[i] < goalRow[j].  When the last condition is checked, we already know that goalRow[i] == row (from above) and goalRow[j] == row (from the first condition), so that last condition will always be false.  I think that perhaps you meant to use goalCol instead:

            if (goalRow[j] == row && b._tiles[i] > b._tiles[j] &&
                    goalCol[i] < goalCol[j]) {
                md += 2;
            }

Bug 2: if statement still always false

After looking over the corrected if statement another time, I found that it is still always false.  The problem is that b._tiles[i] > b._tiles[j] implies that goalCol[i] > goalCol[j] because goalCol[x] is derived in a linear fashion from b._tiles[x].  I believe that you really meant this:

            if (goalRow[j] == row && i > j && goalCol[i] < goalCol[j]) {
                md += 2;
            }

But the simpler way to do this is to just make your loop run from the start of the row to i, like this:

        for (uint8_t j = row * b._width, l = j + col; j < l; j++) {
            if (b._tiles[j] == 0) {
                continue;
            }
            if (goalRow[j] == row && goalCol[i] < goalCol[j]) {
                md += 2;
            }
        }

I'm surprised that your program seemed to run faster after only changing goalRow to goalCol.  You may want to print something out if it ever reaches the md += 2 line to make sure you are ever getting there.  I ran a little test program to generate random boards and it never hit that statement until I fixed it with both fixes.


Can anyone take the for loop out of this code?

The following replaces the loop using higher-order functions:

$para = function($p) { return "<p>$p</p>\n"; };
$content = implode('', array_map($para, array_slice($paragraphs, 0,  $paragraph_count)));


Flask app to return close prices & average

Relays
Your current design:

fetches data from alphavantage once, on startup
offers it to anyone who hits any of your interfaces on port 5000 (which, by the way, is already used by a large number of services other than the default Flask development webserver)

This seems unusual. Perhaps it's just to try out a random use of Flask for learning purposes, which is fine, but:
If you really want to preserve this API as an effective relay, it should probably be authenticated. You can add that here, or in a frontend (nginx, etc). Also, just bind to 80 once you hit production. A frontend can do HTTPS termination effectively translating from 443 to 80.
If all you want is code to conveniently get alphavantage data, don't make your own HTTP API; just make a requests wrapper library.
Globals

To be passed in with ENV-Vars

should apply to api_key, as that's a secret that should not be hard-coded.
Also, it's an odd choice to hard-code symbol. With very little introduced complexity, you can make your code parametric on symbol (and perhaps also function).
Otherwise: session, output, data, etc. probably shouldn't be globals. Consider making an LRU cache for data, and taking advantage of Flask's before_first_request, and moving the great majority of your global code into functions.
For session in particular, there's currently no advantage to having that - you might as well just requests.get since you only do it once.
Request formation
Don't pre-format key-value query parameter pairs. Instead,
session.get(
    'https://www.alphavantage.co/query',
    params={
        'apikey': API_KEY,
        'function': 'TIME_SERIES_DAILY_ADJUSTED',
        'symbol': 'MSFT',
    },
)

Response parsing
json.loads(output.text)

is unnecessary. Just use output.json. Also, between get() and .json, call output.raise_for_status. This will increase the quality of error information when something goes wrong.
Sum over an iterable
sum(list(output.values()))

should not use list. sum can operate on any iterable.


As pointed out, top-down recursive approaches are almost never a good idea when it comes to Fibonacci numbers. Consider the alternative iterative approach:

def fib(n):
    while n <= len(fib.cache):
        fib.cache.append(fib.cache[-1] + fib.cache[-2])
    return fib.cache[n]
fib.cache = [0, 1]

Notice how the memoization cache is stored as an attribute of the function, which is the closest thing in Python to having a static variable inside a function.


This is exactly the kind of task that should be handled using collections.Counter, which offers a most_common() method to extract the results.


Determining whether a task is active based on many conditions

Some comments on your code:

Keep the line length below 80-100 or the code becomes unreadable.
self[:active] == false -> !self[:active]
Checks should be terser, encapsulate logic in methods.
A return at the end of a code block is neither necessary nor idiomatic.
[Subjective] I usually prefer full-fledge conditionals to guards, indentation helps a lot to see what's going on.

In a first refactor, I'd write a more readable case:

def active?
  case
  when (!self[:active] && !ignore_column) || suspended || completed_at
    false
  when failed_attempts >= MAX_FAILED_ATTEMPTS
    if suppress_error_emails
      false
    end
      message = "Too many failed attempts for task execution. " +
        "#{failed_attempts}/#{MAX_FAILED_ATTEMPTS} failed attempts for Task #{id}."
      SystemMailer.error(message: message)
    end
  # ...
  # more conditions here, you get the idea
  # ...
  when template &&
       (status_opted_out? || con_mktg_opted_out? || user_mktg_opted_out?)
    false
  else
    true
  end
end

On a second refactor, I'd probably move all logic to separate methods. Now you could write:

def active?
  condition1? && condition2? && ... && conditionN?
end


As always, the first option is to use PyPy:

>>> time python2 p.py 0 30000
[]
14.4747481346
python2 p.py 0 30000  14.50s user 0.01s system 100% cpu 14.500 total

>>> time pypy p.py 0 30000
[]
0.990810871124
pypy p.py 0 30000  1.06s user 0.03s system 99% cpu 1.098 total

You shouldn't use star imports. Instead directly import the things you want:

from fibonacci_conjecture import is_fibo, is_prime

You should wrap the main body in a function called main.

The iteration would be better as a generator:

def get_falsifiers(start, end):
    for i in range(int(start), int(end)):
        if is_prime(5*i*i+37) and is_fibo(5*i*i+37):
            yield i

This would be run as:

_list = list(get_falsifiers(start, end))

Note that _list is a poor naming choice since it refers to the type and not the value. Something like falsifiers would be better.

These:

def fibonacci_conjecture(end):
    return (True not in map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1)]))

def second_way(end):
    return (True not in map(is_prime, [i**2+41 for i in range(end+1) if is_fibo(i)]))

def third_way(end):
    return (True not in map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1) if minus_four(i)]))

would be better as

def fibonacci_conjecture(end):
    return not any(map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1)]))

def second_way(end):
    return not any(map(is_prime, [i**2+41 for i in range(end+1) if is_fibo(i)]))

def third_way(end):
    return not any(map(is_prime, [fibo(i)*fibo(i)+41 for i in range(end+1) if minus_four(i)]))

Further one should flatten the list comprehensions and map:

def fibonacci_conjecture(end):
    return not any([is_prime(fibo(i)*fibo(i)+41) for i in range(end+1)])

def second_way(end):
    return not any([is_prime(i**2+41) for i in range(end+1) if is_fibo(i)])

def third_way(end):
    return not any([is_prime(fibo(i)*fibo(i)+41) for i in range(end+1) if minus_four(i)])

You also then can just use a generator comprehension:

def fibonacci_conjecture(end):
    return not any(is_prime(fibo(i)*fibo(i)+41) for i in range(end+1))

def second_way(end):
    return not any(is_prime(i**2+41) for i in range(end+1) if is_fibo(i))

def third_way(end):
    return not any(is_prime(fibo(i)*fibo(i)+41) for i in range(end+1) if minus_four(i))

Your fibo(i)*fibo(i) requires two calls to fibo - this can be one with fibo(i) ** 2. Consider also using PEP 8 spacing. You can also remove the if in place and an and:

def fibonacci_conjecture(end):
    return not any(is_prime(fibo(i) ** 2 + 41) for i in range(end+1))

def second_way(end):
    return not any(is_fibo(i) and is_prime(i ** 2 + 41) for i in range(end+1))

def third_way(end):
    return not any(minus_four(i) and is_prime(fibo(i) ** 2 + 41) for i in range(end+1))

Some of these names (eg. minus_four) are particularly cryptic.

Your fibo actually takes \$\mathcal{O}(e^n)\$ time -  what you really want as a basis is a generator to let you do

return all(not is_prime(f ** 2 + 41) for f in fibonacci_numbers(count))

This generator is typically written something like

def fibonacci_numbers(count):
    prev = 1
    curr = 0

    for _ in range(count):
        yield curr
        prev, curr = curr, prev + curr

Now each number takes \$\mathcal{O}(1)\$ (approximately), which is much faster.

Doing this actually quickly leads to an

OverflowError: long int too large to convert to float

since math.sqrt(x) needs to convert

400624556078135004801005131049868376277487458971454665625744044750241868509910118684223898375755770833486910716679881483356186192835924621611785526885928263384281394311273430963137957057246385921466246089044680129333479765771922731594997403327473526588890161488739900887481571279985972340702546216307221018066

to a float.

One other problem is also precision issues. For large numbers your is_perfect_square fails:

is_perfect_square(100000000**2 + 1)

since

float(100000000**2 + 1) == 1e+16

which is rounded. So the results are actually meaningless.


User-defined function for estimating coefficient of performance

You are using the Double data type for all variables. I think this is a good thing since it should avoid conversions. But it is probably too large for your purpose.

From the doc:

  Double (double-precision floating-point)  8 bytes
    -1.79769313486231E308 to -4.94065645841247E-324 for negative values

Source: Data type summary

Perhaps using the single data type is enough ?

  Single (single-precision floating-point)  4 bytes     -3.402823E38 to
  -1.401298E-45 for negative values
  1.401298E-45 to 3.402823E38 for positive values

You can try and compare results.

For reference a response I made on another topic, that includes comments about data types: Adding qty If duplicates keys found VBA

It is unfortunate that the variable names (a..f) are not descriptive and
meaningful. That makes logic errors harder to spot since the variables look  all the same. Surely all those values have a meaning ?

Something else: if you are doing calculations in a loop and assuming this is in Excel, you can suspend automatic recalculation at the beginning of your procedure:

Application.Calculation = xlManual

Turn it back on when you are done:

Application.Calculation = xlAutomatic


Observer pattern using a set of observers and delegated properties

You don't need a wasPresent variable. MutableSet.add returns true if the element was added to the set:

if (observers.add(observer)) {
    init(observer)
}

Sometimes in Kotlin you don't have to declare temporary variables so that you can do something with a return value before returning it. e.g.:

return ObservedProperty(initialValue, onChanged).apply { properties.add(this) }

Unfortunately this can sometimes look a bit strange using this, etc. but in Kotlin 1.1 you can use bound callable references:

return ObservedProperty(initialValue, onChanged).apply(properties::add)

You might want to take a look at Delegates.observable - stdlib - Kotlin Programming Language which you may be able to reuse to improve and reduce your code.


Indeterminate progress bar with Raspberry Pi

Naming

For first, your code looks good, it's not so hard to understand.

  It works, but I feel that it is not perfect.

There is no perfect code. A code is evolving, a code is changing. So, instead of chasing perfection, you should pursue such things like readability.

Your function names are a bit confusing. For example without knowing the body of the switchLine function it's hard to firgure out that it will change the state of several pins sequentially with some delay.

How about a main() function like the following?

int main() {
    struct PinLedMap connections = {{
        { 0, LED_0 }, { 1, LED_1 }, { 2, LED_2 }, { 3, LED_3 },
        { 4, LED_4 }, { 5, LED_5 }, { 6, LED_6 }, { 7, LED_7 }
    }};
    assignPinsToLeds(&connections);
    initialize();

    setDelayOfSequentialOperations(250);
    while(1) {
        turnLedsOnSequentially();
        turnLedsOffSequentially();
    }
    return 0;
}

I think that the code above is clear enough, and easy to understand.

Responsibility

I don't see the reason why do the switchPin function applies the delay? The switchPin function should switch the state of specified pin only. Applying delays between turning LEDs on or off is the responsibility of your switchLine function.

In my example the turnLedsOnSequentially and the turnLedsOffSequentially functions work as follows:

void setLedsSequentiallyTo(enum LedState state) {
    int index;
    for(index = 0; index < NUMBER_OF_LEDS; ++index) {
        setLedTo(index, state);
        delay(_delayInMilliseconds);
    }
}
void turnLedsOnSequentially() {
    setLedsSequentiallyTo(LED_ON);
}
void turnLedsOffSequentially() {
    setLedsSequentiallyTo(LED_OFF);
}

Complete code

I took my example into pieces, so it contains a header file (led_control.h) and two source files (led_control.c, main.c). I've presented the main.c before, so I won't present it again.

led_control.h

#ifndef LED_CONTROL_H
#define LED_CONTROL_H

enum LedNumber {
    LED_0, LED_1, LED_2, LED_3, LED_4, LED_5, LED_6, LED_7,
    NUMBER_OF_LEDS
};
struct PinLedPair {
    int pinNumber;
    enum LedNumber ledNumber;
};
struct PinLedMap {
    struct PinLedPair elements[NUMBER_OF_LEDS];
};

void assignPinToLed(struct PinLedPair* connection);
void assignPinsToLeds(struct PinLedMap* connections);
void initialize();
void setDelayOfSequentialOperations(int delayInMilliseconds);
void turnLedOn(enum LedNumber ledNumber);
void turnLedOff(enum LedNumber ledNumber);
void turnLedsOnSequentially();
void turnLedsOffSequentially();

#endif /* LED_CONTROL_H */

led_control.c

#include "led_control.h"
#include <wiringPi.h>
#include <assert.h>

int _leds[NUMBER_OF_LEDS] = { 0 };
int _delayInMilliseconds = 100;

enum LedState {
    LED_OFF = LOW, LED_ON = HIGH
};

void assignPinToLed(struct PinLedPair* connection) {
    assert(connection);
    _leds[connection->ledNumber] = connection->pinNumber;
    pinMode(connection->pinNumber, OUTPUT);
}
void assignPinsToLeds(struct PinLedMap* connections) {
    int index;
    assert(connections);
    for(index = 0; index < NUMBER_OF_LEDS; ++index)
        assignPinToLed(&connections->elements[index]);
}

void initialize() {
    wiringPiSetup();
}
void setDelayOfSequentialOperations(int delayInMilliseconds) {
    _delayInMilliseconds = delayInMilliseconds;
}

void _setLedTo(enum LedNumber ledNumber, enum LedState state) {
    digitalWrite(_leds[ledNumber], state);
}
void turnLedOn(enum LedNumber ledNumber) {
    _setLedTo(ledNumber, LED_ON);
}
void turnLedOff(enum LedNumber ledNumber) {
    _setLedTo(ledNumber, LED_OFF);
}

void _setLedsSequentiallyTo(enum LedState state) {
    int index;
    for(index = 0; index < NUMBER_OF_LEDS; ++index) {
        _setLedTo(index, state);
        delay(_delayInMilliseconds);
    }
}
void turnLedsOnSequentially() {
    _setLedsSequentiallyTo(LED_ON);
}
void turnLedsOffSequentially() {
    _setLedsSequentiallyTo(LED_OFF);
}


4 distinct integers, whose reciprocals sum up to 1

Fraction has numerator and denominator, which are cleaner than the mucking around with int().

Appending to an external accumulator is quick and easy, but yield may give more readable code. If you combine that with passing the minimum next denominator and the remaining fraction (rather than respectively extracting them and recalculating them on each call) you get

from fractions import Fraction

def solve(num_terms, min_denom, sum_needed):
  if num_terms == 1:
    if sum_needed.numerator == 1 and sum_needed.denominator >= min_denom:
      yield [sum_needed.denominator]
  else:
    next_min = max(min_denom, int(Fraction(1,sum_needed)) + 1)
    next_max = int(Fraction(num_terms,sum_needed))
    for next in range(next_min, next_max+1):
      yield from [[next] + tail for tail in
                  solve(num_terms - 1, next + 1, sum_needed - Fraction(1, next))]

print (list(solve(4, 1, Fraction(1,1))))

Obviously readability is subjective to some degree, but I prefer the version with yield.

I should note that it would be more Pythonic to use a double comprehension instead of a comprehension inside a loop, but I don't find double comprehensions very readable.

itertools can be used, but I don't think there's any way to do so really efficiently - i.e. with early aborts. I think you would have to bound the maximum possible denominator:

# The largest denominator will be the last term when the previous terms are
# as large as possible
recip_max_denom = 1 - sum([Fraction(1,x) for x in range(1, num_terms)]
max_denom = recip_max_denom.denominator // recip_max_denom.numerator

Then you can use

itertools.combinations(range(1, max_denom + 1), num_terms)

and filter to those which give the correct sum.


JS exercise to process an array of animals

I do spot a minor "C# accent" :)

Unless you are dealing with very unruly data, an idiomatic approach would likely drop most of the special-case checks and use map instead of the for-loop:

// This function could even be removed, depending on the larger details of your code
function getAnimals(data) {
  return data.map(getAnimal);
}

function getAnimal(item) {
  return {
    id: item.id,
    type: item.type,
    name: item.name,
  };
}

If the source array may contain null-ey items, you could filter them out beforehand, instead of after attempting to process them:

function getAnimals(data) {
  return data
    .filter(Boolean)
    .map(getAnimal);
}

(null or undefined will evaluate to false in a boolean context.)

If you have a utility library like Lodash on hand, you could use a function like pick to further simplify things:

const getAnimal = item => _.pick(item, ['id', 'type', 'name']);

Otherwise, on a more general scale, most JS code tends to omit explicit null/undefined checks. Let the code throw an error if necessary, otherwise fix whatever is calling your function, eg. by filtering. There's a place for such checks, but in JS it's usually not in every function.

  What I'm really talking about is the way the code is structured. For example, as an "old school" C# developer, I like creating variables and assigning my data to them and cleanly returning them in my methods.

I don't think the code you've provided here merits any temporary variables. Idiomatically, it's a single function applied via Array#map.

Minor syntax things

Your functions are currently in the global namespace, because JS permits variables with no qualifiers as implicit globals. Prefix them with const or let to explicitly make them variables, or use function when possible since it plays nicer with hoisting:

const processArray = (myArray) => {...
// or, as above
function processArray(myArray) {...

Many people omit the braces around the single argument of an arrow function. It's optional, but reads slightly cleaner:

const processArray = myArray => {...

myArray is a toy name, I am assuming this is a toy example
Always use === for comparisons, which you do, unless you want to compare against both null and undefined, which you do, in which case you can do myArray == null. To go a bit further, your first conditional would more simply be written:

if (!myArray || !myArray.length) {

since null and undefined are both "falsey", and so is a zero length.

Essentially: your code works fine -- but it could be a lot shorter.


How can I remove this for-loop in this competitive FizzBuzz code?

The title of your post puts a lot of stress on removing the for loop. Can it be removed?

No, it cannot. You need at least one loop to solve the fizz-buzz...

Additionally, the 'print' statements are by far the largest bulk of your performance problem.

I don't really believe that this code suffers from a problematic performance issue, but, if you want it to go faster, your best bet would be to accumulate all your String values and only print the line once:

NSMutableString* result;
....

for (...) {
    .....
        [result appendString:@"FB "];
    .....
        [result appendFormat:@"%d ", i];

}
printf(result);
printf("\n");

This saves a fair number of unnecessary print statements, and your performance will improve as a result.


Sending an uptime to a remote server through SSH with the method pxssh

It sounds like the problem is not the code but how to package it up in a such a way that only functions that you want to call get called when you want to call them.

A part of the solution is as you have defined it ...

if __name__ == '__main__':
    conn_up()

... this would ensure that conn_up() gets called, but you could just treat conn_up as a constructor and pull all the code from it and put it in another function which you then call on demand.

From further discussion with you on discord it seems that the issue is also in part about extending this in the future so I would advise packaging this up in to a class that you might add functions to, then can add to your "if __name__ == '__main__':" block additional functions as you add them, or through some other logic in a new "onStart()" function or something.

There's a great post on this here ...

Hope this helps.


Default description

public String getDescription() {
    if (description == null) {
        return "";
    }
    else {
        return description;
    }
}

Depending on how this method is used, it may make sense to take in a default value here, and return the default if the field is null, this may simplify code using this class.


Transfer of data instead of copy.paste.clear used

I think apart from the performance your code also has some other issues. Let me first come to the most problematic, then make some suggestions regarding the performance, and finally make some general comments.

The biggest problem I see here is that procedure also copies functions. This can be very problematic if the references within the formulas are not absolute references. Then they will point somewhere totally different than before.

From the point above, I guess that you are only intending to copy values. In this case, you can avoid using the the rather slow copy function and simply copy the values accessing them via the Value or Value2 property of the cells. (The latter is faster and behaves more reliably, see this question on Stack Overflow.)

To speed up things even somewhat more, you can read the entire range you like to copy into an array via Value2 and then process it. You can also set entire ranges from arrays by setting the Value property of a range. Using arrays is the fastest thing you can do to copy large ranges. (See this blog post testing the various ways to copy the values in ranges in Excel.)

Now, the general comments on the code:

The use of Target in the procedure, or at least its name, is rather confusing. Apparently, it is only used in the condition that is tested and it is never used as a target to copy or the like. It seems as if the check might belong into another procedure calling this one.
Your code will throw an error whenever Sheet(CE1 Data) is not the active sheet. The problem is that in:

Set rngQuantityCells = Sheets(CE1 Data).Range(B120, Range(B120).End(xlDown))

the second Range is not qualified, i.e. it is always implicitly referring to the active sheet. It would be a good practice to always qualify calls to Range, even if it's from ActiveSheet.
If the sheet Sheet(CE1 Data) is not active, the paste range will not be inside the cleared range because the paste range will be on the active sheet. (This obviously only applies after qualifying the offending Range from the second comment.)
You might want to save the worksheet in a variable and not query the Sheets collection all the time. Personally, I would even inject the worksheet to use as a parameter of type Worksheet.
Given that you apparently only use this procedure from the worksheet Sheet(CE1 Data), you might consider using a With statement to access the sheet.
You are using quite a number of magic numbers in the procedure, like the bounds in which Target may be or the explicit ranges. It might be better to use constants or named ranges. If you ever want to change from where this procedure reads or to where it writes, named ranges would make your life easier.

Finally, you might consider to remove most blank lines and indent according to nesting like in:

For Each rngSinglecell In rngQuantityCells
    If rngSinglecell.Value = Primary Then
        Range(Range(A & rngSinglecell.Row), Range(D & rngSinglecell.Row)).Copy Range(K & Rows.Count).End(xlUp).Offset(1)
    ElseIf rngSinglecell.Value = Backup Then
        Range(Range(A & rngSinglecell.Row), Range(D & rngSinglecell.Row)).Copy Range(P & Rows.Count).End(xlUp).Offset(1)
    End If
Next

EDIT:

I did not really realize that you wrote a handler for the worksheet changed event. So, the parameter Target has to be there. However, it would be good practice to separate the two current responsibilities of your handler, to decide what kind of thing to do on a worksheet changed event and to copy over the cells. This can be achieved by extracting everything inside the conditional into its own sub, which preferably should not depend on the active sheet. Then my comments above apply to that sub.

One more thing: Your idea to change only the data that changed has a few issues. Whenever you change a value in column B, you have to rewrite everything because rows will potentially drop out or enter one of the two target lists. Moreover, the Target of the worksheet changed event can contain more then one cell. In this case it might actually be faster to simply copy everything instead of figuring out which row to change in the target lists for every cell in Target.

Considering that Target may contain more than one cell, you might also want to consider whether your condition on Target is correct in all circumstances.


You can use an array in a similar way here. Just leave the last one, as it doesn't fit the same pattern.

$.each(
  [
    { poly: 'p1', id: '#apla_p1' },
    { poly: 'p2', id: '#apla_p2' },
    { poly: 'p3', id: '#apla_p3' },
    { poly: 'p4', id: '#apla_p4' },
    { poly: 'a', id: '#apla_p5' },
    { poly: 'b', id: '#apla_p5' }
  ],
  function(o){
    var id = o.id; // copy to closure
    $('#pietra_svg #p1_4 polygon#' + o.poly).click(function() {
      $(id).fadeIn("slow");
      return false;
    });
  }
);

$('.close').click(function() {
  $('.apla').fadeOut("slow");
  return false;
});


Dead code
In this:

    COMMIT TRANSACTION
    select null
END TRY

This line of code: select null does nothing useful (read: nothing at all) and should be deleted. I have no idea why it is there to begin with, but querying for NULL with no criteria will always be null.

Errors not useful
You could improve this error reporting:

    ELSE
        RAISERROR('Required parameters are not provided or Required parameters are passed as NULL',13,1)

TLDR: Don't filter error logs, just store stuff. Developers can filter them easily if they need to.
Why? As it is, this is raising an error with no information on "why" the error was raised. At the very least return the input parameters so the user/dev can decipher what is wrong. This is especially relevant if you are logging those errors somewhere.
You would want to include as much relevant information as possible in your errors, especially if there are multiple instances and databases involved. There are few things which hinder improvement and bug fixes more than half-arsed error logs. Log everything and let the developers sort it out.


I totally agree with Guffa, but I want to add some things: I don't like so long methods, because they are really hard to read, especially for other people which might maintain you code in the future. So I would create some private methods with meaningful names. So everything within the try block, I would change to something like this (pseudocode):

try{
   ExcecuteDelete(parameters, ...)
   ExcecuteInsert(parameters,...)
}

So you have three short instead of one long method.
The query text ("DELETE FROM rh7uiw WHERE bon...") seems to be constant, so I would like to make it a private static constant class variable.

Furthermore, don't use any prefix like my, our and so on, as far as they don't have a special meaning in the context they are used for variable names. Simply call them ifxCommand, command or better: deleteCommand and insertCommand.

By the way, why don't you use a updateCommand? If the affected rows are 0 after a update, you know you have to insert new stuff. But in most cases you have only one database query, instead of always two.


Usage of TPL vs Parallel.ForEach() on file processing

As seen with @t3chb0t and @dfhwze I have been misusing the TPL. I also don't see any point on .ConfigureAwait(false) a Task.WhenAll() call, also with the async all-the-way rule, using an awaitable task for this case would have me to convert many of my APIs to async one.

So they provided me these solutions :

Modifiy my task creation logic this way :  tasks.AddRange(filesPath.Select(async d2PFilePath => await Task.Run(() => UnpackD2PFile(d2PFilePath)))); and removing the Task.Delay(10); on my UnpackD2PFile(string path) task
Use the Parallel.Foreach() loop to let the framework create and handle the concurrency and also allow me to keep a synchronous API

Both of these solutions completed the work in the same time, and provided this output :

As you can see now the behavior is quite different than before, not every task start at the same moment, also now there is a delay before every progress bars shown up. But we gained almost 2sec on the total execution time :)

I highly recommend to use the Parallel approach as it is the easiest one to implement.


Reordering a list from the ends towards the middle

As this algorithm is tail recursive lets tackle another problem: having recursion instead of loops often makes it easier to reason about a single step but more difficult to see whether one step is (partially) undoing effects of the previous one.

Here, the remaining numbers are reversed in every step. This is an O(n) operation (n = length of the list), doing this in every step means the overall complexity is O(n2).

It seems the result could also be computed by

splitting the list into a, b
interleaving a and the reversed b

For splitting in linear time, there is a 'trick': moving two 'pointers' while keeping track of the visited elements (acc). The second pointer (ys) always skips two elements while the first one (xs) skips just one. The function needs to be called with (input, input), i.e. both pointers at the first element:

let rec split acc =
    function
    | x :: xs, _ :: _ :: ys -> split (x :: acc) (xs, ys)
    | x :: xs, [_] -> split (x :: acc) (xs, [])
    | xs, _ -> List.rev acc, xs

Interleaving is straightforward:

let rec interleave acc =
    function
    | h :: t, o -> interleave (h :: acc) (o, t)
    | [], h :: t -> interleave (h :: acc) (t, [])
    | [], [] -> List.rev acc

both functions are of linear complexity, combining them sequentially is O(n) still:

let shuffley' list =
    let rec interleave acc =
        function
        | h :: t, o -> interleave (h :: acc) (o, t)
        | [], h :: t -> interleave (h :: acc) (t, [])
        | [], [] -> List.rev acc

    let rec split acc =
        function
        | x :: xs, _ :: _ :: ys -> split (x :: acc) (xs, ys)
        | x :: xs, [_] -> split (x :: acc) (xs, [])
        | xs, _ -> List.rev acc, xs

    let a, b = split [] (list, list)
    interleave [] (a, List.rev b)

On my machine, shuffley [0..10000] (10k) takes about the same time as shuffley' [0..1000000] (1M) (less than a second), whereas shuffley [0..100000] (100k) doesn't even terminate within a minute.

Note that we can now also shuffley' any list, not just ints (due to the removed type annotations). If you want to pass an empty list in F# interactive, just use shuffley' ([] : int list).

I reversed the accumulator and 'real' parameters to make use of the concise functionality.


Preorder, inorder, postorder for tree in C++11

Memory management

Don't think that is the appropriate smart pointer.

shared_ptr<node> newNode (int i)

Do you have plans to actually share ownership of a node? Or is it more likely that ownership will be done by the patent of the node? I would have gone with unique_ptr<node> if I was going to use smart pointers.

make_X

You should not be using new with smart pointers. There are make_XXX commands that combine all the memory allocation required into a single operation (thus making it more efficient).

   std::shared_ptr<node> n  = std::make_shared<node>(val);  // or make_unique

Using

I suppose this is better than using namespace std;

using std::cout;
using std::endl;
using std::shared_ptr;

But its still pretty sloppy and lazy. Pull those declarations into the tightest scope possible (ie inside a function).

Braces

This looks strange

preOrder((n->left));
preOrder((n->right));

Now I am all for using braces to make expression easy to read or to force a particular evaluation order. But this just looks strange and does not help in the evaluation.

Prefer '\n'

Prefer '\n' to std::endl.

The difference between the two is that std::endl forces a flush after placing the new line on the stream. It is very rare that you actually want to force a flush (as the runtime is much better at making that decision than you). Excessive flushing just makes the stream libraries slow.

“\n” or '\n' or std::endl to std::cout?
Why does endl get used as a synonym for “\n” even though it incurs significant performance penalties?


This is much slower than necessary.  It takes time to construct the array, and more to shorten the array word-by-word.  It's easy to imagine how this would go if words contains a whole book and K is some small number.

In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.

A regular expression is an efficient and compact way to find text that meets your criteria.  Consider:

function crop(message, K) {
    if(K<1) return "";
    const reK = new RegExp( `^.{0,${K-1}}[^ ](?= |$)` );
    return ( message.match(reK) || [ "" ] )[0];
}

.match returns an array with the matched text as the first element, or null if no match.  The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).

The regular expression, broken down, means:

^: match start of string
.: followed by any character
{0,10}: ... up to ten times (one less than K)
[^ ]: followed by a character that is not a space
(?=…): this is an assertion; it means the following expression must match, but is not included in the result:

: followed by a space
|: or
$: end-of-string

Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?


Unit tests for a simple function thats part of a public API

Assuming this function is async, neither. Provide a callback parameter or return a Promise (I'd favour Promises personally). This is a more common / understood pattern in JavaScript.
Unfortunately no there isn't, it's very much part of the downsides (and beauty) of using a loosely-typed language. If you're concerned about type-safety then you should really take a look at TypeScript or equivalents.

With regards to the tests, personally I think covering each error scenario is fine - I do it myself, they're minimal effort and will help catch any regressions.


Finding a key from values (which are list) in dict

Given that you only want the first match, it would be more efficient to stop when you reach it:

output = next(key for key, value in x.items() if n in value)

Note that this will throw a StopIteration exception if there is no matching key, rather than the IndexError your current code throws.

If you need to do this multiple times, you could build a reverse map:

x_reversed = {num: key for key, value in x.items() for num in value}

then the lookup is a trivial x_ reversed[n] However, note the error case changes again, to KeyError.


Python: OOP design for event pricing updates

After a small check, it seems the best solution is to add a condition per type of event, where you adjust accordingly.

Since all events have their effect 'doubled' on the last 7 days, you can use a single if for it

Lastly, you use a single if as well to check if you can update the event, regarding final price

Also I added a list comprehension to avoid looping through 'construction' events, whose value never changes

class EventPricingUpdate(object):
    ORIGINAL_REDUCTION = 10

    def __init__(self, events):
        self.events = events

    def events_to_update(self):
        return [event for event in self.events if event.event_type != 'construction']

    def update(self):
        for event in self.events_to_update():
            reduction = self.ORIGINAL_REDUCTION

            if event.event_type == 'music':
                reduction = reduction * -1

            if event.event_type == 'sports':
                reduction = reduction * 2

            if event.days_from_start < 7:
                reduction = reduction * 2

            # if you use python 2 this if needs a slight change
            if 500 >= event.price - reduction >= 50:
                event.price -= reduction

            event.days_from_start -= 1

        return self.events

# Fill some events
events = [
    Event(event_type='construction', days_from_start=10, price=100),
    Event(event_type='music', days_from_start=10, price=100),
    Event(event_type='sports', days_from_start=10, price=100)
]

EventPricingUpdate(events).update()

# Check update
assert events[0].price == 100
assert events[1].price == 110
assert events[2].price == 80

As you can see, is easy to plug new events, just a new condition on the loop

If you want to go further on the refactoring, you will add the reduction on the list comprehension method


There are a number of ways your code can be improved:

Use nice indentation using 4 spaces. This improves the readability a lot. See the official guidelines on indentation here.

Basically every time you open a new curly brace you should start a new indentation depth. (See code sample below)
Use braces around all kinds of blocks, e.g. here even for one-lined if/else blocks. Also, for Java it is the official convention to place the braces like this:

if (line.equals("")) {
    truefalse = false;
} else {
    System.out.println(line);
}

You can use a trick to assign the value of the scanner input to a variable inside the while condition and then use the String's isEmpty() function to check if the input was empty. This way you can spare the boolean variable indicating whether something was read:

while (!(line = input.nextLine()).isEmpty())

Use try() to create instances of Types that implement java.lang.AutoCloseable to make sure they are automatically closed when the block ends (Note this only works with Java 7 or newer):

try (Scanner input = new Scanner(System.in))

See here for reference.

Putting that all together:

public class Morse {

    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            String line;
            while (!(line = input.nextLine()).isEmpty()) {
                System.out.println(line);
            }
        }
    }
}


I think your code does not exactly what the comment wants. In line:

x |= (y & ~(0 << n)) << p;

0 << n is 0. If you want n rightmost bits of y you may use a mask like (1<<n)-1 (which is n 1 bits).
Now on your code style, when you are coding a bit manipulating task, you'd better do it completely with bitwise operators (at least use other functions very few). Here in this code, using log and pow can be avoided. If you want to get number of bits in an integer type, you can use sizeof, like below:

size_t s = sizeof(int) << 3;

here << 3 is equal to * 8, because each byte definitely has 8 bits (it works on integer types of any size, just replace int with any other type like short or long long).

Now instead of using pow(2, s) you can write 1 << s :)

And about your printing, you can replace s%4 with s&3 (think about it). And I prefer shifting down mask instead of shifting up x (here  it doesn't make any difference, but when you work with signed values it does, because sign will be preserved in left shifts). And for reducing number of lines for printing, you may use for loop.


Securing PHP using a gateway that consults a whitelist

Remove the additional information you are providing in your die statements. Just simply die quietly without revealing any information. It's similar to putting a zero byte index.html file in directories that you don't want people browsing.

Edit: Going away quietly without providing any information gives less information about your site to someone who may be trying to attack it. Any clues that you give them, like file not found for example, lets them know that they need to change their attack vector. The less information you can give them the better.


For large datasets, avoid converting between native Python list and NumPy array objects as much as possible.  Look at the np.loadtxt and np.genfromtxt functions.  They may help you go from saved files of your data to NumPy arrays without having to make any Python lists at all.  But suppose you do have a Python list.  You shouldn't have to convert all of the data to a NumPy array, and then later convert each users's data to an array separately.  I would try something like this, assuming that np.loadtxt doesn't work for you:

data_lengths = [len(Xi) for Xi in X]
num_users = len(X)
max_length = max(data_lengths)
all_data = np.zeros(shape = (num_users, max_length), dtype = 'int')

for row, Xi in enumerate(X):
    row_length = len(Xi)
    all_data[row, 0:row_length] = Xi

From then on, every operation on your data should be an operation on a NumPy array instead of on a Python list.  The way I wrote it, it assumes your data are integers, and also that 0 can never occur as a real data point.  You can modify the dtype and offset of the call to np.zeros accordingly to meet the requirements of your particular data.

This approach will only be good if each user has a number of data points that is not too different from the number for the other users.  Other wise representing your data as a full matrix will be memory inefficient.
Use dtypes.  If your data are non-negative integers, for example, then np.bincount() will be much faster than np.histogram, for example.  Actually, if your data are integers, then you could probably just use collections.Counter() to make your histograms in native Python, which could also save time.


Searching an element in a 2D sorted array

Your function does a linear search over all elements of the nested array, until the given number is found, or all elements have been visited. The complexity is \$ O(mn) \$ for an \$ m \$-by-\$n \$ matrix. For a square \$ n \$-by-\$n \$ matrix that makes \$ O(n^2) \$, and not \$ O(n) \$ as you claimed.

This can be improved, but let's first do a

Review of your current implementation

The Java naming convention for variables is “lower camel case,” e.g. lastRow, lastCol instead of LastRow, LastCol.

The while-loop is a nested loop over all rows and columns in disguise, and can be more clearly written as nested for-loops:

int numRows = a.length;
int numCols = a[0].length;

for (int row = 0; row < numRows; row++) {
    for (int col = 0; col < numCols; col++) {
        if (a[row][col] == x) {
            return true;
        }
    }
}

This also restricts the scope of row and col to the minimum needed.

A better algorithm

Your implementation does not take advantage of the fact that the numbers are sorted in each row and in each column. A better algorithm is described in Search in a row wise and column wise sorted matrix on GeeksForGeeks:

Start with top right element.
Loop: compare this element e with x

if e = x, then return position of e, since we found x in the given matrix.
if e > x then move left to check elements smaller than e (if out of bound of matrix, then break and return false)
if e < x then move below to check elements greater than e (if out of bound of matrix, then break and return false)

repeat until you find the element, or return false

I do not want to deprive you of the satisfaction of implementing it yourself. Just note that any element is now found after at most \$ m+n \$ steps, so the complexity is reduced from \$ O(mn) \$ to \$ O(m+n) \$ for an \$ m \$-by-\$n \$ matrix.


Angular 2 Component conditionally displaying a list of elements from an array

Naming: A better name for the change event handler is toggleShowOnlyMyPolls().
TypeScript is about types: I'm trying not to forget specifying return types of the methods -- this makes it easy to inspect/scan over the signatures, and gives compile time support.
pollsToDisplay can be relatively cheaply calculated on the fly. That will simplify code significantly at the cost of performance (which is not an issue as long as you don't deal with at least several hundred of Poll objects).

Propose:

export class PollListComponent implements OnInit {
    showOnlyMyPolls = false;
    polls: Poll[] = [];

    get pollsToDisplay(): Poll[] {
        if (!this.showOnlyMyPolls)
            return this.polls;

        const loggedInUserId = this.authService.getLoggedInUserId();
        return this.polls.filter(poll => poll.userId === loggedInUserId);
    };

    constructor(private pollService: PollService, private authService: AuthService) { }

    ngOnInit(): void {
        this.pollService
            .getPolls()
            .subscribe((polls: Poll[]) => this.polls = polls);
    }

    toggleShowOnlyMyPolls(): void {
        this.showOnlyMyPolls = !this.showOnlyMyPolls;
    }

    isLoggedIn(): boolean {
        return this.authService.isLoggedIn();
    }
}

How is this code simpler?

pollsToDisplay used to be a field that is assigned in three different places: one in subscribe(...) and two in displayMyPolls(). Each of these places could have a bug, and this code was scattered. Now it's calculated on the fly:

no assignments at all;
everything happens in one place -- if there is a bug with poll list construction, you know where to look for it, easier to unit-test, etc.;
and there is no unnecessary field since get pollsToDisplay() is an accessor.

toggleShowOnlyMyPolls() became trivial, it really does only what it is responsible for, which is mode switching.


You can avoid building a list of results to print them after, you can just print them as you calculate them.

Also you assign a lot of variables and:

binNum=binary[2:]

is not explicit in removing the '0b' that Python prefixes, better is

.replace('0b','')

Also the padding with 0 logic that you write is already implemented in the zfill function, so you can avoid re-writing it yourself.

Finally, you should write a function to read the input to separate concerns and maybe reuse it in a similar problem.

Here are all my suggestions implemented.

def read_numbers(n):
    return [int(input()) for _ in range(n)]

for i in read_numbers( int(input()) ):
    binary_padded = bin(i).replace('0b','').zfill(32)
    print( int( binary_padded[::-1], 2) )


Autocompleting when a certain class is present

I'm proposing to reduce code by putting all similar code to one function:

function initAutocomplete(selector, field) {
  $(selector).on('keydown', function() {
    $(this).autocomplete({
      source: '<?php echo base_url();?>description/get_description',
      minLength: 1,
      select: function(evt, ui) {
        this.form.elements[field].value = ui.item.sub_description;
      }
    });
  });
}

initAutocomplete('.sn', 'sub_description');
initAutocomplete('.sn2', 'sub_description2');


Find all pairs in an array that sum to a given number

No comments on the time complexity, I do have a bunch of other comments:

Code to interfaces, not implementations

It's better to use Set<Integer> allElements = new HashSet<Integer>() (side note: guess you're not on >= Java 7, since you can use diamond operators otherwise) so that users of allElements do not need to know that it actually is a HashSet. This is just good practice. The lesson here is that it allows the programmer to replace the implementation with another in the future when required.

Does not contain, then add to a Set

In the following code block:

if (!original.contains(toAdd) && !original.contains(reversePair(toAdd))) {
  original.add(toAdd);
}

I think the extra check !contains() is not really required because Set.add()'s Javadoc says:

  If this set already contains the element, the call leaves the set unchanged and returns false.

So, even if original did contain toAdd, calling add() will leave the set unchanged anyways. I guess this is useful when you're running on a large set of inputs so that there is some short-circuiting done, hence this is strictly just 'food-for-thought' and not something to frown upon.

hashCode()

I'm guess there's an implied range of inputs such as all must be positive right? Because your calculation (element1 + element2) * element2 + element1 will yield the same hash codes when element1 + element2 equals to 1, and having a bunch of negative and positive integers (or just 0, 1) will 'break' this easily. You may want to update your question with any assumptions on the range of inputs.

How to reverse a Pair

I think that you can move your method reversePair(Pair) into the Pair class itself as such:

public final class Pair { // also declared as final

    private final int element1; // also declared as final
    private final int element2; // also declared as final

    public Pair(int element1, int element2) {
        this.element1 = element1;
        this.element2 = element2;
    }
    ...

    public Pair getReverse() {
        return new Pair(element2, element1);
    }
}

Using it then becomes slightly easier:

if (!original.contains(toAdd.getReverse())) {
  original.add(toAdd);
}

Override toString()

Oh yeah, given how you want to print the contents of Pair objects in the end, why not just override toString() too? :)


I'm a bit hesitant to comment on anything related to concurrency, but I'll give it a try:

Why does Dispose wait for runTask to finish? To me, that's a rather surprising side-effect. I'd expect Dispose to stop the timer, and to abort the current invocation if possible, but not to block.
Letting a callback dispose the CompletionTimer that's running it sounds like a bad idea - it seems like an inverted ownership situation.
The deadlock seems fairly straightforward: RunInternal invokes callback asynchronously, so the rest of the code is registered as a continuation and will be run when callback finishes. However, callback disposes the CompletionTimer, which waits for runTask (RunInternal) to finish. The callback and the run task are now both waiting for each other to finish.
If you want the callback to be able to stop the timer, perhaps changing its return type to Task<bool> is a better idea: the timer can then terminate its loop after the callback returns false.
The requiresAtLeastOne construction looks a little confusing, with it being compared against a few 'magic values'. A requiredInvocationsLeft field that is decremented after each invocation seems a little easier to grasp - and would also allow you to configure the number of required invocations after a wake-up.
Perhaps SkipCurrentDelay is a more descriptive name than WakeUp. WakeUp could be interpreted as the timer being in sleep mode (as in, it's paused, it's not periodically invoking its callback).
You may want to document the intended behavior of your class. As my comments may show, other people likely have different assumptions about how a timer will behave.

Creating a separate StopAndWaitForCompletionAsync method is probably a better idea if you need to wait for the last invocation to finish.


Copying sections of one picture to another

The second one is more efficient. Simply because in the first one you are calculating the if w * h times but in the second you are calculating it h times.

Also it can be made more readable and efficient just by using this. It eliminates leaf which you aren't using anywhere. Readability doesn't need explaining.

for y in range(0,h):
  if (20 > y >= 0) or (60 > y >= 40)or (100 >= y >= 80):
    for x in range(width):
      sourcePx = getPixel(pic1, x, y)
      targetPx = getPixel(pic2, x, y)
      setColor(targetPx, getColor(sourcePx))
  repaint(pic2)

Update 1

As limelights has suggested, use of xrange is better than use of range in Python2. If your h or w are big then using range would return a list which occupies memory while use of xrange returns a generator which is much more memory efficient. Performance might suffer a bit but in most cases it is worth it.


PHP class design with methods requiring database access

OOP is definitely the way to go. The best advise I can offer is to read the book "Clean Code" by Uncle Bob. The code there is in Java but all principles apply equally to any other language.

I would definitely abstract the DB interface so I can use for any other database, even if you don't plan it in the next future. I have posted small data store architecture code that may help you.

From a look at your code, I am a bit confused by the naming connect and connection and the latter stores $connect in the constructor. Maybe give a more descriptive names (one of the top recommendations in the mentioned book).

Why are you unsetting $connect?
The names such as $LNK_ID are cryptic for reader.
I would reserve a separate class dealing with the database via thin interface (see my post) and let other classes only talk to that class instead of DB directly.


If you provide a destructor you should handle copying and assigning. In other words follow the Rule of 3 (or 5 if you care about move semantics). You can also disallow them but then there should be move constructor and assignment.

Otherwise you will get in trouble with double freeing when calling a function void foo(Stack<int> s).

empty() doesn't change the stack. So it should also be const.

Consider adding a peek() method that returns a reference to the top value of the stack (with const and non-const version).

T& peek()
{
    return topNode->data;
}

const T& peek() const
{
    return topNode->data;
}

The reason for using the reference is to avoid a unnecessary copy.

Having a print method interacting with the console is not a good idea. What if you want to show the contents in a gui instead?

Instead add iterators to be able to inspect what is on the stack without having to capture the output that print() generates.


Disclaimer : this is not quite an answer but more than a comment.

You've written tests and I'd like to start by thanking your for this. This definitly makes reviewing easier.

Good think to know if that you can make easily double the amount of test you have without thinking too much.

Indeed, it seems like by inversing the parameters of your function, the return value should be the opposite value.

You can write this :

for d1, d2, res in [
        ([1, 1, 2], [1, 1],  3),
        ([1, 2, 4, 5], [3, 4],  2),
        ([1, 2, 4, 5], [3, 5],  2),
        ([1, 2, 4, 5], [3, 6],  -1),
        ([20, 12, 20, 14], [17, 15, 20, 5, 18, 2],  2),
        ([20, 10, 2, 4], [ 5, 20, 6, 4, 19, 3],  -2)
    ]:
    assert check_rolls(d1, d2) == res
    assert check_rolls(d2, d1) == - res

Also, I thought I'd take this chance to test check_rolls(d1, d1) and it seems like it always returns - len(d1). Shouldn't you handle perfect tie situation in a different way ?

Edit : still not quite a review but you got me interested and I wondered if this could be written in a more simple way. Here's what I got translating my understanding of the problem into Python code :

def check_rolls(d1, d2):
    c1, c2 = Counter(d1), Counter(d2)
    res = 0 # nb points
    winner = 0 # player winning so far : 1 if 1, 2 if 2, 0 otherwise
    for key in reversed(sorted(set(c1) | set(c2))):
        v1, v2 = c1[key], c2[key]
        if v1 == v2:
            res+= v1 # ties count for whoever is winning
        else:
            local_winner = 1 if v1 > v2 else 2
            if winner and local_winner != winner:
                break
            else:
                winner = local_winner
                res+= max(v1, v2)
    return res if winner == 1 else -res


Yes, this can easily be achieved with a few non-redundant lines.

You can hook up all button clicks to this common MouseDown event:

private void toolStripButton_MouseDown(object sender, MouseEventArgs e)
{
    ToolStripButton button = sender as ToolStripButton;
    if (button == null) throw new InvalidCastException();
    foreach (ToolStripItem item in button.Owner.Items)
    {
        if (item is ToolStripButton)
        {
            ((ToolStripButton)item).Checked = (item == button);
        }
    }
}

Note that the Click event doesn't allow you to find out which button was clicked as all button clicks map to the ToolStrip itself! Therefore it doesn't lend itself to any sort of common processing that makes use of the sender paramter all events have..

As ever so often MouseDown works much better ;-)

The logic above assumes you want a radiobutton-like behaviour. RadioButtons can only be switched on; to switch them off you need to click another RadioButton in the group. If you want to be able to switch a button on and off directly you can expand it a little..


PEP-8 issue: Function names should be lowercase_with_underscores.


Querying MySQL from an external application

The most important thing here is not to create and destroy the connection as part of executing your query.  Force the calling code to create the connection first (or create it yourself if its not done) but dont destroy the connection until the library is unloaded.  That should improve speed.


You'll have to do something like (this will work for Moq, change the api usage to match your Mocking framework).

_controller.Setup(p=>p.ServerNameOrIP).Returns("testServerName");

before you call your assert statement.


Firstly, you should add a class to the a element instead, since that's what all the other elements are contained in.

That way, you don't have to add/remove classes on all the child elements separately. You can just add/remove 1 class, and set up your CSS to style the child elements accordingly.

You also decouple your JS from the HTML to greater extent; now you can control things in just the CSS instead of having the HTML, the CSS, and the JS all concern themselves with the exact structure of your page.

Given your current code, however, I would suggest something like this:

jQuery(function($) { // shortcut for $(document).ready(...)
  function showPost() {
    var a = $(this).closest("a"); // get this once, use it thrice
    a.find('img.postimg').addClass('imggrow');
    a.find('h1').addClass('bannerhover');
    a.find('p.excerpt').delay(500).addClass('phover'); // note the delay() call
  }

  function hidePost() {
    var a = $(this).closest("a"); // same as above
    a.find('img.postimg').removeClass('imggrow');
    a.find('h1').removeClass('bannerhover');
    a.find('p.excerpt').removeClass('phover');
  }

  if ($(window).width() > 1000) {
    // No need to use hide/show with a timeout of zero, as far as I can tell.
    // Just pass the two functions directly
    $('div.post').hover(showPost, hidePost);
  }
});


Java - Something similar to Abstract Factory?

A few points about your resolver.

Since you're using an enum to specify the repository's Type and resolve the tools depending on that type, an EnumMap seems to be the simplest solution to resolving the specific tool implementation necessary.

Also caching objects that have virtually no creation cost seems overkill to me. You can just eagerly initialize the objects and then don't even have to care about multithreading problems:

class Resolver {

    private static final Map<Repository.Type, AbstractRepositoryTools> cache =
        new EnumMap<>(Repository.Type.class);

    static {
        cache.put(GITHUB, new GitTools());
        cache.put(FILE, new LocalFileTools());
        cache.put(FOLDER, new LocalFolderTools());
        cache.put(BITBUCKET, new BitbucketTools());
    }

    public static AbstractRepositoryTools getToolsFor(Repository repo) {
        if (cache.containsKey(repo.getType()) {
           return cache.get(repo.getType());
        }
        throw new NotImplementedException("Repository.TYPE = " + repo.getType());
    }
}

Additionally I wouldn't call the class AbstractRepositoryTools, but just RepositoryTools.

You can simplify the resolver call by only giving it the type of the repo (since that's the only thing necessary). Furthermore I would extract the doDownloadZip into a separate interface and then seal the RepositoryTools class by declaring it final

Other than that your code is very clear and simple. I assume the javadoc comments are only explanatory notes for reviewers, and that you excluded the actual javadoc.

And since you asked about the name of the pattern... This is a Facade


One case that you missed is replication in the search string.

>>> '1213' in StringClass('121213')
False
>>> '1213' in '121213'
True

This is because your class is already past the second one before it sees a difference and has to start completely over.

Asides from that, the empty string and None cases are problems, as is mentioned in other answers.


If your list is sorted you can use binary search (your second code), and it will be faster for large lists, but if it's unsorted you'll have to keep to linear search. The Python library provides fast implementation of both methods, so you really don't need to roll your own:

>>> a = range(10)

>>> a.index(4) # linear search
4

>>> import bisect
>>> idx = bisect.bisect(a, 4) # binary search
>>> if a[idx-1] == 4:
...     print idx - 1
... else:
...     raise ValueError('item not in list')
...
4


It is usually better to ask forgiveness than permission and explicit is better than implicit. So I would change your getattr..if hasattr to a try..except, which is a lot easier to understand:

def post(self, request, slug):
    try:
        return self.store(request)
    except AttributeError:
        raise HttpResponseForbidden("Method not allowed")

And similar for get and view:

def get(self, request, slug):
    try:
        if slug is not None:
            return self.show(request, slug)
        return self.index(request)
    except AttributeError:
        raise HttpResponseForbidden("Method not allowed")

def view(self, request, slug=None):
    try:
        return getattr(self, request.method.lower())(request, slug)
    except AttributeError:
        raise HttpResponseForbidden("Method not allowed")