Project Euler Problem 11 ("Largest product in a grid") in Python

If you restricted your lines to 79 columns, as recommended by the Python style guide (PEP8), then we wouldn't have to scroll the code horizontally to read it here.

Anyway, all four loops have the same form:

max(grid[i][j]
    * grid[i+i_step][j+j_step]
    * grid[i+2*i_step][j+2*j_step]
    * grid[i+3*i_step][j+3*j_step]
    for i in range(i_min, i_limit)
    for j in range(j_limit))

given particular choices of parameters i_step, j_step, i_min, i_limit and j_limit. So we can implement the program as a data-driven loop over those choice of parameters:

print(max(max(grid[i][j]
              * grid[i+i_step][j+j_step]
              * grid[i+2*i_step][j+2*j_step]
              * grid[i+3*i_step][j+3*j_step]
              for i in range(i_min, i_limit)
              for j in range(j_limit)))
          for i_step, j_step, i_min, i_limit, j_limit
          in [( 0, 1, 0, 20, 17),  # horizontal
              ( 1, 0, 0, 17, 20),  # vertical
              ( 1, 1, 0, 17, 17),  # leading diagonal
              (-1, 1, 3, 20, 17)]) # trailing diagonal

If you want to avoid writing out the multiplication, then the best approach would be to define a helper function, for example using functools.reduce and operator.mul:

from functools import reduce
from operator import mul

def product(iterable):
    """Return the product of the numbers in the iterable."""
    return reduce(mul, iterable, 1)

and then:

print(max(max(product(grid[i+k*i_step][j+k*j_step] for k in range(4))
              for i in range(i_min, i_limit)
              for j in range(j_limit)))
          for i_step, j_step, i_min, i_limit, j_limit
          in [( 0, 1, 0, 20, 17),  # horizontal
              ( 1, 0, 0, 17, 20),  # vertical
              ( 1, 1, 0, 17, 17),  # leading diagonal
              (-1, 1, 3, 20, 17)]) # trailing diagonal


Bubble sort a list of integers for a number of iterations

Three improvements:

Use the for loop idiom instead of a counter and use _ for variables you don't use.
return the result, don't print it, you should separate processing and output.
Use nums, not num because you should sort multiple numbers, a plural is a more sensible choice.

def bubsort(nums, iters):
    for _ in xrange(iters):
        nums = sorting(nums)
    return nums


Implementation of Dijkstra's algorithm in Python

[x for x in range(1, 1001)] can be written as just list(range(1, 1001)).
It would be good to give that 1001 a name too.

Similarly, [0 for x in RANGE_ARR] can be written as [0] * len(RANGE_ARR). Multiplying any sequence type by an integer repeats the elements within the sequence. As a bonus, from some quick benchmarking that I just did, it's also more than 10x faster:
from timeit import timeit

N = int(1e6)
TRIALS = int(1e3)

print(timeit(lambda: [0] * N, number=TRIALS), "seconds")

print(timeit(lambda: [0 for x in range(N)], number=TRIALS), "seconds")

2.9889957 seconds
38.1463017 seconds

Be aware though that you should not use this when the element type is mutable (like [[0]] * 5). Multiplying a sequence creates multiple references to the same object; it doesn't make copies.

It looks like Q should be a set. You don't care about order, and the only thing you use it for is to track membership of a set. Sets will be significantly faster here. The only two changes needed are:
Q = set()

. . .

Q.add((i, j))

The only change I can see this making is dijkstra_get_min technically does rely on the order of Q. If two elements with the same minimum values are in Q, your algorithm picks the last instance. Since sets may use a different order, this may change what vertex gets returned.

It looks like MAX_DISTANCE is meant to be some arbitrarily large number that everything else will be less than. You may want to try using np.inf for that. By hardcoding the upper limit, you risk the problem "growing" later and potentially exceeding that max; causing erroneous behavior.


ACCESS_ERROR_CODE is errno.EACCES.

BYTES_IN_GIGABYTE is clearer as 2**30. That's transparent enough that the constant and convert_bytes_to_gigabytes aren't needed, so I'd just write folder[1] / 2**30.

GIGABYTE_DISPLAY_LIMIT sounds like an upper limit to display. How about GIGABYTE_DISPLAY_THRESHOLD instead?

To reduce the opportunity for unit confusion, I'd keep the size and the threshold in bytes, and only convert to GB when printing.

You may want folder_sizes.sort(reverse=True) to get the largest ones first.

get_all_folder_sizes recurses over directories twice: once in os.walk and once in get_folder_size. This takes time quadratic in the tree depth, so it may be slow. Can you do the recursion just once, by returning a generator of (size, path) pairs, and recursing on subdirectories?

You can avoid the two try blocks by getting directory size in the same place as file size. (Then you don't even need isfile.)

The continue in the inner exception handler is redundant.


After getting user input, you check it by doing decision == "Yes". This is pretty exact text to expect from the user. I'd at least upper-case their input, and unless you really needed them to be specific, only keep the first letter:

decision = input("You guessed wrong, do you want to continue? Yes or No ")
std_decision = decision[:1].upper()  # [:1] discards all but the first letter

if std_decision == "Y":
   . . .

In coin_flip_game you have

guess_count = 1  #guesses set to 1 so that program considers 1st guess

Then later:

if user_input != random_flip():
    guess_count += 1
    guesses.append(user_input)
    first_try = False
else:
    winner = True

You're only increasing guess_count if the guess was wrong. Regardless of if they were right or wrong though, they still made a guess. I think it makes more sense to add to the guess_count regardless, and start it at 0.

But then you're also only adding to guesses on wrong answers too. If you change it to append to guesses on both right and wrong answers, you'll have this:

guess_count = 0

. . .

guess_count += 1
guesses.append(user_input)

if user_input != random_flip():
    first_try = False

else:
    winner = True

Notice now though that guess_count will always be equal to the length of guesses, so it isn't needed. If you need to find out how many guesses were made, you can just do len(guesses). first_try also isn't necessary. To check if it was their first guess or not, you can do:

if len(guesses) == 0:
    . . .

Or, more idiomatically:

if not guesses:  # "If no(t) guesses (have been made)"
    . . .

I think that whole game loop part should be taken out into it's own function though; beyond what you've already done. I'd have a function that returns a list of guesses made until a correct guess was made. With how you have it set up now, I'm going to disregard cancelling since that will require some broader changes to accommodate, and it's highly unlikely that the user will have to guess more than a few times.

def guess_loop() -> List[str]:
    guesses = []

    while True:  # We're just going to return, so we don't need a condition
        user_input = user_choice()
        guesses.append(user_input)

        if user_input == random_flip():
            return guesses  # Returning guesses means we won

        else:
            print("You guessed wrong. Try again.")

def coin_flip_game():
    print("Lets start! Begin by choosing:")
    guesses = guess_loop()

    if len(guesses) == 1:
        print("Congratulations, you guessed correctly on your first try!")

    else:
        print("Congratulations! After", len(guesses), "you guessed correctly!")
        print("Your guesses were: ", guesses)

The bulky bit was taken out so it can be dealt with as an isolated bit of code. To know the outcome of the game, all I care about (besides cancelling, which could be handled by returning None) is the list of guesses they made until they won. I can get all the information I need from just that. Needing to mix in winner, and cancel flags can suggest that that code should be moved out. By the time you're managing two or three flags to control execution in one block of code, it can become hard to follow.

user_choice can be cleaned up too. Again, you're using a condition to control a loop when I think returning directly from the loop leads to cleaner looking code:

def user_choice():
    while True:
        user_input = input("Heads or Tails?").capitalize()  # Capitalize to give the user some leeway

        if user_input in {"Heads", "Tails"}:
            return user_input

        else:
            print("Invalid input.")

After the above and some small formatting touchups, I'm left with:

import random
from typing import List

def random_flip() -> str:
    return random.choice(["Heads", "Tails"])

def user_choice() -> str:
    while True:
        user_input = input("Heads or Tails?").capitalize()  # Capitalize to give the user some leeway

        if user_input in {"Heads", "Tails"}:
            return user_input

        else:
            print("Invalid input.")

def guess_loop() -> List[str]:
    guesses = []

    while True:  # We're just going to return, so we don't need a condition
        user_input = user_choice()
        guesses.append(user_input)

        if user_input == random_flip():
            return guesses  # Returning guesses means we won

        else:
            print("You guessed wrong. Try again.")

def coin_flip_game() -> None:
    print("Lets start! Begin by choosing:")
    guesses = guess_loop()

    if len(guesses) == 1:
        print("Congratulations, you guessed correctly on your first try!")

    else:
        print("Congratulations! After", len(guesses), "you guessed correctly!")
        print("Your guesses were: ", guesses)

coin_flip_game()

The -> bits are type hints for the return type of the function. I think they're handy to have to make it clearer what type of data is being dealt with.


Fluent interface and polymorphism for building a scene with shapes

Another thing to consider in your current design:

~Scene() { for (auto & f : v) delete f; }

You are calling the destructor of the base here, not the derived classes' destructors. Remember to make a virtual destructor in your class to solve this problem.


Your constructor is nigh-identical to this up-voted answer for splitting a string.

The rest of the class doesn't add much value: IMO the vector provides the same API as your class and more besides; so a user might prefer to have the vector than to have your StringTokenizer instance which wraps/encapsulates/hides the vector.

vector.at returns a const reference, instead of returning by value: perhaps your methods should too.


Your constructHeap method works in O(n), and you call in O(n) times from removeMax method, so your code works in O(n^2), so it is not a correct implementation of Heapsort.

Comments:

public static void heapSort(int[] inputArray) {

Why do you need another array? Heapsort is in-place.

  /* Creates an array A which will contain the heap */

Why do you need 1-based indexing? You don't seem to use it anywhere, and 0-based is more convenient.

  /* A has size n+1 to allow 1-based indexing */
  int n = inputArray.length;

  int[] A = new int[n + 1];

You don't use this variable.

  int temp = 0;

  /* Copies the array inputArray into A, with inputArray[i] being stored in A[i+1] */

You should replace this loop with System.arraycopy(...) call

  for (int i = 0; i < n; i++) {
    A[i + 1] = inputArray[i];
  }
  constructHeap(A, n, 1);
  removeMax(A, n);
  copyBack(A, inputArray);
}

Consider transforming such comments into valid javadoc.

/* Transforms A into a max-heap using a 'bottom-up' algorithm. */
public static void constructHeap(int[] A, int n, int i) {
  if (2 * i > n) {
    return;
  }
  constructHeap(A, n, 2 * i);
  constructHeap(A, n, 2 * i + 1);
  bubbleDown(A, n, i);
}

Comment?

public static void bubbleDown(int[] A, int n, int i) {
  if (2 * i > n) {
    return;
  }
  int leftChild = 2 * i;
  int rightChild = 2 * i + 1;
  int max = leftChild;
  if (rightChild <= n && A[max] < A[rightChild]) {
    max = rightChild;
  }
  if (A[i] < A[max]) {
    int temp = A[i];
    A[i] = A[max];
    A[max] = temp;
    bubbleDown(A, n, max);
  }
}

  /* Performs a sequence of n 'remove-maximum' operations, storing the removed element at
     each step in successively smaller indices of A */

public static void removeMax(int[] A, int i) {
  if (i == 0) {
    return;
  }
  int temp = A[1];
  A[1] = A[i];
  constructHeap(A, i, 1);
  A[i] = temp;

So you make O(n) recursive calls? This is causing StackOverflowException with large n and harming your running time. Consider transforming this tail recursion into a loop.

  removeMax(A, i - 1);
}

  /* Copies the sorted values in A back into inputArray, with inputArray[i] getting
     the value from A[i+1] */

public static void copyBack(int[] A, int[] inputArray) {

ditto

  for (int i = 0; i < inputArray.length; i++) {
    inputArray[i] = A[i + 1];
  }
}


Node.JS module to retrieve configuration from environment variables

Disclaimer: since I'm not familiar with export/import realm, my suggestion below might be too naive and not work. If so, rather than only downvoting, thanks in advance for a little comment pointing me to a resource which would enlight how and why I'm wrong.

That's said, with merely my pure JS skills, here is how I'd work:

var keys = [
  'SAMPLE_SECRET',
  'SAMPLE_SECRET_MORE'
];
keys.forEach(function(keyName) {
  Object.defineProperty(module.exports, keyName, {
      get: function() {
          if (!process.env[keyName]) {
              console.error(
                "ExternalVars error! Could not load a value for: " + keyName
              );
              process.exit(1);
          } else {
              return process.env[keyName];
          }
      }
  });
});


AJAX call with repetitive success/failure handlers

Here's a shot at it. I don't have a demo environment to test with, so let me know if I had any typos etc. I also wrapped it in a self-executing function to keep things from being in the global scope. If you already have it scoped then the self-executing function is unnecessary.

I pulled out the duplicated code into a function so the code is no longer duplicated. This helps with maintainability and shrinks the file size.

(function() {
    function doWork(event, response) {
        $('#project-wrapper').addClass('activated');

        // Keep the rest of the projects grey while #project-wrapper is activated
        $('article').addClass('grayscale grayscale-fade').css('opacity', '0.4');

        // Load up the response from the Ajax call
        $('#project-container').html(response);

        // Make the max-height of the container exact for smoother animations
        var containerHeight = $('#project-container').outerHeight();
        $('#project-wrapper.activated').css('max-height', containerHeight);

        // CSS effects
        $('.post-container').addClass('fadeInUp');
        $('.close-button').addClass('fadeInDown');

        // Remove pesky, sticky 'hover' class
        $('article').removeClass('hover');

        // Shuffle letters and update the title of the page
        $('#project-wrapper').find('.entry-title').shuffleLetters({
            callback: function(){
                var title = $(event.currentTarget).closest('#main').find('h1').text();
                $('head').find('title').text('Keebs | ' + title);
            }
        });
    }

    // Activate projects
    $('.post-link').click(function(e) {
        e.preventDefault();

        var post_id = $(this).attr('rel'),
            ajaxURL = site.ajaxurl; // Ajax URL localized from functions.php

        // Initiate the Ajax call
        $.ajax({
            type: 'POST',
            url: ajaxURL,
            data: {'action': 'load-content', post_id: post_id },
            beforeSend: function() {
                $('').insertBefore($(e.currentTarget));
            },
            success: function(response) {
                $('.loading-icon').remove();

                if ($(window).scrollTop() != 0) {
                    $('html, body').animate({
                        scrollTop : 0
                    }, 200, function() {
                        doWork(e, response);
                    });
                } else {
                    doWork(e, response);
                }

                return false;
            }
        });
    });
})();


PHP class which preserves line break by splitting the line into as many line break as it have

After about 10 minutes of reading your code and testing it out, I think I figured out what your class is supposed to, which is not a good sign for such a small class.

To me it seems that the goal of your class is to strip all the tags from a string containing HTML code, without losing the
 tags, by replacing these tags with newlines. However, when running your code I did not see this behaviour at all.

I ran your code using the default $pattern parameter and the following HTML as input:

"Hello
World!

How are you doing?

Great!
"

and the result (using var_dump()) from your getPreservedContent() method was:

array(1) { [0]=> string(35) "HelloWorld!How are you doing?Great!" }

Which I am not sure what to do with. Why is it in an array? Where are the newlines? They do not seem to be preserved at all!

I am assuming that the desired result for this HTML string would be:

string(67) "Hello
World!
How are you doing?

Great!
"

Based on my observations of the incorrect functionality of your class, design flaws and untidiness I will propose a redesign of your class and explain why I made the changes that I made.

Redesign

First of all, your class seems to be implemented specifically for the use of keeping HTML line breaks. This means that you have two choices here. Either choose to create a class for a more general use case, or make your class very specific to the HTML domain. I would chose for the latter here.

The name of your class does not describe what the intent of your class is. It only states that it preserves line breaks, not that is also strips the HTML tags from the string. I would suggest a name like:

class HtmlTagStripper { ... }

Which arguably might not be a very good name either, but I think it is a step up from where we were, as it clearly states the intent of the class.

This class could then have two public functions, one for regular stripping of tags and one for stripping the tags whilst preserving the newlines.

public function strip($html_text) { ... }

public function stripWithPreservedLineBreaks($html_text) { ... }

As you can see, I have chosen to require the user to pass the HTML text into the function instead of into the constructor of the class. This makes the class stateless and allows for reuse of the class without having to create a new instance.

Furthermore, we do not want the user to be able to pass in a pattern to the constructor either, since this class only works with HTML and therefore only works with
 tags. Combining these two adjustments, we no longer need to specify a constructor at all!

To match the
 tags, we need a regular expression, which you already presented in your code via the $pattern parameter. I will implement this regular expression as a constant on the class. The tricky part is that
 tags can be written in any of the following ways:
,
,
,
,
 and many more slight variations. So we need to make the regular expression a bit more robust.

I found such a regex in this StackOverflow question. Implementing this regex as a constant would look like this:

class HtmlTagStripper {
    const BR_TAG_REGEX = '/
]+)*[\/]?>/gi';

    ...
}

Now that we have this out of the way, lets start with the implementation of the regular strip() function.

public function strip($html_text) {
    return strip_tags($html_text);
}

Now lets implement the stripWithPreservedLineBreaks() function.

public function stripWithPreservedLineBreaks($html_text) {
    $html_text = $this->convertLineBreakTagsToNewlines($html_text);

    return $this->strip($html_text);
}

private function convertLineBreakTagsToNewlines($html_text) {
    return preg_replace(self::BR_TAG_REGEX, PHP_EOL, $html_text);
}

There are two things to take note of here. First, we have delegated the responsibility of replacing the
 tags with newlines to a separate function with a very clear name, to improve readability. It is important to specify that this method is private and cannot be used outside of your class, as it encapsulates the internal workings of the class. Second, we delegate the actual stripping of the tags to the basic strip() function that we wrote earlier.

The class as a whole now looks like this:

class HtmlTagStripper {
    const BR_TAG_REGEX = '/
]+)*[\/]?>/gi';

    public function stripWithPreservedLineBreaks($html_text) {
        $html_text = $this->convertLineBreakTagsToNewlines($html_text);

        return $this->strip($html_text);
    }

    private function convertLineBreakTagsToNewlines($html_text) {
        return preg_replace(self::BR_TAG_REGEX, PHP_EOL, $html_text);
    }

    public function strip($html_text) {
        return strip_tags($html_text);
    }
}

What to take away from this

You did not specify any visibility modifiers for your functions. Always make clear which functions are meant to be exposed (public) and which are internal (private/protected).
Naming is extremely important in code readability. Name your classes, methods, variables and parameters appropriately.
Always test your code!

Testing

Something I haven't touched on in this review is testing. You should always test your code to ensure/prove that it works the way you intended. Use a unit testing library such as phpunit to test many different inputs to your functions and verify that they are correct.

An example test:

class HtmlTagStripperTest {
    public function testSimpleBrTagIsReplacedWithNewline() {
        $html_tag_stripper = new HtmlTagStripper();
        $stripped_html = $html_tag_stripper->stripWithPreservedLineBreaks("
");
        $this->assertEquals(PHP_EOL, $stripped_html);
    }

    public function testComplexBrTagIsReplacedWithNewline() {
        $html_tag_stripper = new HtmlTagStripper();
        $stripped_html = $html_tag_stripper->stripWithPreservedLineBreaks("
");
        $this->assertEquals(PHP_EOL, $stripped_html);
    }
}

These two tests verify that different variations of the
 tag are both replaced with a newline character. Of course you will need to test many more variations as well as test bigger HTML strings and so on.


Find all file occurences of a search term on drive

I really like this code. Let me explain why in a few short sentences:

Typechoice:

You return an IEnumerable and not a List. This is awesome, because a List implies sorted entries and blocks some Types, that you can use with IEnumerable

Naming:

Your names are short, comprehensive and follow the naming conventions. There's not much more to say.

Program flow:

It is instantly obvious to the reader, what your program does and how it does that, simply by speaking english. This is very hard to accomplish, and I want to compliment you on that.

Choice of methods:

You explained very nicely why you chose EnumerateFiles() over GetFiles(). If you'd comment that, IMO your code would be perfect.


Since you're using some ES6+ features, I'd definitely recommend looking into others, such as let, arrow functions, and so on. This website is a good start, and you can find more information by searching "javascript es6".
Adding onto the last point, whenever you don't change a variable, prefer using const for consistency's sake. If you do need to change a variable, use let. Note that you can change properties on objects declared with const, but you still can't reassign the variable. You can look up more details on the website I linked.
The result function can be improved.

First off, it doesn't look like the return value is being used at all, so there's no need to return anything from it.

Secondly, if an element is referenced multiple times from jQuery, it's usually a good idea to cache it in a variable, so jQuery doesn't have to unnecessarily query the DOM multiple times. In small cases like this the performance difference doesn't matter much, but it's still a decent habit to pick up.

Here's what you'd end up with for the result function, as an example:

const result = (a, b) => {
  const $newAge = $(".newAge")
  const $retireYear = $(".retireYear")

  $(".currentYear").text(currentYear)
  if (b > a) {
    $newAge.text(b - a)
    $retireYear.text(currentYear + (b - a))
    message1.dialog("open")
  } else {
    $newAge.text(a - b)
    $retireYear.text(currentYear - (a - b))
    message2.dialog("open")
  }
}


Groupby count, then sum and get the percentage

I think your code is already nearly optimal and Pythonic. But there is some little things to improve:

cluster_count.sum() returns you a Series object so if you are working with it outside the Pandas, it is better to specify the column: cluster_count.char.sum(). This way you will get an ordinary Python integer.
Pandas has an ability to manipulate with columns directly so instead of apply function usage you can just write arithmetical operations with column itself: cluster_count.char = cluster_count.char * 100 / cluster_sum (note that this line of code is in-place work).

Here is the final code:

df = pd.DataFrame({'char':['a','b','c','d','e'], 'cluster':[1,1,2,2,2]})
cluster_count=df.groupby('cluster').count()
cluster_sum=sum(cluster_count.char)
cluster_count.char = cluster_count.char * 100 / cluster_sum

Edit 1: You can do the magic even without cluster_sum variable, just in one line of code:

cluster_count.char = cluster_count.char * 100 / cluster_count.char.sum()

But I am not sure about its perfomance (it can probably recalculate the sum for each group).


I'm not sure about your first question - I've never programmed on a mobile device where power was an issue.

In answer to your second question, one of the options for sockets that is contained in the specification for TCP/IP is SO_KEEPALIVE. When this is set to true, the internal socket mechanism takes care of keeping the connection alive so that you don't have to worry about heart beats or anything like that. The Socket class has accessors for SO_KEEPALIVE.

Also, you need to seriously refactor this code and extract out the two meaningful parts into functions (one does the connecting, one the R/W). As it is the code is too long and complicated to be able to easily follow the logic.


Since you're doing an O(N³) operation, with a linear search, a big performance boost will happen if we can eliminate that search.

There are two similar ways to go about it; both replace the search with an indexed lookup.

Change the type of board from a vector that holds the cards to a vector (or array) of card_count slots that holds a count of how many of that card is in the board (using a count for future expansion to multiple decks).
In GetEquity, fill a vector or array of card_count elements with counts for the cards in board, then just check that container for a nonzero to see if the card is contained in the board.  This has the additional advantage of being able to add c1 and c2, so the inner loop checks only need to check one condition (rather than 2 or 3) to see if a card is available.

Here's an updated GetEquity using ideas from option 2:

float GetEquity(const std::vector<int>& board)
{
    std::vector<int> counts(card_count);
    for (auto b: board)
        ++counts[b];

    float equity = 0;

    for (int c1 = 0; c1 < card_count; c1++) // Player1 card
    {
        if (counts[c1])
        {
            continue;
        }
        ++counts[c1];

        for (int c2 = 0; c2 < card_count; c2++)  // Player2 card
        {
            if (counts[c2])
            {
                continue;
            }
            ++counts[c2];

            size_t usedBoards = 0; // number of boards are possible for this players and board cards
            float currentEquity = 0;

            for (int b = 0; b < card_count; b++) // Iterating river board cards
            {
                if (counts[b])
                {
                    continue;
                }

                size_t p1stren = GetHandStrength(board, c1, b);
                size_t p2stren = GetHandStrength(board, c2, b);

                if (p1stren > p2stren)
                {
                    currentEquity += 1.0;
                }
                else if (p1stren < p2stren)
                {
                    currentEquity -= 1.0;
                }

                usedBoards++;
            }

            currentEquity /= usedBoards;
            equity += currentEquity;

            --counts[c2];
        }
        --counts[c1];
    }

    return equity;
}


Feedback

I like the style, timing of events, and how the number input spinners are hidden. It really looks like a console application! Plus, pizza is my favorite food!*

Suggestions

Cache DOM references

As was mentioned in answers to your other question (like the retirement calculator), any DOM element lookups that happen multiple time should be reduced to a single lookup that is stored in a variable (or a constant using const). So in your code, it would be wise to cache $('#peopleInput');, $('#pizzaInput'), etc...

$(function(){
    $('.secondQuestion').hide();
    const peopleInput = $('#peopleInput');
    peopleInput.focus();
    const pizzaInput = $('#pizzaInput');

Don't repeat yourself

This principle comes to play here with the following blocks:

$('#peopleInput').keyup(function(e){
    if(e.keyCode == 13){$(this).trigger("enterKey")}
});

and

$('#pizzaInput').keyup(function(e){
    if(e.keyCode == 13){$(this).trigger("enterKey")}
});

These could be combined to a single CSS Selector:

$('#peopleInput, #pizzaInput').keyup(function(e){
    if(e.keyCode == 13){$(this).trigger("enterKey")}
});

Since those are the only input elements on the page, it could be simplified to simply $('input'), but that might not be a good habit to get into, especially if you go on to larger applications.

Naming

Some of the names are misleading. For example: piece is actually a function that returns the number of pieces, so something like pieceDivision or getNumerOfPieces would be more appropriate.

Templating

Like I mentioned in my answer to your question about the retirement calculator, using templates might allow the code that sets the text to be simplified...

Altered Code

With the suggestions above, the code could be modified to be more like this:

$(function() {
  $('.secondQuestion').hide();
  const peopleInput = $('#peopleInput');
  peopleInput.focus(); //$('#peopleInput').focus();
  const pizzaInput = $('#pizzaInput');

  //Three functions for outputting the result
  const firstOutput = function(a, b) {
    if (b > 1) {
      $('#firstStr').text(a + " people with " + b + " pizzas")
    } else {
      $('#firstStr').text(a + " people with " + b + " pizza")
    }
  }
  const getNumberOfPiecesPerPerson = (a, b) => Math.floor((b * 8) / a);
  const secondOutput = function(a) {
    if (a > 1) {
      $('#secondStr').text("Each person gets " + a + " pieces of pizza")
    } else {
      $('#secondStr').text("Each person gets " + a + " piece of pizza")
    }
  }
  const getNumberOfLeftoverPieces = (a, b) => (b * 8) % a;
  const thirdOutput = function(a) {
    if (a > 1) {
      $('#thirdStr').text("There are " + a + " leftover pieces")
    } else {
      $('#thirdStr').text("There is " + a + " leftover pieces")
    }
  }

  //Action after pressing the enter key on the first line
  peopleInput.bind("enterKey", function(e) {
    $('.secondQuestion').show();
    pizzaInput.focus();
  });
  //combine $('#peopleInput') and $('#pizzaInput') - could also be $('#peopleInput, #pizzaInput')
  $('input').keyup(function(e) {
    if (e.keyCode == 13) {
      $(this).trigger("enterKey")
    }
  });

  //Action after pressing the enter key on the second line
  pizzaInput.bind("enterKey", function(e) {
    peopleInput.focus();
    const numPeople = peopleInput.val();
    const numPizzas = pizzaInput.val();
    firstOutput(numPeople, numPizzas);
    setTimeout(function() {
      secondOutput(getNumberOfPiecesPerPerson(numPeople, numPizzas));
    }, 300);
    setTimeout(function() {
      thirdOutput(getNumberOfLeftoverPieces(numPeople, numPizzas));
    }, 600);
  });
});
body {
  background: #000;
  color: #fff;
  font-family: 'Inconsolata', monospace;
}

h2 {
  font-weight: normal;
}

.output {
  margin-top: 10px;
}

p {
  margin: 0 0 5px 0;
}

input {
  border: none;
  background-color: #000;
  width: 50px;
  color: #fff;
  padding-left: 5px;
  margin-bottom: 5px;
}

input:focus {
  outline-color: #000;
}

main {
  position: absolute;
  left: 200px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
<link href="https://fonts.googleapis.com/css?family=Inconsolata:400,700" rel="stylesheet">

Pizza Party >

      How many people?
      <input type="number" class="form-control" id="peopleInput" value="" name="" min="0" oninput="validity.valid||(value='');">

      How many pizzas do you have?
      <input type="number" class="form-control" id="pizzaInput" value="" name="" min="0" oninput="validity.valid||(value='');">

*not that it means the code is worth more, but at least it is interesting!


Buy once and sell once for maximum profit

profit would be a better name than result.

This could be simplified to a one-liner using itertools.combinations()

profit = max(sell - buy for buy, sell in itertools.combinations(prices, 2))


Do I have too many regexes in my validation logic?

For one, I wouldn't worry about the number of regexps here. There's nothing terribly complex going on here. I'd say regular expressions are the right tools for this job, so no reason to change that.

I do have some other comments though:

I'd advice you to always use English in your code, so phoneNumber, formattedPhoneNumber etc.. I'm not a native English-speaker myself, but I never write code in any other language. Just for consistency.
You can combine the first step of sanitizing the input and checking if there is any. To avoid indenting the code, you can also just return early.
While you're at it, you may want to simplify the regexp a bit. You basically just want to replace everything that isn't a digit or a plus sign:

var input = executioncontext.getEventSource().getValue();
var phoneNumber = String(input).replace(/[^\d+]/g, '');
if(!phoneNumber) return;

The large regexp may be simplified a bit (and be made more consistent by always using \d in place of 0-9). I'd write it as follows, and use match instead of test

var match = phoneNumber.match(/^(?:\+32|0032)?0?([1-9]\d{7}|4\d{8})$/);
if(!match) return; // again we can return if the number wasn't matched

You've already got the formatting part handled well. I've changed it a little, but nothing major. I've swapped out \d for simply . (since we know we're only dealing with digits at this point) but that's not necessary - \d would do equally well.

function acm_mscrm2011_psa_FormatPhoneNumber(executioncontext) {
  var input, phoneNumber, match, formattedNumber;

  input = executioncontext.getEventSource().getValue();
  phoneNumber = String(input).replace(/[^\d+]/g, '');

  if(!phoneNumber) return;

  match = phoneNumber.match(/^(?:\+32|0032)?0?([1-9]\d{7}|4\d{8})$/);

  if(!match) return;

  if(match[1].length === 8) {
    formattedNumber = match[1].replace(/(.)(...)(..)(..)/, "+32 $1 $2 $3 $4");
  } else {
    formattedNumber = match[1].replace(/(...)(..)(..)(..)/, "+32 $1 $2 $3 $4");
  }

  executioncontext.getEventSource().setValue(formattedNumber);
}

You could also combine a couple of steps, and do

function acm_mscrm2011_psa_FormatPhoneNumber(executioncontext) {
  var input, match, formattedNumber;

  input = executioncontext.getEventSource().getValue();
  match = String(input)
    .replace(/[^\d+]/g, '')
    .match(/^(?:\+32|0032)?0?([1-9]\d{7}|4\d{8})$/);

  if(!match) return;

  if(match[1].length === 8) {
    formattedNumber = match[1].replace(/(.)(...)(..)(..)/, "+32 $1 $2 $3 $4");
  } else {
    formattedNumber = match[1].replace(/(...)(..)(..)(..)/, "+32 $1 $2 $3 $4");
  }

  executioncontext.getEventSource().setValue(formattedNumber);
}


Python implementation of find_all_indexes

The code looks correct but overly complicated for the naïve algorithm used.

For a first refactor, you could pull out the special case pattern == ''. (We might pull it back in later).

Then

            for i in range(len(pattern)):
                if text_index + i < len(text):
                    if text[text_index + i] != pattern[i]:
                        break
                    if i == len(pattern) - 1:
                        indexes.append(text_index)

is just a substring equality check. There are two things to note here:

Since it fails when text_index + len(pattern) > len(text) the outer loop runs too far.
This could be written as if text[text_index:text_index+len(pattern)] == pattern: indexes.append(text_index).

Thirdly, the outer while loop could be written as a for in range, which is more Pythonic.

Putting those together, we have

def find_all_indexes(text, pattern):
    if pattern == '':
        return range(len(text) + 1)

    indexes = []
    for text_index in range(len(text) - len(pattern) + 1):
        if text[text_index : text_index + len(pattern)] == pattern:
            indexes.append(text_index)
    return indexes

But then the Pythonic way to write a for if append loop like that is a comprehension:

def find_all_indexes(text, pattern):
    if pattern == '':
        return range(len(text) + 1)

    return [text_index for text_index in range(len(text) - len(pattern) + 1)
            if text[text_index : text_index + len(pattern)] == pattern]

And now the special case is really a microoptimisation, and could possibly be removed to leave a one-liner.

However, that's not the final word. Naïve string search is asymptotically inferior to techniques such as Knuth-Morris-Pratt string search. You probably shouldn't roll your own KMP routine, but you could use string.find to get the benefit. So a better implementation would be a loop around string.find.


Nice solution, it's compact and simple to understand. There is little to improve, few suggestions:

Imports: there are a lot of imports, maybe leftovers of previous attempts.
Try Except block: should be around the code that can cause the exception.

Applying the suggestions:
import re

class Solution:
    def myAtoi(self, s: str) -> int:
        MAX, MIN = 2147483647, -2147483648
        s = re.findall(r'^\s*[+-]?\d+', s)
        try:
            res = int(''.join(s))
        except:
            return 0
        if res > MAX:
            return MAX
        if res < MIN:
            return MIN
        return res

Performance
Runtime: 36 ms, faster than 51.56% of Python3 online submissions
Memory Usage: 14.1 MB, less than 32.27% of Python3 online submissions

Regex makes the code compact but is not the fastest approach. Faster solutions iterate through the string character by character.


times.count in for(int x = 0; x != times.count; x++) is a method call, move it to a variable. Also, you should probably use the < instead of != as it is more common.

However, as you don't really need the index of the element, you can replace both iterations

for(int i = 0; i != filtered.count; i++) {
    unit = [filtered objectAtIndex:i];

by native iteration

for (LogUnit* unit in filtered) {

Is @autoreleasepool necessary in every iteration? Having it outside for should help performance as well. In most application you are not required to use @autoreleasepool at all.

NSString *attributeName = @"realTime";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K IN %@", attributeName, [times objectAtIndex:x]];
// Filter the objectArray by the time, so we don't have to run through all the objects in objectArray, and check if time is right.
NSArray *filtered  = [objectArray filteredArrayUsingPredicate:predicate];

Your filtering doesn't do what your comment describes. You don't want to run through all the objects but that's exactly the thing filteredArrayUsingPredicate: does. Only using reflexion and moving the objects into a new array. By using the filtering code, you are losing performance.

There are various code quality issues not related to performance:

usage of variable names x, f, h, objectArray. Use more descriptive names or use i, j, k for iterators.
Move some code to separate methods, e.g. view generation.
Don't use NULL in Obj-C, use nil. NULL is to be used only when you interact with C pointers, not Obj-C objects.
[comp isEqualToString:NULL] will never evaluate to YES (true)
if(_breakPlease == false) Don't use false in Obj-C. Use YES or NO. Never ever compare a BOOL with a bool literal. Use logical operators instead, e.g. if (!_breakPlease).

Algorithm performance:

The main problem of your algorithm is its complexity. Basically you have two arrays and you compare objects from an array with all objects from the other array. That's O(n^2)

There are many ways how you could improve this, I will list some of them:

Don't use a NSArray to store the log units. Use a NSDictionary where time is the key and log unit, or possibly array of log units with the same time, is the value. Finding log units with the given time will be trivial then.
Sort times and objectArray by time. You can then iterate through both arrays at the same time and you get O(n + n * log n).


This exercise is somewhat unsettling. On the one hand, a stack, as part of a pushdown automaton, is the canonical way to decide balanced languages such as this one; on the other hand, there are much more efficient, idiomatic and practical ways to solve that particular exercise. It is unclear whether it's a computer science exercise or a language learning exercise, one to make concepts sink in or one to discover C++'s expressiveness.

A stack would have been more easily justified if the function argument had been a std::istream& for instance, since it can be traversed only once; or if starting / ending tags had come of different kinds (if they're all the same an integer makes for a perfect stack and counting shouldn't be discriminated).

As @Mike Borland said, the trick to answer that question is to avoid explicit counting by popping the stack filled with as while you iterate over the rest of the string. Something along the lines:

#include <stack>
#include <string>

bool is_ab_balanced(const std::string& str) {
    if (!str.size()) return false;
    auto it = str.begin();
    std::stack<char> as;
    while (it != str.end() && *it == 'a') as.push(*it++);
    while (!as.empty()) {
        if (it == str.end() || *it != 'b') return false;
        as.pop(); ++it;
    }
    return it == str.end();
}

By the way, you'll notice that:

it always is better to use standardized containers unless you need customized behavior: std::stack is certainly better optimized and tested than linkedStackType<>
you shouldn't take a string by value as an argument, unless you intend to modify it while keeping the original string unchanged. Here, there's no modification, so use a const reference instead.
you should get rid of unused variables (see a and b in your second version). Those superfluous variables probably are a by-product of bad habits: declaring variables too far ahead of their use, and not enabling all warnings when you compile your code.
iterators are a better way to iterate over a range: it's more idiomatic, it's necessary to leverage the power of the STL, and it also avoids that extra size variable.
A few more key-strokes are better than using namespace std, which is is a bad idea

But, as I said, a good exercise should look more like real life. In real life, you use a stack only if it is the best way to go. So how would you check if a string belongs to the language if you could choose without restriction?

My take on that would be:

#include <string>
#include <algorithm>

using Iterator = std::string::iterator;
bool is_balanced(Iterator first, Iterator last) {
    auto middle = std::next(first, std::distance(first, last) / 2);
    return std::equal(first, middle, middle, last, [](auto a, auto b) {
        return a == 'a' && b == 'b';
    });
}

Or, other more meaningful exercises would have been:

how would you check if parenthesis are balanced in an expression (I wouldn't use a stack here either)?
how would you check if html tags are correctly balanced (here using a stack is meaningful)?


Choice Decision Maker (Random string from ArrayList)

-For starters, I'm not sure why you needed inheritance for this in the first place, as opposed to passing your choices array into your init function. I'm assuming just to get practice with inheritance?

-I'd move your toString function to your base class if this is functionality you plan on using in most of the children classes. I'd also rename this function to avoid common keywords and to be more descriptive--something like printResult might make more sense, unless your intent is to overload the built-in toString function.


Check if a string is a valid english word, and convert to a valid english word

You should avoid statements on the same line as an if.
So for example

if (len == 0)
    return true;

instead of

if (len == 0) return true;

Also, I find that the (s.charAt(0) < 65) || (s.charAt(0) > 90) are really hard to understand as they use magic numbers.

But, most importantly, are you sure your code is responding to all the cases ?

Let's create some unit test with JUnit and AssertJ :

class TestTestString {
    @Test
    void isValidString_shouldAcceptSimpleWord() {
        assertThat(TestString.isValidString("Hello")).isTrue();
    }

    @Test
    void isValidString_shouldAcceptVeryLongWord() {
        assertThat(TestString.isValidString("Thisincrediblylongwordisylbidercnilongz")).isTrue();
    }

    @Test
    void isValidString_shouldAcceptSingleUppercaseString() {
        String[] values = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N" };
        for (String s : values) {
            assertThat(TestString.isValidString(s)).isTrue();
        }
    }

    @Test
    void isValidString_shouldAcceptStringWithDiacritics() {
        assertThat(TestString.isValidString("Résumé")).isTrue();
    }

    @Test
    void isValidString_shouldRefuseStringThatStartWithALowerCaseLetter() {
        assertThat(TestString.isValidString("apropos")).isFalse();
    }

}

Without much surprise, the isValidString_shouldAcceptStringWithDiacritics is failing... but so is the isValidString_shouldAcceptVeryLongWord because the 120 isn't the good number !
Never forget to do some unit tests :) (you should also add some tests for numbers and special characters)

To conclude, if I were you, I'd get rid of the current test altogether and use the Character methods that are nicer lookings, namely isUpperCase and isLowerCase :

public static boolean isValidString(final String s){
        int len = s.length();

        if (len == 0)
            return true;
        if (!Character.isUpperCase(s.charAt(0)))
            return false;
        for (int i = 1; i < len; i++) {
            if (!Character.isLowerCase(s.charAt(i)))
                return false;
        }

        return true;
    }

Now, if you rerun the tests, they should be all green.

You can also use the same methods for your convert function ;)


Correct way to delete elements from a ConcurrentDictionary with a predicate

I know it's not a direct answer to your question, but I'm trying to get to the roots of the problem rather than giving correct answer to issue caused by potential misuse...

In your code what you are actually trying to do is to write a cache with time-based expiration of items. Even though ConcurrentDictionary is thread-safe, it's not quite appropriate structure for frequent element scans like you do. Moreover, in your code you remove items, then add them back in case when they have been updated in the middle. It causes side effects for other threads that may try to read the value in-between.

Correct solution would be to use a proper data structure. If by any chance you are using .NET 4.0 or later .NET has already provided you with proper solution - MemoryCache class, otherwise I would recommend creating a lock-based class that maintains 2 indexes for entries - a Dictionary for storing key-value pairs, and a SortedList for storing expiration timestamp-key mapping. In this case you'll always know upfront when the next expiration will happen so timer can be set to specific TimeSpan, and you don't have to scan through all cache entries to find expired ones.


You can use a variable and assume that it will fail, if you do not print the new message

   public void login(View view){
            RequestQueue queue = Volley.newRequestQueue(this);
            String URL = "http://10.0.2.2:8000/api/login";
            StringRequest request = new StringRequest(Request.Method.POST, URL,
                    new Response.Listener<String>()
                    {
                        @Override
                        public void onResponse(String response) {
                            String loginMsg = "Ooops something is not correct !";

                            try {
                                JSONObject jsonObj = new JSONObject(response);
                                myToken =jsonObj.getString("token");
                                if (myToken != ""){
                                    loginMsg = "Login successfull !"
                                }
                            } catch (JSONException e) {
                                 myToken = "";
                                 e.printStackTrace();
                            }

                            Toast.makeText(getApplicationContext(), loginMsg, Toast.LENGTH_LONG).show();

                        }
                    },
                    new Response.ErrorListener()
                        {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            myToken = "";
                            Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
                            NetworkResponse response = error.networkResponse;
                            String errorMsg = "";
                            if(response != null && response.data != null){
                                String errorString = new String(response.data);
                            }
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams()
                {
                    Map<String, String> params = new HashMap<String, String>();
                    TextInputEditText mail = findViewById(R.id.textInputEditTextEmail);
                    TextInputEditText pw = findViewById(R.id.textInputEditTextPassword);
                    params.put("email", mail.getText().toString());
                    params.put("password", pw.getText().toString());
                    return params;
                }
            };
            queue.add(request);
        }


Ignoring the effect of a space when applying encryption

Before I answer your question, I'm gonna give a more general review:

Spaces are good things. They help readability a lot. For example, this:

for(int c=0;c<distances.length;c++) {

should be this:

for (int c = 0; c < distances.length; c++) {

The rules I use are complicated, but it boils down to a space on either side of a keyword, binary operator, or curly brace.
Put a newline between your methods. After the closing brace of one, you should have a blank line, then any Javadocs for the next method, then the next method itself.
convert should probably be a private static, and the rest should be public static. It's very rare that you actually want to use package-private things; more often than not, the other three permissions cover every case.
Use advanced for loops when the only thing you use the index for is accessing a single array.
Instead of repeated + on Strings, use a StringBuilder and .append. For example, this:

String result = "";
for (int c : distances) {
    char distance = (char) ('A' + c);
    result += distance;
}
return result;

becomes this:

StringBuilder result = new StringBuilder(distances.length);
for (int c : distances) {
    char distance = (char) ('A' + c);
    result.append(distance);
}
return result.toString();

It's more performant in terms of speed and memory.
Use better variable names than array, c, etc. Those tell us nothing about what they really are.

Now, on to your question: Yes, you can do this. In fact, there are a couple of ways to do it. You've gone for the most obvious -- and, for only one or two letters, arguably best -- option. However, as you start to have more and more letters you want to ignore, it becomes a hassle to add them all to the if.

One thing you could do is declare a static final char[] forbiddenLetters and, each iteration, check if the letter (or, more accurately, 'A' + convertedLetter) is contained in forbiddenLetters, skipping over it if so.

Another option is, instead of using a blacklist, use a whitelist: Have a static final char[] validLetters and use it much the same way, but applying the encryption if the letter is in the list or not. This works better for your case, as I think you'll probably have a good deal more forbidden letters than valid ones. If you just want capital letters, you could also apply the same concept by checking that for each (converted) letter \$l\in\mathbb{Z}\$, \$l\in\left[0,25\right]\$

I'm gonna leave the implementation of that up to you, though. Both ought to be fairly easy -- especially the second suggestion in the latter -- to translate to Java.


Refactoring if statement based on a hash key

I suggest using find

ARTICLE_ACTIONS = { :draft => :to_draft,
                    :archived => :to_archive,
                    :default => :publish
                  }

def update_state
  state = [:draft, :archived, :default]
             .find {|state| params[state].present?}
  @article.send ARTICLE_ACTIONS[state]
end


Identical jQuery autocomplete handlers for two form fields

You can create separate function like this:

function autoComplete($obj, $valueObj, $zipValue){
        $obj.autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "includes/state_au_ajax.php",
                    dataType: "json",
                    method: "post",
                    data: {
                        term : request.term,
                        state : $valueObj.val()
                    },
                                success: function( data ) {
                                     response( $.map( data, function( item ) {
                                        var code = item.split("|");
                                        return {
                                            label: code[0],
                                            value: code[0],
                                            data : item
                                        }
                                    }));
                                }
                });
            },
            autoFocus: true,
            minLength: 2,
              select: function( event, ui ) {
                    var output = ui.item.data.split("|");
                    $zipValue.val(output[1]);
                },
            delay: 300
          });
    }

And then call it appropriately:

    autoComplete($("#suburb"), $("#state"), $('#zip_code'))
    autoComplete($("#p_suburb"), $("#p_state"), $('#p_zip_code'))


Shuffle a deck of cards, using the overhand shuffle method

A quick disclaimer: I am not really a clojure developer so take any of my recommendations with a pinch of salt.

Regarding your giant let:  I don't think that's necessarily a bad thing to do, but in some cases it might be worth splitting some of it off into separate functions.  For example max-slice-size and number-of-slices are only really needed to generate slice-sizes, so it may be worth splitting them off into a make-slice-sizes function or something.

Most of the reasons you listed for having things in a giant let are actually really good reasons to use smaller functions:

You've got a selection of smaller functions rather than the big dense mono-function you were trying to avoid.
Your individual functions are your manageable pieces, rather than each binding of the let.  You can call them from a repl, or write tests of just those individual functions to make sure they are behaving as expected.
Debugging is also still possible, but with the benefit that it's easier to use a repl & write tests.

A few points about your reduce:

You can simplify it a bit by returning a vector instead of a map and using argument destructuring instead of getting the values out of the map.
When you want to do a take & a drop using the same numbers it's usually easier to use split-at.
Passing back 2 things from a reduce doesn't seem wrong.  However I would consider just using your reduce to build up a list of slices that you can manipulate afterwards rather than using concat to actually do the shuffling within the reduce.  The reductions function can help with this - it is like reduce, but it returns the intermediate steps that you can manipulate later.
Currently you are building up a list of random slice sizes, and then writing some more code to handle the remainder of the cards (top-cards in your code).  I think you could simplify your code a fair bit by just treating this as another slice and adding it in to your slice-sizes sequence.

I've had a go at implementing my suggestions, and ended up with this:

(defn overhand-shuffle
  "Shuffle the cards, using the overhand shuffle technique.
  REFL https://en.wikipedia.org/wiki/Shuffling#Overhand_shuffle"
  [cards]
  (let [slice-sizes        (make-slice-sizes (count cards))
        ; The first value returned by reductions is the initial value, so we
        ; drop it here.
        [_ & slices]       (map first
                             (reductions (fn [[_ remaining-cards] slice-size]
                                           (split-at slice-size remaining-cards))
                                         [nil cards]
                                         slice-sizes))]
    (apply concat (reverse slices))))

(defn- make-slice-sizes
  "Randomly determine the size of the little slices we will take"
  [number-of-cards]
  (let [number-of-slices  (/ (* number-of-cards 7) 52)
        max-slice-size    (int (/ (* number-of-cards 0.6) number-of-slices))
        slice-sizes       (map inc (repeatedly
                                    number-of-slices
                                    #(rand-int max-slice-size)))
        remaining-cards   (- number-of-cards (apply + slice-sizes))]
    ;; We need to make sure all our cards get "shuffled", so add a slice of the
    ;; remaining cards on the end of our list of slices
    (concat slice-sizes [remaining-cards])))

Please let me know if I've explained any of this badly, and I'll try and improve it.

Edit: You can actually take this a bit further and split out your reduction into a function as well:

(defn build-slices
  "Builds a sequence of slices from cards.
   The sizes of the slices are determined using slice-sizes"
  [cards slice-sizes]
  ;; Perform a reduction where the first element of each step is the slice,
  ;; and the second element is the remaining cards.  Use a let binding to get
  ;; rid of the first reduction, because it is just the initial value we
  ;; passed in.
  (let [[_ & slices]  (map first
                          (reductions (fn [[_ remaining-cards] slice-size]
                                        (split-at slice-size remaining-cards))
                                      [nil cards]
                                      slice-sizes))]
    slices))

Which allows you to simplify your overhand-shuffle function further:

(defn overhand-shuffle
  "Shuffle the cards, using the overhand shuffle technique.
  REFL https://en.wikipedia.org/wiki/Shuffling#Overhand_shuffle"
  [cards]
  (let [slice-sizes   (make-slice-sizes (count cards))
        slices        (build-slices cards slice-sizes)]
    (apply concat (reverse slices))))

Since both these functions are now just a series of steps each building on the last you could rewrite using one of the threading macros (-> or ->>).  These let you list a series of forms and automatically insert the result of the last form into the next form, as either the first (for ->) or the last (for ->>) parameter to each of them.  This allows you to make your function a series of "steps" that transform your input data, a bit like your original let bindings, but without the intermediate variables:

(defn build-slices
  "Builds a sequence of slices from cards.
   The sizes of the slices are determined using slice-sizes"
  [cards slice-sizes]
  (->> slice-sizes
       ;; Perform a reduction where the first element of each step is the slice,
       ;; and the second element is the remaining cards.
       (reductions (fn [[_ remaining-cards] slice-size]
                     (split-at slice-size remaining-cards))
                   [nil cards])
       ;; Drop the first element, as it is just our initial [nil, cards] value.
       (drop 1)
       ;; Extract each of the slices.
       (map first)))

(defn overhand-shuffle
  "Shuffle the cards, using the overhand shuffle technique.
  REFL https://en.wikipedia.org/wiki/Shuffling#Overhand_shuffle"
  [cards]
  (->> cards
       (count)
       (make-slice-sizes)
       (build-slices cards)
       (reverse)
       (apply concat)))

A bonus edit: the loop in your test-shuffle function is very procedural.  Could be better with iterate:

(defn test-shuffle
  "Simple invocation of shuffle, to show result"
  []
  (let [simple-cards (range 1 53)
        shuffle-times 10]
    (nth (iterate overhand-shuffle simple-cards) shuffle-times)))


If you have access to C++11, I'd suggest using std::max with an initializer_list<T>. A complete minimal example:

#include <algorithm>
#include <initializer_list>
#include <iostream>

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;

    int m = std::max({a, b, c});

    std::cout << m << "\n";
}


Read two numbers and return a sum, in PIC24 Assembly

As @Snowbody already pointed asked, what is your code supposed to after this line:

mov W3,[W0]

It seems as though the execution of your program will fall through and re-enter the mySUB subroutine again.

To fix this...

Create a second label after the mySUB. Then, after _main is done working with the return values of mySUB, you can jmp (or whatever it is called in PIC24) to the second label that you created.

Then, execution will jump over mySUB and hit the .end pragma at the end.

Your mySUB subroutine seems to be doing more than it's job.

The very first line of this subroutine is

mov #R0, W0

This line is moving a pointer to a memory location into W0. However, this subroutine is supposed to add numbers together. If it was meant to add numbers together and then put the result in memory, then why isn't it doing that at the end of the subroutine?

In my opinion, you should move the first line out of the subroutine and to the first line after the subroutine call (and before mov W3,[W0]).

That way, the subroutine is doing it's job of adding two numbers together, and the _main routine is doing it's job of getting two numbers added together, and then putting that sum in memroy

In the future, I recommend that you add some sort of documentation for each subroutine you have. It doesn't have to be a lot; it can be something as simple as this:

; Adds two numbers
; Input: W1, W2
; Output: W3 = W1 + W2
mySUB: ...


Calculate sum of price on distant relation

You can do this:

def total
  self.appointments.joins(:activity).sum(:price)
end

You could perhaps simplify it a little, by making an explicit 2nd order has_many on your booking model:

has_many :appointments
has_many :activities, :through => :appointments

Then you can just do:

def total
  self.activities.sum(:price)
end

In either case, it'll end up as a single DB-query.


Mailinator automatic checker for new e-mails

Overall it looks great, but here are a couple of thoughts:

print('New email received.'): maybe print a snippet form the message or just the time stamp so you have some idea on when the new email arrived (instead of just having a stream of same strings stating "New email received.").
I'd consider moving the inbox operations into its own class. Its __init__ could be __init__(inbox, api): .... CHECKING_FREQ could be a keyword argument to this, defaulting to 30, but configurable through the input params when running the script. The class could have a fetch_inbox (merging your get_inbox and check_inbox). And finally the has_new_items (just rename your is_new method).
Your wait_email is what I'd call check_inbox because for checking the inbox you first have to fetch the inbox and then check the message timestamps on what was returned.
I feel someone might have a good suggestion on how to do that infinite loop, but I can't think of a good way right now. All I know is it feels a little odd (or maybe it's fine :).

Hopefully this helps.


Speed up solution to Project Euler problem 75

For the record, this is Project Euler problem 75.

1. Admonition

You write:

  Please note that I am not looking for a different calculating method (I am sure there is one, but, for me, Project Euler is about finding your own methods. Using yours would, to me, be cheating.)

Abandon this attitude! A key part of programming — just as important as coding — is developing a wide repertoire of algorithms and techniques that you can apply to problems you face. Although for your own intellectual satisfaction it's great to discover algorithms on your own, you should always go on to compare your solution to the best solutions discovered by others, so that you can improve your repertoire for the next problem.

In particular, when you want to speed up a program, it's counterproductive to say, "I don't want to implement a different algorithm, I just want to speed up the code I wrote". The biggest speedups come from finding better algorithms.

You say that your program "runs fine" but that doesn't seem to be true. Project Euler says:

  Each problem has been designed according to a "one-minute rule", which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute.

I tried running your program, but after ten minutes it still had not produced an answer (and my laptop was running hot), so I killed it.

So in section 2 below I'll be using a smaller test size, 100,000 instead of 1,500,000, to keep the runtimes manageable.

2. Piecewise optimization

Your program is hard to test from the interactive interpreter because it has code at the top level. Better to put the main program inside a function so that you can call it from interpreter and then add an if __name__ == '__main__': section so that you can run it as a script if you want to.

I've used the function name problem75, and it takes an argument, which is the largest value of the length of wire in the problem. Now:

>>> from timeit import timeit
>>> timeit(lambda:problem75(10**5),number=1)
12 (3, 4, 5)
24 (6, 8, 10)
30 (5, 12, 13)
[... much output deleted ...]
33.87288845295552

The print statement near the end of the main loop is unnecessary. This saves about 3 seconds, bringing the time down to 31.0 seconds.
Your function aFactors makes an initial call to isPrime, taking \$ O(\sqrt n) \$, in order to avoid a loop that also takes \$ O(\sqrt n) \$. The test costs as much as it saves, so it's not worth it. Remove the call to isPrime and rewrite the function like like this:

def factors(n):
    """Return the set of factors of n."""
    result = set([1, n])
    add = result.add
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            add(i)
            add(n // i)
    return result

Here I've picked a better name for the function, written a docstring explaining what it does, and cached the value of result.add so that it does not need to be looked up each time arounnd the loop. This saves about 4 seconds; time now 27.7 seconds.
Since the only thing you do with the set of factors is to turn it into pairs which you then iterate over, why not generate the pairs, like this:

def product_pairs(n):
    """Generate pairs (i, j) such that i * j = n."""
    yield 1, n
    yield n, 1
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            j = n // i
            yield i, j
            yield j, i

and then process them like this:

triangles = []
append = triangles.append
for i in product_pairs(number // 2):
    for j in product_pairs(i[0]):
        append((2*i[1]*i[0]-i[1]*i[1]*j[0],2*i[0]*i[1]-2*i[0]*j[1],2*i[0]*j[1]+i[1]*i[1]*j[0]-2*i[0]*i[1]))

This avoids having to construct an intermediate list in memory. This saves about 3 seconds; time now 24.3 seconds.
Instead of writing for i in product_pairs(...): and then looking up i[0] and i[1], split up the pair into two variables when you assign it in the loop, like this:

for i, j in product_pairs(number // 2):
    for k, l in product_pairs(i):
        append((2*j*i - j*j*k, 2*i*j - 2*i*l, 2*i*l + j*j*k - 2*i*j))

This avoids the sequence lookups. This saves about 3 seconds; time now 21.2 seconds.
You construct a list of triangles, some of which have sides with negative or zero length. You then go through the list and del the triangles which are invalid. But del on a list is a potentially expensive operation: it has to copy the remainder of the list to keep it contiguous. See the TimeComplexity page on the Python wiki for the cost of basic operations on Python's built-in data structures, where you can see that "delete item" operation on a list takes \$O(n)\$.

So don't add these invalid triangles to the list in the first place. In fact, don't bother with the list at all, just construct the set of triangles directly:

triangles = set()
add = triangles.add
for i, j in product_pairs(number // 2):
    for k, l in product_pairs(i):
        triangle = 2*j*i - j*j*k, 2*i*j - 2*i*l, 2*i*l + j*j*k - 2*i*j
        if all(side > 0 for side in triangle):
            add(tuple(sorted(triangle)))

This saves about 6 seconds; time now 15.1 seconds.
You can avoid some repeated multiplications by naming the various products of i, j, k, and l:

for i, j in product_pairs(number // 2):
    for k, l in product_pairs(i):
        p, q, r = 2 * j * i, j * j * k, 2 * i * l
        triangle = p - q, p - r, r + q - p
        if all(side > 0 for side in triangle):
            add(tuple(sorted(triangle)))

This saves about 1 second; time now 13.9 seconds.

And I'm afraid that's as far as I got by applying piecewise speedups to your code. About 60% speedup in total. The revised program now gets the solution to the full Project Euler problem in about eight minutes on my laptop:

>>> timeit(lambda:main(1500000),number=1)
[... solution deleted ...]
467.3059961795807

Perhaps some other participant here can make more piecewise progress, but for dramatic speedups, you really need ...

3. A better algorithm

(Avert your eyes if you must.)

The basic insight is that instead of iterating over the perimeter and finding the Pythagorean triples with that perimeter, we can iterate over all Pythagorean triples in some more convenient order, and keep count of how many triangles are found at each perimeter length.

We can further speed things up by only generating the primitive Pythagorean triples, and then multiplying the primitive triples by successive numbers 1, 2, 3, ... to generate the remaining Pythagorean triples in the required range. In fact, we only need to multiply their perimeters.

Euclid’s formula can be used to generate all primitive Pythagorean triples. Given coprime positive integers \$m\$ and \$n\$, with \$m > n\$, and exactly one of \$m\$ and \$n\$ even, $$ \eqalign{ a &= m^2 − n^2 \\ b &= 2mn \\ c &= m^2 + n^2} $$ is a primitive Pythagorean triple.

The remaining subtlety is that Euclid’s formula doesn’t generate triples in order by length of the perimeter, so there needs to be some way to determine when to stop. My strategy in the code below is to iterate over ascending values of \$m\$. The perimeter of the triple is \$a + b + c = 2m^2 + 2mn\$, which is at least \$2m(m + 1)\$, since \$n ≥ 1\$. So \$2m(m + 1)\$ is a lower bound on the perimeter for which all triples have been generated so far. When this exceeds the limit, we can stop the search: there are no more triples to be found in the required range.

from collections import Counter
from fractions import gcd
from itertools import count

def coprime(m, n):
    """Return True iff m and n are coprime."""
    return gcd(m, n) == 1

def all_primitive_triples():
    """Generate all primitive Pythagorean triples, together with a lower
    bound on the perimeter for which all triples have been generated
    so far.

    """
    for m in count(1):
        for n in range(1, m):
            if (m + n) % 2 and coprime(m, n):
                a = m * m - n * n
                b = 2 * m * n
                yield a, b, m * m + n * n, 2 * m * (m + 1)

def problem75(limit=1500000):
    """Return the number of values of L <= limit such that there is
    exactly one integer-sided right-angled triangle with perimeter
    L.

    """
    triangles = Counter()
    for a, b, c, q in all_primitive_triples():
        if q > limit:
            break
        p = a + b + c
        for i in range(p, limit + 1, p):
            triangles[i] += 1
    return sum(n == 1 for n in triangles.values())

This solves the Project Euler problem in a more reasonable amount of time:

>>> timeit(problem75, number=1)
2.164217948913574


Infinite Continued Fraction - iterative and recursive

Your solutions look good.

I don't see any significantly different way to do the recursive solution.  My preferences for whitespace (mostly concerning the if) are a little different.  Also, I wouldn't define a function for next in this situation.  If for some reason you don't want to simply put (+ n 1) as an argument a let expression would be more applicable.

(define (cont-frac n_i d_i k)
   (define (recurse n)
     (if (= n k)
         (/ (n_i k) (d_i k))
         (/ (n_i n) (+ (d_i n) (recurse (+ n 1)))) ))
   (recurse 1))

OR

(define (cont-frac n_i d_i k)
   (define (recurse n)
     (if (= n k)
         (/ (n_i k) (d_i k))
         (let ((next_n (+ n 1)))
           (/ (n_i n) (+ (d_i n) (recurse next_n)))) ))
   (recurse 1))

PS - write a function for the nth_odd_square and try this

(/ 4.0 (+ 1 (i-cont-frac nth_odd_square (lambda (i) 2.0) 500000)))


Your instruction list:

#define READ 10;
#define WRITE 11;
#define LOAD 20;
#define STORE 21;
#define ADD 30;
#define SUBTRACT 31;
#define DIVIDE 32;
#define MULTIPLY 33;
#define BRANCH 40;
#define BRANCHANG 41;
#define BRANCHZERO 42;
#define HALT 43;

has a few issues. First of all, you shouldn't add semicolons after those defines. Also, this would be better represented as an enum, since op codes are mutually exclusive.

Your memory initialization:

int memory[100] = {2022,1022,3022,2122,2021,3120,2121,4209,4000,1122,4300}; // my set of instruction for sum 10 numbers

also needs a few adjustments. Since none of these values will exceed 9999, you should be storing them as int16_t, not int. Furthermore, you shouldn't be writing raw machine code in that array. You should be constructing those values like

{
    100*LOAD + 22,
    100*READ + 22,
    // ...
}

Also, it seems like you store -99999 as a magic value to indicate program termination, when this is technically not necessary. I don't have the specifications for your VM, but it would make more sense to

have all of the memory contents be of type int16_t
on HALT, simply terminate the program

rather than

on HALT, jump to the end of memory
at the end of memory, have a magic negative value.

There's a typo in instRegistrer. It's "register", not "registrer".

I propose that, instead of having to manually write a different printf string for each instruction,

declare an array of 44 character pointers
define a macro that indexes into the array based on the opcode value, and initializes that element to a stringized (#) version of the opcode
call the macro for every opcode that you have

You could take this strategy further and store a struct at each element of the array, containing a string name and an operation function pointer. This would nicely generalize your code and make execution of long programs faster.

You're also keen on avoiding separate assignment of memory contents for use by variables. This can be done by shifting your "data" memory to the address right after your "program" memory, and then doing the initialization in your array literal.

The following incorporates all of the above. It seems you're still learning basic C, so some of these concepts may require explanation - please let me know in the comments.

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

typedef enum
{
    READ = 10,
    WRIT = 11,
    LOAD = 20,
    STOR = 21,
    ADD = 30,
    SUB = 31,
    DIV = 32,
    MUL = 33,
    BRA = 40,
    BRNG = 41,
    BRZR = 42,
    HALT = 43
} OpCode;

typedef struct
{
    int16_t mem[100], acc;
    uint8_t counter;
} VM;

typedef struct
{
    const char *name;
    void (*execute)(VM *vm, uint8_t addr);
} Operation;

static uint16_t makeOp(OpCode code, uint8_t addr)
{
    return 100*code + addr;
}

#define DEFOP(op) ops[op] = (Operation){.name=#op, .execute=exc_##op}

static void exc_READ(VM *vm, uint8_t addr) {
    int32_t x;
    if (scanf("%d", &x) != 1)
    {
        perror("Failed to read integer");
        exit(1);
    }
    if (x >= 10000 || x <= -10000)
    {
        fprintf(stderr, "Invalid value %d", x);
        exit(1);
    }
    vm->mem[addr] = x;
    vm->counter++;
}
static void exc_WRIT(VM *vm, uint8_t addr) {
    printf("%d\n", vm->mem[addr]);
    vm->counter++;
}
static void exc_LOAD(VM *vm, uint8_t addr) {
    vm->acc = vm->mem[addr];
    vm->counter++;
}
static void exc_STOR(VM *vm, uint8_t addr) {
    vm->mem[addr] = vm->acc;
    vm->counter++;
}
static void exc_ADD(VM *vm, uint8_t addr) {
    vm->acc += vm->mem[addr];
    vm->counter++;
}
static void exc_SUB(VM *vm, uint8_t addr) {
    vm->acc -= vm->mem[addr];
    vm->counter++;
}
static void exc_DIV(VM *vm, uint8_t addr) {
    vm->acc /= vm->mem[addr];
    vm->counter++;
}
static void exc_MUL(VM *vm, uint8_t addr) {
    vm->acc *= vm->mem[addr];
    vm->counter++;
}
static void exc_BRA(VM *vm, uint8_t addr) {
    vm->counter = addr;
}
static void exc_BRNG(VM *vm, uint8_t addr) {
    if (vm->acc < 0)
        vm->counter = addr;
    else
        vm->counter++;
}
static void exc_BRZR(VM *vm, uint8_t addr) {
    if (!vm->acc)
        vm->counter = addr;
    else
        vm->counter++;
}
static void exc_HALT(VM *vm, uint8_t addr) {
    exit(0);
}

int main()
{
    const uint8_t X = 13, I = 12, DELTA = 11;

    Operation ops[HALT+1];
    DEFOP(READ);
    DEFOP(WRIT);
    DEFOP(LOAD);
    DEFOP(STOR);
    DEFOP(ADD);
    DEFOP(SUB);
    DEFOP(DIV);
    DEFOP(MUL);
    DEFOP(BRA);
    DEFOP(BRNG);
    DEFOP(BRZR);
    DEFOP(HALT);

    VM vm = {.counter = 0,
             .acc = 0,
             .mem = {
                makeOp(LOAD, X), // 0: beginning
                makeOp(READ, X),
                makeOp( ADD, X),
                makeOp(STOR, X),
                makeOp(LOAD, I),
                makeOp( SUB, DELTA),
                makeOp(STOR, I),
                makeOp(BRZR, 9),
                makeOp( BRA, 0),
                makeOp(WRIT, X), // 9: exit loop
                makeOp(HALT, 0),
                1,  // 11: DELTA
                10, // 12: I
                0   // 13: X
             }};

    for (;;) {
        int16_t current = vm.mem[vm.counter];
        uint8_t code = current/100,
                addr = current%100;
        const Operation *op = ops + code;
        printf("%02u: %4s %02u\n", vm.counter, op->name, addr);
        op->execute(&vm, addr);
    }
}


Don't use meaningless names like "napis" and "wynik".
x and i are meaningful in some contexts, but not for what you're using them, so use better names for those as well.
You could take advantage of negative indices, i.e., remove ALPHABET[i+x] if i+x<len(ALPHABET) else  and just use ALPHABET[i+x-len(ALPHABET)]. Or, more generally, ALPHABET[(i+x) % len(ALPHABET)].
You could assume that spaces are the most frequent characters and do x = ALPHABET.index(' ') - max(napis, key=napis.count) instead of the loop.


private static byte[] getSaltFromPassword(byte[] passwordByteArray) {
    byte[] bytes = sha256.digest(passwordByteArray);
    for (int i = 0; i < SALT_ITERATIONS; i++) {
      bytes = sha256.digest(bytes);
    }
    return bytes;
  }

this part is an NO NO. salt has to be random. please refer this
old question
The salt has to be independent and random else it is useless.


A simple testable standalone DLL for die rolling

Add one more constructor that takes an extra Random param:

public Die(int numberOfSides, Random random)
{
    if(numberOfSides < 2)
        throw new ArgumentException(string.Format(GameComponentsResources.InvalidNumberOfSides, numberOfSides));

    _numberOfSides = numberOfSides;
    _random = random;
}

public Die(int numberOfSides)
{
    this(numberOfSides, new Random());
}

Most users will use the single-param version.
Some users, who want more control, for example in tests, can use the two-param version.
You can write your tests in a straightforward way using the two-param version.

If you really don't want to expose the two-param constructor in the public API,
then make it protected.
But I think it's quite fine to include in the public API,
it doesn't make the library confusing, and I don't see any harm.

If, for some reason you are against passing a Random instance (like @JasonLind, see his comment),
then you can make the constructor taking a Random above private,
and add another constructor that takes a seed parameter instead:

public Die(int numberOfSides, int seed)
{
    this(numberOfSides, new Random(seed));
}


Skip to the Dramatic Update for the best solution
I was curious how to do this myself, because I could clearly tell there had to be an easier way! I started from scratch and I think I've found exactly what this question is asking for.
I don't normally just rewrite code, but since the question asks the best way, I believe I'm obligated to share what I believe is the "bets way".
$input = [1, 10, 11, 12, 11, 12, 18, 18];

$recorded = array_count_values($input);

arsort($recorded);

$output = [];

foreach ($recorded as $key => $value) {
    if ($value == max($recorded)) {
        array_push($output, $key);
    }
}

print_r($output);

I'll explain what's happening here:

We receive the input in $input
array_count_values() returns an array using the values of array as keys and their frequency in array as values. In our case, from $input.
arsort — Sort an array in reverse order and maintain index association
Loop over each pair in the newly sorted array. Create some variables to reference the current pair.
If the current value is equal to the largest value from $recorded
Add that key to the output!

And there we have it!
Update to increase performance
$input = [1, 10, 11, 12, 11, 12, 18, 18];

$recorded = array_count_values($input);

arsort($recorded);

$output = [];

$maximum = max($recorded);

foreach ($recorded as $key => $value) {
    if ($value == $maximum) {
        $output[] = $key;
    } else if ($value < $maximum) {
        break;
    }
}

print_r($output);

We've stored the maximum so we aren't checking every iteration, and we're checking for a value less than the maximum so we can break out of the loop to prevent going through the whole array.
Dramatic Update
So, I completely missed the array_keys function, as pointed out by shudder. The newly improved code would look something like:
$input = [1, 10, 11, 12, 11, 12, 18, 18];

$recorded = array_count_values($input);

$output = array_keys($recorded, max($recorded));

print_r($output);

Crazy improvement compared to the OPs original code!


Overall, the code is quite simple. That's a good thing already.

Some things can be improved though:

Always create the autorun property. It will help your compiler. See here for more details. Besides, it's simpler to read. Just go with this:

function Queue(autorun) {
    this.autorun = autorun;
}

On another note, adding the properties on the prototype is just as bad, read the link I already showed to understand why.

Maybe it's only me, but the first lines are disturbing because they're before the "class" declaration. So it looks like they belong to the external object, while they actually belong to the hoisted function.
You don't need typeof variable === "undefined". variable === undefined is enough because you know for sure the identifier exists.
var shift = this.queue.shift(); w-w-w-what's this variable name?! You probably mean var first .... Use descriptive variable names.
I'm not sure you want to return shift in dequeue. Don't you mean this? Chaining is fun!


Should I use an object or type as trait?

Yes, the std way of doing things in C++ would be to provide static member functions of your traits type. Consider:

// declaration - empty
template <typename SETTINGS>
struct SettingsTraits;

// specialization for type CFoo
template <>
struct SettingsTraits<CFoo>
{
  typedef CFooRelated RelatedType;
  static CAttribute<RelatedType>& GetAttrFrom(CDataSource& ds) { return ds.GetFooAttr(); }
};

// specialization for type CBar
template <>
struct SettingsTraits<CBar>
{
  typedef CBarRelated RelatedType;
  static CAttribute<RelatedType>& GetAttrFrom(CDataSource& ds) { return ds.GetBarAttr(); }
};

typedef SettingsTraits<SETTINGS> TRAITS;
CAttribute<TRAITS::RelatedType> attr = TRAITS::GetAttrFrom(datasource);

Notice that this way of doing things doesn't involve global objects or values at all; it's all done entirely within the type system. The compiler can look at the line TRAITS::GetAttrFrom(datasource) and statically know that it's equivalent to datasource.GetFooAttr(), which means the whole thing compiles down to a single call instruction. Your old code would have required a trip to memory in order to load the value of the pointer SettingsTraits<CFoo>::GetAttr.

Rule of thumb: you should never need to construct a type-traits object at all. If you do, you're probably doing it wrong.


I didn't yet found a way to have a class in ECMAScript that mixes public and private methods in a way, where the public methods (and only them) can still access private methods and vars.

JavaScript ain't classical OOP. Don't force it to be like one. The default inheritance pattern in JS is prototypal, and everything is public and methods are shared across instances.

You could emulate private by defining your data not as properties but as vars in the constructor. However, this requires that your methods be defined in the constructor to have access to them. This means that your methods are created on a per-instance basis, rather than shared via the prototype.

Anyways, off to a review of your code:

this._items = [];

I'm pretty sure you wanted a hash {} instead of an array.

this._items[key] = this[key] = value;

I'm not sure why you want to add the key-value pair as a property of the cache object. I'm pretty sure this is why you have to guard against overriding your methods. I suggest you don't. Make your object just an interface. Don't put your data on it. Just put it in _items.

this._frozenMethods.map( function(v) {
  Object.defineProperty(obj, v, {
    enumerable: false,
    writable: false,
    configurable: false
  });
});

['_items', '_capacity', '_accessMap', '_frozenMethods','_size', '_functionalProps',
'_removeOldest','_updateAccessMap','_addNewItem'].map( function(v) {
  Object.defineProperty(obj, v, {
    enumerable: false,
    configurable: true
  });
});

map is a special iterator method. It runs on each array item and expects a return value for each item to form the new array it creates. If you just end us using it to loop through, then forEach is a better choice. Less confusing.

Additionally, naming variables properly is a must. Explicit is better than implicit, and naming your variables explicitly is better for readability than having to guess what they're for. It takes 5 seconds for a developer to know a purpose of a variable if named properly, rather than 5 mins because the developer has to read through the implementation.

this.delete = function(key) {

IIRC, IE8 and some other browsers have issues when using some keywords as property/function names. Best use alternative names like remove.

Anyways, here's a simplified implementation. Should be straightforward:

function LruCache(capacity){
  this._capacity = capacity || 1;
  this._accessMap = [];
  this._items = {};
}

LruCache.prototype.addItem = function(key, value){
  if(this._accessMap.length >= this._capacity) this.removeOldest();
  this._accessMap.push(key);
  this._items[key] = value;
};

LruCache.prototype.remove = function(key){
  this._accessMap.splice(this._accessMap.indexOf(key), 1);
  delete this._items[key];
};

LruCache.prototype.removeOldest = function(){
  var oldestKey = this._accessMap.shift();
  delete this._items[oldestKey];
};

LruCache.prototype.getCapacity = function(){
  return this._capacity;
};

LruCache.prototype.getSize = function(){
  return this._accessMap.length;
};

LruCache.prototype.getItems = function(){
  var instance = this;
  return Object.keys(this._items).reduce(function(carry, key){
    carry[key] = instance._items[key];
    return carry;
  }, {});
};

If you really want privates by way of closures and throw away the entire concept of shared methods, you can do this:

function LruCache(capacity){
  var _capacity = capacity || 1;
  var _accessMap = [];
  var _items = {};

  function removeOldest(){
    var oldestKey = _accessMap.shift();
    delete _items[oldestKey];
  };

  this.addItem = function(key, value){
    if(_accessMap.length >= _capacity) removeOldest();
    _accessMap.push(key);
    _items[key] = value;
  };

  this.remove = function(key){
    _accessMap.splice(_accessMap.indexOf(key), 1);
    delete _items[key];
  };

  this.getCapacity = function(){
    return _capacity;
  };

  this.getSize = function(){
    return _accessMap.length;
  };

  this.getItems = function(){
    return Object.keys(_items).reduce(function(carry, key){
      carry[key] = _items[key];
      return carry;
    }, {});
  };

}


If you want to duplicate GroupBy semantics exactly, there are several things missing:

Eager error checking on parameters instead of deferred
The correct order of the groups (GroupBy guarantees that the groups are ordered by the relative order of the group's first element in the source)
Allowing keys that are null

You may be interested in Jon Skeet's recent blog postings.


Counting letters, words, etc. in the input

About using namespace std;. It's best to just do, e.g., std::ifstream etc each time. There's a lot of stuff here, and even in this example it would have made it easier for me to see that std::ispunc was built-in, and not something you wrote for this.

Variable names: If your name is two words put together, you should use either snake_case or camelCase consistently. E.g. countletters -> countLetters. I'd find numLetters even more readable. Some people would even say you really ought to make it numberOfLetters. lab3 also ought to be more descriptive.

Arrange your code logically. First you declare lab3. Then you declare word. Then you declare a lot of other stuff. And finally, you make sure lab3 opened correctly. Doing all the ifstream stuff in one place makes it so much easier to read/fix later on. E.g.

std::ifstream input("lab3.txt");
if (!input)
{
    std::cerr << "Could not open file." << std::endl;
    return 1;
}

For reading the file, personally I would use std::getline, then split each line into a vector of "words." First of all, this would it easier to check whether to count something as a word (I think yours breaks on contractions.) And then you can just loop over each character of each word of each line for the small stuff.

Misc. std::ifstream's close() gets called by the destructor when it goes out of scope. No need to do it manually here. Your output says you have 4 sentences. You have 4 lines. Several more sentences. There's probably not much to do about it here, but whenever I see a whole bunch of variable definitions grouped together, my first thought is to move them closer to where they're actually used. But again they're already about as close as they can get here. You never use word.


Generate filter criteria based on multiple field combinations

Usually I tell at code reviews that saving a level of indentation is a good thing, but in the case of your code I wondered why you placed three times the same condition because I had a hard time to notice the !'s so I would suggest to take a different route, otherwise you will be confused in half a year as well.

I would use a `if..else if´ like so

if (searchConditions.FeeTypeId.HasValue)
{
    if (string.IsNullOrEmpty(searchConditions.FeeTypeName))
    {
        return new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value };
    }
    return new { TenantId, FeeTypeId = searchConditions.FeeTypeId.Value, searchConditions.FeeTypeName };
}
else if(string.IsNullOrEmpty(searchConditions.FeeTypeName))
{
    return new { TenantId };
}

return new { TenantId, searchConditions.FeeTypeName };


What you could do first is to separate out the logic that does the calculation from the logic that handles the UI. This makes it easier to update the math. Also, this makes the logic portable, should you scrap the UI code for something else, like if you move to use a framework.

Also, break up the logic to small functions that accept a predictable input. For instance, calculating shares is simply multiplying your inputs by your dividend - an array of input values and a number.

// In goes an array of hours and the dividend, out comes an array of shares
function getShares(hours, dividend){
  const sum = hours.reduce((c, v) => c + v);
  const rate = dividend / sum;
  const shares = hours.map(hour => hour * rate);
  return shares;
}

I also notice this strange E function which is just short for document.getElementById. There is document.querySelector and document.querySelectorAll that allows you to use CSS selectors to get a reference of your elements. Also, I'd avoid IDs since IDs should only appear once on the page. You can't use it for multiple elements of the same kind, for instance your inputs. Use classes instead.

For this case, I would tolerate the innerHTML usage. Otherwise, construct elements using document.createElement. Now to create repeated HTML, you can use array.map and array.join with template literals.

function renderResults(results){
  return results.map(result => `

${result.hours} x ${result.dividend} = ${result.share}

  `).join('');
}

For your HTML, while there are cases where the quotes on attributes are optional, it's best you put them in for consistency.


Using 503 page when my site is in maintenance mode

It looks good to me, but I do have one thing to say.

If I want to access http://yourdomain.com/example/page, and get a 503 error, I want to be able to refresh the page in a little while, to see if the 503 error is lifted.

What you do is redirect the user to the 503 page, which means that the address I'll get now if I refresh is http://yourdomain.com/503.php, this is not optimal.

Instead of redirecting, include the 503 error page.

Also some other things:

The error says 503, but your titles says "Page not Found"
Code indentation is important. Don't neglect it!
Never use an if block without curly brackets. Never.


First I would suggest to separate the code into two functions: One which computes the sum of odd divisors of a single number, and another which adds the odd divisors of all numbers in a list. Also, use better function names, and add at least a simple doc comment:

def oddDivisorSum(n):
    """Return the sum of odd divisors of n."""
    # ... to do ...

def totalOddDivisorSum(numbers):
    """Return the sum of all odd divisors of all numbers."""
    return sum(oddDivisorSum(n) for n in numbers)

This makes the code more clear, better reusable, and makes it easier to add test cases.

To make the computation faster, two observations help:

If \$k\$  is a divisor of \$n\$, then \$\frac{n}{k}\$ is also a divisor of  \$n\$.

This is what Oscar also said, and it allows to restrict the search for divisors to the interval  \$1\dots \sqrt n\$. The "problem" is that \$k\$ and \$\frac{n}{k}\$ can have different oddity.
If \$ k \$ is an odd divisor of an even number \$n\$ then \$k\$  is also an odd divisor of \$\frac{n}{2}\$.

Therefore, we can remove all even factors of \$n\$ first, and then find odd divisors in the reduced (odd) number. This makes the code simpler (because all divisors are odd) and faster for even numbers (a smaller \$n\$ means less trial divisions):

def oddDivisorSum(n):
    """Return the sum of odd divisors of n."""
    while n % 2 == 0:
        n //= 2
    sum = 0
    for k in range(1, int(n ** .5) + 1, 2):
        if n % k == 0:
            sum += k
            if n // k != k:
                sum += n // k
    return sum