One of your biggest performance issues is, using Mid to get one character from the string.  This gets the character as a string which is inefficient.  It would be better to get the character as a Char, by using the index operator of the String class(Str(j)).  To compare with literal characters use the character indicator(c)at the end of the string quotes("+"c).

Whenever you have code duplication try to find a way to break that code out into a separate function.  A case in point is when you are checking for operators in your string a simple function:

Private Function isOperator(chr As Char) As Boolean
    Return chr = "+"c OrElse chr = "-"c OrElse chr = "*"c OrElse chr = "/"c OrElse chr = ","c OrElse chr = ")"c
End Function

simplifies and unclutters your main code.

Whenever you have chained conditionals as above, use the shortcut boolean operators(OrElse and AndAlso).  This way a false result will return right away instead of reading the rest.

Don't use Len() to get the length of the string.  The String class has a length property that you can use and put into a variable.

Without any concrete examples of the complexity of the formulas that you're expecting, it's difficult to critique the efficiency of your approach.  I'm thinking though, that as a general rule, anytime you are doing extensive string manipulations you should definitely look at using a StringBuilder.

Simplified with these recommendations your code would look something like this:

Private Function _replacePower(Str As String) As String
    Const PowerString As String = "Pow({0},{1})"

    Dim i, j As Integer
    Dim c As Char
    Dim before, after, all As String
    Dim length As Integer = Str.Length
    Dim other_p As Integer 'Keep track of other opening/closing parenthesis, to avoid breaking for a nested one.

    other_p = -1
    i = 1
    While i <= length
        c = Str(i)
        If c = "^"c Then
            If Str(i - 1) = ")"c Then
                j = i - 1
                Do While Str(j) <> "("c Or other_p > 0
                    If Str(j) = ")"c Then other_p = other_p + 1
                    If Str(j) = "("c Then other_p = other_p - 1
                    j = j - 1
                Loop
                before = Mid(Str, j, i - j)
            Else
                j = i - 1
                'The expression to be raised is everything between the power and + - * / , ( <- Opening parenthesis is not ok if there is no closing one, and this case is handled above.
                Do While (Not isOperator(Str(j)))
                    j = j - 1
                    If j = 0 Then Exit Do
                Loop
                before = Mid(Str, j + 1, i - j - 1)
            End If

            other_p = -1

            If Str(i + 1) = "("c Or other_p > 0 Then
                j = i + 1
                Do While Str(j) <> ")"c
                    If Str(j) = ")"c Then other_p = other_p - 1
                    If Str(j) = "("c Then other_p = other_p + 1
                    j = j + 1
                Loop
                after = Mid(Str, i + 1, j - i)
            Else
                j = i + 1
                Do While (Not isOperator(Str(j)))
                    j = j + 1
                    If j = length + 1 Then Exit Do
                Loop
                after = Mid(Str, i + 1, j - i - 1)
            End If

            all = before & "^" & after
            Str = Replace(Str, all, String.Format(PowerString, before, after))
            i = 1
        End If
        i = i + 1
    End While
    Return Str
End Function

Private Function isOperator(chr As Char) As Boolean
    Return chr = "+"c OrElse chr = "-"c OrElse chr = "*"c OrElse chr = "/"c OrElse chr = ","c OrElse chr = ")"c
End Function

I took a more in depth look at your code, and realized there were quite a few more improvements that could be made.

Don't be afraid to be verbose with your variable names.  If you're worried about extra typing, Intellisense will bring up suggestions as you type, allowing you to just tab over the suggestion you want, instead of typing it all out.

You seem to do a lot of checking for different types of characters. Really all you need to check for is digits and brackets.

When checking for matching brackets, it is useful to have a `Dictionary(Of, Char, Integer)'.  Opens are +1, closings are -1.

The Char class has an IsDigit function that simplifies checking for those.

There is another large code duplication when you check to the left and the right of the caret to get the appropriate strings.

You didn't mention whether there is a possibility of more than one caret symbol in a string.  It seems logical that this could be a possibility.  My though is make the function recursive to keep checking the returned string for caret's.

Putting this all together, you might come up with something like this:

Private Function FixString(value As String) As String
    Dim caretIndex = 0
    caretIndex = value.IndexOf("^"c)
    If caretIndex <> -1 Then
        Dim sb As New StringBuilder()
        Dim leftHand = ""
        Dim rightHand = ""
        Dim leftHandIndex = 0
        Dim rightHandIndex = 0
        leftHandIndex = caretIndex - 1
        rightHandIndex = caretIndex + 1
        leftHand = getString(value, caretIndex, leftHandIndex, -1)
        rightHand = getString(value, caretIndex, rightHandIndex, 1)
        sb.AppendFormat("{0}Pow({1},{2}){3}", value.Substring(0, leftHandIndex + 1), leftHand, rightHand, value.Substring(rightHandIndex))
        Return FixString(sb.ToString)
    Else
        Return value
    End If
End Function

Private Function getString(value As String, caretIndex As Integer, ByRef offset As Integer, increment As Integer) As String
    Dim bracketTotal = 0
    Dim index = offset
    If Char.IsDigit(value(index)) Then
        While index <> value.Length AndAlso Char.IsDigit(value(index))
            index += increment
        End While
    ElseIf brackets.ContainsKey(value(index)) Then
        bracketTotal += BRACKETS(value(index))
        index += increment
        While index <> value.Length AndAlso bracketTotal <> 0
            If BRACKETS.ContainsKey(value(index)) Then
                bracketTotal += BRACKETS(value(index))
            End If
            index += increment
        End While
    End If
    offset = index
    If increment = -1 Then
        Return value.Substring(index + 1, caretIndex - index - 1)
    End If
    Return value.Substring(caretIndex + 1, index - caretIndex - 1)
End Function

Private ReadOnly BRACKETS As Dictionary(Of Char, Integer) = New Dictionary(Of Char, Integer)() From
{
     {")"c, -1},
     {"("c, 1}
}

I didn't see anything in your code, that would suggest the possibility of badly formatted strings, so I assumed that validation was being handled elsewhere.


How to properly detect multiple devices failure?

I think your enum is taking naming conventions, making a little paper ball out of it, and throwing it out the window.

An enum is a type. As such, its name should be PascalCase. Enum members are, well, public members of a type. As such, their names should be PascalCase as well.

Consider:

enum ErrorCode
{
    MotorA    = 0x0000001,
    MotorB    = 0x0000010,
    Serial    = 0x0000100,
    Lan       = 0x0001000,
    MainBoard = 0x0010000,
    Generator = 0x0100000,
    Max = 6
}

A number of things are not clear:

Why use a hexadecimal representation of the values?
Why is 6 not represented as hex, too?
Is Max supposed to represent all 6 bit flags turned on?

  We have made an ID for every class and put a base 2 number...

No, you haven't. Your numbers are hexadecimal numbers, they're base-16.

Consider:

[Flags]
enum ErrorCode
{
    None = 0,
    MotorA = 1,     // 2^0, or 1 << 0
    MotorB = 2,     // 2^1, or 1 << 1
    Serial = 4,     // 2^2, or 1 << 2
    Lan = 8,        // 2^3, or 1 << 3
    MainBoard = 16, // 2^4, or 1 << 4
    Generator = 32, // 2^5, or 1 << 5
    Max = MotorA | MotorB | Serial | Lan | MainBoard | Generator
}

Take a look at this comment on SO:

  Flags itself does nothing. Also, C# does not require Flags per se. But the ToString implementation of your enum uses Flags, and so does Enum.IsDefined, Enum.Parse, etc. Try to remove Flags and look at the result of MyColor.Yellow | MyColor.Red; without it you get "5", with Flags you get "Yellow, Red". Some other parts of the framework also use [Flags] (e.g., XML Serialization). –  Ruben Aug 17 '09 at 17:30

This means the [Flags] attribute changes how ToString() represents an ErrorCode value. Your code breaks the type safety and treats the enum as an int, but you could do this as well:

ErrorCode ConnectToEveryDevice()
{
    var result = ErrorCode.None;
    foreach(IDevices device in this.Devices)
    {
         result = result | device.Connect();
    }
    return result;
}

Then the return value of this method could be made meaningful to a user, simply with a ToString() call:

var result = ConnectToEveryDevice();
var resultString = result.ToString();

Where resultString holds "MotorA, MainBoard, Generator" if MotorA, MainBoard and Generator are in an error state.


rollDieN doesn't look very random to me

*Risk> map unDV $ rollDieN 100
[5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,
 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6]

This looks better:

*Risk> map unDV $ evalRand (replicateM 100 die) (mkStdGen 123456)
[4,5,2,3,5,6,2,3,2,5,4,5,5,5,1,1,6,6,2,3,2,5,5,3,4,1,3,1,
 3,2,4,4,3,2,2,6,2,2,3,1,6,6,4,5,3,6,6,6,5,2,2,1,6,3,6,3,
 6,3,6,5,6,5,1,1,1,2,1,5,4,4,3,3,3,3,3,3,4,5,5,2,4,1,5,4,
 4,2,1,1,5,1,4,2,6,5,3,5,2,3,6,1]

Now we can write a function that will return the two army's dice rolls

rollDice n = replicateM n die

battleTest :: Battlefield -> Rand StdGen ([Int], [Int])
battleTest battlefield = do
    attackerRolls <- rollDice $ getLegalAttackers (attackers battlefield)
    defenderRolls <- rollDice $ getLegalDefenders (defenders battlefield)
    return (map unDV attackerRolls, map unDV defenderRolls)

And check that our output looks sane

*Risk> evalRand (battleTest (Battlefield 10 20)) (mkStdGen 12)
([6,3,2],[5,1])
*Risk> evalRand (battleTest (Battlefield 10 20)) (mkStdGen 123456)
([4,5,2],[3,5])

Now assuming a function to update the battlefield based on dice rolls, we just change it to

battle :: Battlefield -> Rand StdGen Battlefield
battle battlefield = do
    attackerRolls <- rollDice $ getLegalAttackers (attackers battlefield)
    defenderRolls <- rollDice $ getLegalDefenders (defenders battlefield)
    return $ nextBattlefield attackerRolls defenderRolls battlefield

There's also a problem with getLegalDefenders. The homework says

  The defending player may defend with up to two units (or only one if
  that is all they have).

So instead of

getLegalDefenders :: Army -> Army
getLegalDefenders n
  | n >= 4    = 2
  | n == 3    = 1
  | otherwise = 0

It should look like

getLegalDefenders :: Army -> Army
getLegalDefenders n
  | n >= 2    = 2
  | n == 1    = 1
  | otherwise = 0

Or

getLegalDefenders n = max 0 (min 2 n)


How can I enhance my linkedlist implementation in java?

1 Coding conventions

In Java, you should keep the opening curly brace on the same row as the token it relates to. Instead of writing

public void add(int data)
{
    ...
}

...
else
{
    ...
}

you should write

public void add(int data) {
    ...
}

...
else {
    ...
}

What comes to other conventions, you should have a single space between if-keyword and the opening parenthesis of the condition. Instead of

if(foo(bar)) ...

you should write

if (foo(bar)) ...

Also, what comes to the if keyword, you should have another single space between the closing parenthesis of the condition and the opening curly brace. So, instead of

if (foo(bar)){
    ...
}

you should write

if (foo(bar)) {
    ...
}

Now, I suggest you do not write more than one statement on a single line. Instead of

{head = n; tail = n;}

it would be nicer to write

... {
    head = n;
    tail = n;
}

2 Field initializers

The following is superfluous:

Node head = null;
Node tail = null;
int size = 0;

By default, Java initializes the object fields to null and integer fields to 0. Also, they must be declared private, since otherwise whatever is in your package, it may tamper with the fields. So, you should write

private Node head;
private Node tail;
private int size;

3 class Node

I think it would be a better idea to declare Node as a private static inner class of LinkedList (see Summa summarum for details). Also, I would rename data to datum since it is the singular form of the word. Also, datum/data may be declared final since it is not modified. Moreover, you could declare both data and next as private and provide appropriate getters and setters.

4 printList

The conventional way to do what you do in printList is to override the Object.toString method returning a string representing the contents of your list.

5 remove*

Your list would be more useful, if your remove* methods returned the datum removed from the list.

6 size()

Printing the current size of the list to standard output is not a good idea. Instead, just return the size and let the caller do whatever (s)he wants with it (for example, print it to console).

Summa summarum

Putting all pieces together, I had this implementation in mind:

package datastructures;

import java.util.NoSuchElementException;

public class LinkedList {

    private Node head;
    private Node tail;
    private int size;

    private static final class Node {

        private final int datum;
        private Node next;

        Node(final int datum) {
            this.datum = datum;
        }

        int getDatum() {
            return datum;
        }

        Node getNext() {
            return next;
        }

        void setNext(Node n) {
            this.next = n;
        }

    }

    public void add(final int datum) {
        Node node = new Node(datum);

        if (head == null) {
            head = node;
        } else {
            tail.setNext(node);
        }

        tail = node;
        size++;
    }

    public int size() {
        return size;
    }

    public void addFirst(int datum) {
        Node node = new Node(datum);

        if (head == null) {
            tail = node;
        } else {
            node.setNext(head);
        }

        head = node;
        size++;
    }

    public void addLast(int datum) {
        add(datum);
    }

    public int removeFirst() {
        if (size == 0) {
            throw new NoSuchElementException("Removing from an empty list.");
        }

        final Node firstNode = head;
        head = head.getNext();
        size--;
        return firstNode.getDatum();
    }

    public int removeLast() {
        if (size == 0) {
            throw new NoSuchElementException("Removing from an empty list.");
        }

        final Node lastNode = tail;
        Node previous = null;
        Node current = head;

        while (current.getNext() != null) {
            previous = current;
            current = current.getNext();
        }

        tail = previous;

        if (tail != null) {
            tail.setNext(null);
        }

        size--;
        return lastNode.getDatum();
    }

    @Override
    public String toString() {
        if (size == 0) {
            return "[]";
        }

        final StringBuilder sb = new StringBuilder("[");
        sb.append(head.getDatum());
        Node node = head.getNext();

        while (node != null) {
            sb.append(", ").append(node.getDatum());
            node = node.getNext();
        }

        return sb.append("]").toString();
    }

    public static void main(String args[]) {
        LinkedList l = new LinkedList();
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
        l.add(6);
        l.add(7);
        l.add(8);
        l.addLast(9);
        l.addFirst(0);
        System.out.println(l);

        System.out.println("Head Node is " + l.head.getDatum());
        System.out.println("Tail Node is " + l.tail.getDatum());
        l.size();

        System.out.println("\\\\\\\\\\\\\\\\Before removing the first element////////");
        System.out.println("");

        System.out.println("\\\\\\\\\\\\\\\\After removing the first element and removing the last element////////");
        System.out.println("");

        l.removeFirst();
        l.removeLast();
        System.out.println(l);
        System.out.println("Head Node is " + l.head.getDatum());
        System.out.println("Tail Node is " + l.tail.getDatum());
        l.size();
    }
}

Hope that helps.


Mapping a product its corresponding image file

I am going to shorten up some of your code a little bit,

if ($this->isCustom($product)){
            $image_path = PRODUCT_IMAGE_PATH . $this->order['order_number'] . $index . '.jpg';
            $index++;

            if (!$this->checkRemoteImage($image_path)){
                return "No Image";
            }
            return $image_path;
        }

        else{
            $image_path = PRODUCT_IMAGE_PATH . $product['sku'] . '.jpg';

            if (!$this->checkRemoteImage($image_path)){
                $this->notifyOnNonCustoms($image_path);
                return "No Image";
            }
            return $image_path;
        }
    }

you should allow your image path variable to live a little longer and use it to return once.

this is kind of what I was thinking

if ($this->isCustom($product)){
    $image_path = PRODUCT_IMAGE_PATH . $this->order['order_number'] . $index . '.jpg';
    $index++;

    $image_path = $this->checkRemoteImage($image_path) ? "No Image" : $image_path;
}
else{
    $image_path = PRODUCT_IMAGE_PATH . $product['sku'] . '.jpg';

    if (!$this->checkRemoteImage($image_path)){
        $this->notifyOnNonCustoms($image_path);
        $image_path = "No Image";
    }
}
return $image_path;

a little less indentation inside the if statement block.  I couldn't do much with the else statement block.

Your first set of code is nice in that it creates the path and checks it, but it evaluates

$this->isCustom($product)

twice in some circumstances, and you don't want that because it adds more operations to your algorithm.

Your second set of code is much more precise, it still only creates the $image_path once, but does it differently depending on the value of the truthy statement.  also you have different operations that need to be done for custom and not custom if the image path doesn't exist.

Your second block of code is better than the first.


Template function which determines how to move-assign a type

I think you're putting the cart before the horse here.

  I am manipulating some heterogeneous containers of user-defined types.
  I desperately need to be able to move-assign these types without generating exceptions.

Let's say your container is a Cart<T>. And you need to define a move-assignment operator

Cart<T>& Cart<T>::operator=(Cart<T>&& rhs) noexcept;

Well, if Cart behaves like std::vector, then you could implement this as something like

Cart<T>& Cart<T>::operator=(Cart<T>&& rhs) noexcept
{
    delete [] this->pointer_to_Ts;
    this->pointer_to_Ts = rhs->pointer_to_Ts;
    rhs->pointer_to_Ts = nullptr;
}

Notice that this does not require T's own move-assignment operator at all; T might not even be movable! The only user-defined function we're executing here is T's destructor (and if that throws, we're in trouble anyway).

But okay, let's suppose that you're implementing Cart's move-assignment operator like this instead:

Cart<T>& Cart<T>::operator=(Cart<T>&& rhs) noexcept
{
    for (int i=0; i < n; ++i) {
        this->array_of_Ts[i] = std::move(rhs->array_of_Ts[i]);
    }
}

So now you're calling a ton of user-defined functions (well, just one function, but you're calling it n times). This is already violating the spirit of move-semantics, in that moving is supposed to be a fast operation, but we'll let that slide.

What should you do if T's move-assignment operator is defined as noexcept? Well, you're golden. Everything will work fine.

What should you do if T's move-assignment operator is not defined as noexcept, but doesn't throw in practice? Well, you're golden. Everything will work fine in practice. If it ever accidentally does throw an exception, then your program will call std::terminate and (presumably) exit. This seems like a good idea in most cases. If you really can't afford to call std::terminate when something as terrible as "move-assignment throws an exception" happens, then I bet you're coding to some strict government standards that will preclude the existence of non-noexcept move-assignment operators in the first place.

What should you do if T's move-assignment operator is explicitly defined as noexcept(false)? Well, you should probably go find the person who wrote that code and shoot them in the face. (Politely, of course.)

Now the unfortunate bit: It's actually impossible to tell in C++14 (and C++17 as well, AFAIK) whether a given function has been declared noexcept(false) or merely non-noexcept. So your code won't ever be able to distinguish case 2 above ("you're golden, in practice") from case 3 above ("you have to shoot somebody in the face") — it's useless to try.

So, should you go gray worrying about case 3? IMHO you should not. Just assume that every instance of case-2-or-3 in your codebase is really a case-2; and then write your code accordingly. It'll be simple and straightforward and efficient, and if you ever run into a throwing move-assignment operator, well, by definition it's the user who wrote the bad code, not you.

This is not the philosophy that led to the current pessimal behavior of std::vector::resize. I'll let someone else take a stab at explaining that philosophy, because I don't understand it at all.


Making a .bat batch command-line interface

You can use a FOR /F to parse out the command from the arguments.

I would define a variable containing a delimited list of all valid commands. Then you can use simple search and replace to validate whether the user entered command is valid.

Addition of a new command is as easy as adding the command to the list, and creating a labeled subroutine for the new command.

I would use CALL instead of GOTO so that each routine can easily parse the arguments. The only disadvantage is CALL will double up quoted carets ("^" becomes "^^")

Here is a basic framework that can easily be extended. Note that user entered ! will be corrupted (or expanded) because of delayed expansion. There are simple ways to get around this limitation with additional code.

@echo off
setlocal enableDelayedExpansion
echo Simple command-line interface
echo(

:: Define all valid commands: make sure there is a space between each command
:: and also one at beginning and end
set "commands= something echo exit "

:input.get

:: Clear the existing value in case user hits <Enter> without entering anything
set "input="

:: Get the next command
set /p "input=COMMAND\>"

:: Parse command into command and arguments.
for /f "tokens=1* delims= " %%A in ("!input!") do (

  REM check if command is valid (not case sensitive) and act accordingly
  if "!commands: %%A =!" equ "!commands!" (
    echo Invalid command: %%A
  ) else if /i %%A equ exit (
    exit /b
  ) else (
    call :%%A %%B
  )
)
echo(
goto input.get

:something
echo Doing something with Arg1=[%1] and Arg2=[%2]
exit /b

:echo
echo(%*
exit /b


Project Euler problem 23 - non-abundant sums

1. Sieving for sums

The computation of the sum of divisors can be improved using a bit of math. Let's call the sum-of-divisors function \$σ\$, and consider \$σ(60)\$: $$ σ(60) = 1 + 2 + 3 + 4 + 5 + 6 + 10 + 12 + 15 + 20 + 30 + 60. $$ Collect together the divisors by powers of 2: $$ \eqalign{σ(60) &= (1 + 3 + 5 + 15) + (2 + 6 + 10 + 30) + (4 + 12 + 20 + 60) \\ &= (1 + 2 + 4)(1 + 3 + 5 + 15) \\ &= (1 + 2 + 4)σ(15)}. $$ Then do the same thing for \$σ(15)\$, collecting together the divisors by powers of 3: $$ \eqalign{σ(15) &= (1 + 5) + (3 + 15) \\ &= (1 + 3)(1 + 5) \\ &= (1 + 3)σ(5)}. $$ And so on, getting \$σ(60) = (1 + 2 + 4)(1 + 3)(1 + 5)\$. In general, if we can factorize \$n\$ as: $$ n = 2^a3^b5^c\dotsm $$ then $$ σ(n) = (1 + 2 + \dotsb + 2^a)(1 + 3 + \dotsb + 3^b)(1 + 5 + \dotsb + 5^c)\dotsm $$ These multipliers occur many times, for example \$(1 + 2 + 4)\$ occurs in the sum of divisors of every number divisible by 4 but not by 8, so it's most efficient to sieve for the sums of many divisors at once, like this:

def all_sum_divisors(n):
    """Return a list of the sums of divisors for the numbers below n.

    >>> all_sum_divisors(10) # https://oeis.org/A000203
    [1, 1, 3, 4, 7, 6, 12, 8, 15, 13]

    """
    result = [1] * n
    for p in range(2, n):
        if result[p] == 1: # p is prime
            p_power, last_m = p, 1
            while p_power < n:
                m = last_m + p_power
                for i in range(p_power, n, p_power):
                    result[i] //= last_m
                    result[i] *= m
                last_m = m
                p_power *= p
    return result

2. Review

I would change the signature of the function as follows:

def solve_euler23(n=28124):
    """Return the sum of all positive integers below n which cannot be
    written as the sum of two abundant numbers."""

The reason for doing this is to make it possible to test the function on small instances: for example, you could test the claim in the problem statement (that 24 is the smallest number that cannot be written etc.), by running solve_euler23(24) and checking that it returns \$ \sum_{1≤i<24}i=276 \$, and then running solve_euler23(25) and checking that it returns the same result.
The division operator / returns a float in Python 3, so for portability it would be worth writing:

MAX_DIVISOR = MAX_TEST_ABUNDANT // 2

The efficiency gain of avoiding computing the sum of divisors of the numbers up to SMALLEST_ABUNDANT (12) is negligible, and it deprives you of the chance to check that your sum-of-divisors algorithm is correct on small numbers (for example, an off-by-one error might lead it to deduce that 6 is abundant, but if you started at 12 you might have trouble spotting the bug).
The question only asks for the sum of the positive integers which cannot be written as the sum of two abundant numbers, so it's not necessary to keep a list of the numbers themselves.
When looking for sums adding up to number, the code tests every abundant number:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in abundant_numbers:
        if number - abundant in abundant_numbers_set:
            break

but we only need to test abundant numbers up to number // 2 (if two abundant numbers add up to number, then one of them will be no more than number // 2). We could test for this in the loop:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in abundant_numbers:
        if number - abundant in abundant_numbers_set:
            break
        else if abundant >= number // 2:
            impossible_sum_of_two_abundant_numbers.append(number)
            break

but because abundant_numbers is sorted, we can quickly calculate how far along this list we need to go, using bisect.bisect and itertools.islice:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in islice(abundant_numbers,
                           bisect(abundant_numbers, number // 2)):
        if number - abundant in abundant_numbers_set:
            break

3. Revised code

from bisect import bisect
from itertools import islice

def solve_euler23(n=28124):
    """Return the sum of all positive integers below n which cannot be
    written as the sum of two abundant numbers.

    """
    sum_divisors = all_sum_divisors(n)
    abundant = [i for i in range(1, n) if sum_divisors[i] > 2 * i]
    abundant_set = set(abundant)
    def unsums():
        for i in range(1, n):
            for j in islice(abundant, bisect(abundant, i // 2)):
                if i - j in abundant_set:
                    break
            else:
                yield i
    return sum(unsums())

I find this is about three times as fast as the code in the original post.


Building a dynamic dictionary mapper inside function

We can do a dictionary comprehension and avoid code repetition:

NAMES = ['aAbreu', 'cGreen', 'lCessa', 'aJudge', 'jEllsbury']
ATTRIBUTES = ['firstname', 'lastname', 'address', 'phone_number', 'company', 'position']
for name in NAMES:
    full_name = mapping.get(name)
    obj.information.update({
        f'{name}_{attr}': mapping.get(attr).format(full_name)
        for attr in ATTRIBUTES
    })

Note the use of an f-string for the key definition.

And, aside from that, I think you can remove the information variable as it is unused.

And, both my and your versions of the code don't handle missing keys situation - what if there is no such key in mapping?


Decimal-to-binary converter for IP addresses

Code simplification and related:

Line 4: remove line 3 and replace line 4 with

ip_array = filter(None, ip.split('.'))

Line 7:
Create an exception, to prevent that a caller gets a string of error instead of the actual result.

Line 12: assuming this is not python3, it's better if you use xrange() instead of range(), because range would create an actual list listing all the items in specified range. xrange(), instead, returns the next item in the sequence without creating the list. This behaviour is the same as the range() function in python3.
Anyway, for your purposes changing it with:

for el in ip_array:
    ip_bin.append('{0:08b}'.format(int(el)))

or, even better:

ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]

Last line:
instead of appending the "." after each element, join over the dot:

return '.'.join(ip_bin)

Style:
Pursue consistency in all the code: if you use double-quotes for defining strings, use them everywhere, same thing with single-quotes (which i personally prefer for strings, reserving double ones for docstrings).

Reassuming:

def dec_to_bin(ip):

    ip_array = filter(None, ip.split('.'))

    if len(ip_array) != 4:
        raise NotValidIPException('Invalid IP Address format.')
    else:
        ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]
        return '.'.join(ip_bin)


Method to re-open a connection on a datacontext if it has gone down

First off, not sure I fully understand why you're doing this but taking that as a given here are some tips to make your code a bit more readable and concise.

Namespaces

Unless you have conflicts with other namespaces, I'd suggest adding using System.Data; and using System.Data.Linq; to the top of you file. If you do have a conflict and you created it yourself (not from a 3rd-party library) I'd suggest changing the name so there isn't a conflict if possible. Just makes things easier.

Method Extensions

Those if-statements you've got are kind of ugly. You could create a couple of method extensions for the DataContext class like this.

public static class DataContextExtensions
{
    /// <summary>
    /// Checks that the context and its connection are not null.
    /// </summary>
    public static bool HasContextAndConnection(this DataContext dataContext)
    {
        return dataContext != null
            && dataContext.Connection != null;
    }

    /// <summary>
    /// Checks if the context's connection is broken or closed.
    /// </summary>
    public static bool IsConnectionClosedOrBroken(this DataContext dataContext)
    {
        // NOTE: You can add the above null-checks to this one so that this
        // function doesn't throws a NullReferenceException if called before the other.
        return dataContext.Connection.State == ConnectionState.Closed
            || dataContext.Connection.State == ConnectionState.Broken;
    }
}

Try-Catch

You should be intentional with your code, having a wide-open try/catch states to whoever is reading it "The person who coded this has no idea what could possibly go wrong with it." (or more commonly, "I'm too lazy to list out what could go wrong."). So not only does it make you look bad, but it also doesn't provide any information to the reader/maintainer of what is expected to go wrong.

So then you should look into what could go wrong. Well, we're already doing null-checks so there shouldn't be any NullReferenceExceptions. That leaves the Dispose() method and the Activator.CreateInstance being the only other two possibilities.

According to the IDisposable.Dispose() MSDN page, Dispose should never throw an exception. Additional StackOverflow reference here too. So we should be good there.

Activator.CreateInstance however, could throw a handful of exceptions and you don't have a try-catch around that. Here's the MSDN page that outlines the exceptions that could be thrown.

Result

private void OpenConnection<T>(DataContext dataContext, string connectionString)
    where T : DataContext
{
    // DISPOSE: Clean up the existing context if the connection is closed or broken.
    if (dataContext.HasContextAndConnection() && !dataContext.IsConnectionClosedOrBroken())
    {
        dataContext.Dispose();
        dataContext = null;
    }

    // CREATE: Instantiate a new context given the connection string.
    if (dataContext == null)
    {
        var type = typeof(T);

        try
        {
            dataContext = Activator.CreateInstance(type, connectionString);
        }
        catch (TargetInvocationException)
        {
            // Constructor threw an exception.
        }
    }
}

Personal Touch

Personally, I like adding the header comments you see above. Where the all-caps part is a quick 1-2 word description of the section and everything after is a bit more detailed. I find it helps me scim code faster, however that is something that needs maintained when code is changed.


Designing a stack such that getMin() is both constant time and constant space

If the grader is complaining about "time limit exceeded," it must be because some loop is executing too many times. All of your functions are clearly O(1) — they have no loops. So which loop is executing too many times? It must be the only loop in the entire program:

    while(!isFull(n)){
        cin>>a;
        push(a);
    }

Is it possible that your isFull is returning an incorrect answer? It's very straightforward: it tests s.size() == n. Is it possible that push(a) is not updating s.size()?

Reflowed for brevity and clarity, your push looks like this:

void push(int a)
{
     if (s.empty()) {
         minEle = a;
         s.push(a);
     } else if (a < minEle) {
         s.push(a - minEle);
         minEle = a;
     } else if (a > minEle) {
         s.push(a);
     }
}

Do you see the bug yet? The problem is that when a == minEle, you never push anything! So if you get the input 1 1, you'll cause the test driver to loop forever... and that is what causes the timeout.

Also consider that there is no limit on the values of the integers you're given (just on the number of test cases T and the number of integers per test case N). So you'll have to find a way to make your code work with input -1 as well.

Consider maintaining a second stack std::stack<int> minEle alongside your std::stack<int> s. Does that make the problem easier?

EDITED TO ADD: If you kept the current push, then you could rewrite it for even more clarity by factoring the s.push to the bottom of the function, like this:

void push(int a)
{
     if (s.empty()) {
         minEle = a;
     } else if (a < minEle) {
         a -= std::exchange(minEle, a);
     } else if (a > minEle) {
         // do nothing
     } else {
         return;  // uh-oh!
     }
     s.push(a);
}

This shows clearly that each call to push results in one and only one call to s.push (except for the buggy case).


A Text-Based Browser using Requests, Beautiful Soup, Sys, OS, and colorama

Use argparse

Argparse will give you cleaner code and a friendlier CLI. It will simplify much of this blob:

dir_name = ''
if len(sys.argv) == 2:
    dir_name = sys.argv[1]
    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
path = dir_name + '/' if dir_name else ''

Also, for path handling and directory creation consider the use of pathlib.Path.

write_path

You're passing an URL into what you've called the file parameter, so that's confusing. Also, it appears that you're manually parsing that URL using split when you're better off using urllib.parse.

Ternary

This:

_ = text_list.append(txt + '\n') if len(txt) > 2 and not txt.startswith(('$', '.', '@')) else 0

should be expanded out into a plain if:

if len(txt) > 2 and not txt.startswith(('$', '.', '@')):
    text_list.append(txt + '\n')

Similarly, this:

    _ = [print(line, end='') for line in content]

is doing a comprehension and throwing away the result. Instead,

print(''.join(content))

Error handling

response = requests.get(page, headers={'user-agent': 'Mozilla/5.0'}, timeout=5)
if not response:
    raise Exception

First, never raise a base Exception - you want to raise something more specific. That said, in this case, replace your if with a response.raise_for_status().

In a similar case,

if '.' not in url:
    raise Exception

should instead be raising something like ValueError(f'Malformed URL {url}'). It's also odd that this is referring to the global url variable instead of the page argument. Finally: to do this kind of validation (not sure why it matters that there's a dot in the URL), you should be using urllib.parse.

Global code

Pull everything from history_stack = [] onwards into one or more functions.


Extending prototype of given instance from factory method

Prototypal Inheritance
Now, the very first problem you'll face in your implementation is memory usage. Each RubberBall instance will be creating an internal function - that's a bad thing:
function RubberBall(){
  this.someFn = function(){...}
}

In this sample code above, each RubberBall instance will create its own someFn. Functions are also objects in JS and will take up memory.
The proper way to do it in JS is to place those methods in the prototype, so that they are shared in all instances of RubberBall. This is what we call prototypal inheritance Do note that we are only placing/sharing the methods. Instance data remains in the instance:
function RubberBall(){
  // ballData gets created *per instance*
  this.ballData = 'I am bouncy';
}

// Assign a prototype object, shared accross all instances of RubberBall
RubberBall.prototype = {
  getData : function(){
    // If called as `[instance].getData()`, `this` is the instance.
    return this.ballData;
  }
}

As far as I've read (but I may be wrong), the V8 engine optimizes objects via hidden classes, and are more optimized if you declare all instance properties in advance. That way, it does not do some "run-time rebuilding". So have your rubber ball properties declared in advance.
Now, you wanted to extend Box2D's b2Body (I'm not well versed in Box2D so pardon my vocabulary). The previous example does not yet inherit it. So [we use the more proper Object.create][2] to create an object that has b2Body in its prototype. Let's modify the previous example:
function RubberBall(){
  // Attach to this instance all properties of b2Body
  b2Body.call(this);

  this.ballData = 'I am bouncy';
}

// Now create our prototype object, with its prototype pointing to b2Body's prototype
RubberBall.prototype = Object.create(b2Body.prototype);

// Then attach methods to it
RubberBall.prototype.getData = function(){...}
RubberBall.prototype.anotherSharedMethod = function(){...}

Private members
JS wasn't designed to have private members, but there are a lot of ways to emulate it (and I think ES6 has something more formal for it). You can create closures, which are fast, but if not handled properly, might eat memory.
So let's stick to prototypal inheritance and public members. If you need to indicate that it's private, by convention you can prefix the property or method with a _.
requestAnimationFrame
Modern browsers are now equipped with requestAnimationFrame which is a special timer that executes a given function as fast as possible, aiming 60fps. It's also optimized to throttle it's speed in different situations, like slowing down when the tab is not focused to save battery.
There are polyfills that automatically fill in the gap, especially for older browsers that don't have it.
Standard Reminders

Don't use globals
Place everything you do in a namespace or an enclosed scope
Keep your code short and readable
Use proper indentation


MySQL query to select messages related to a user

Some thoughts:

You should consider using prepared statements.
Remove $chat_type as parameter, as it is not used
Consider stronger validation on $page_type() parameters(like that is it null or integer). Right now you can easily break the function
Don't use * selects.  They don not help the code reader understand what sort of data is being returned without having to look a database.  They also tend to cause more bandwidth consumption than is necessary and make your queries fragile.  What if you add a new audit field to the database table?  That could then break your object instantiation later in the code if an unexpected field shows up or cause you to go modify that object's class for some reason that is unrelated to what that object does.
Consider COALESCE instead of IFNULL for determining conditional values (this is more suitable function in that it does not have potentially hidden value typing behavior). This is probably more common as well amongst MySQL developer types.
Write your query in a more readable form (not a series of concatenations, drop unnecessary parenthesis, ne consistent around using backticks, and capitalization of reserved words, etc.)

For example:

SELECT
    direct_message.{field} AS {field_alias},
    {other fields you need} AS {field_aliases},
    COALESCE (direct_message_group.staff_id, 0) AS staff_id
FROM direct_message
LEFT JOIN direct_message_group
    ON direct_message_group.chat_id = direct_message.id
INNER JOIN direct_message_thread
    ON direct_message_thread.chat_id = direct_message.id
WHERE
    (
        direct_message.recipient_id = ?
        OR direct_message.creator_id = ?
        OR (
            direct_message_group.staff_id = ?
            AND direct_message_group.active = '0'
        )
    )
    AND direct_message.school_id = ?
    AND direct_message_thread.school_id = direct_message.school_id
GROUP BY direct_message.id
ORDER BY direct_message_thread.inserted DESC
LIMIT ?, ?

Here I have applied named parameters instead of you string concatenation.

You query makes you relationship between tables seem unclear. On one hand you join direct_message to direct_message_thread on some sort of chat id value, yet you also put in a WHERE condition that school id's for these records on these tables must be equal.  Should this just be a part of the join condition as opposed to WHERE clause filter?
addslashes() may not be appropriate for escape purposes and it is not being used to escape $start (offset value).  I would suggest you either use prepared statements or an appropriate DB-connector-specific escape functionality. Also, if you know the values of your class methods calls are going to be integers, for example, do you really need to escape these?
You object instantiation for direct_message class seems weird.  Why not pass the row data upon instantiation rather than having to call separate _populate() method with the data?  Why start that method name with an underscore?  Consider UpperFirstCamelCase for all class/interface names instead of snake_case.


PHP: checking for $_GET variables with if statements

If it's a small app something like that would probably be better:

$getvar = isset($_GET['getvar']) ? $_GET['getvar'] : 'somedefault';

If you want to test more stuff:

$getvar = isset($_GET['getvar']) && $JUST_PUT_IT_HERE ? $_GET['getvar'] : 'somedefault';


Some error messages may be confusing like:

$ mkcd /foo/../bar
mkcd:cd:3: no such file or directory: /foo/..
$ mkcd /bin/../bar
mkdir: cannot create directory `./bar': Permission denied

Probably not much you can do about that.


Choosing the desired icon when fetching results

Extract Duplication to Function

You could try to extract some of the duplication:

getCheckIconHTML($color) {
    return "";
}

Now all the check icon HTML is in one place, which also makes it easier to change.

But the HTML really doesn't only depend on the color, but it also matters if it is clickable or not, so lets add that as well:

getCheckIconHTML($color, $isClickable) {
    $checkIcon = "";
    if ($isClickable) {
        $checkIcon = "" . $checkIcon . "";
    }
    return $checkIcon;
}

Improve the ifs

Now, the foreach would look like this, which is already better:

foreach ($results as $result){

    if ($_SESSION['id'] == $author_id) {            // User is logged
        if ($result['id'] == $AcceptedAnswerId) {
            $AcceptAnswerIcon = getCheckIconHTML('green', true);
        } else {
            $AcceptAnswerIcon = getCheckIconHTML('grey', true)
        }
    } else {      // User isn't logged
        if ($result['id'] == $AcceptedAnswerId) {
            $AcceptAnswerIcon = getCheckIconHTML('green', false);
        } else {
            $AcceptAnswerIcon = null;
        }
    }
}

But now that we have the function, we can also restructure the ifs to get this:

$isUserLoggedIn = ($_SESSION['id'] == $author_id);
if ($result['id'] == $AcceptedAnswerId) { // There is accepted answer
    $AcceptAnswerIcon = getCheckIconHTML('green', $isUserLoggedIn);
} else {
    $AcceptAnswerIcon = $isUserLoggedIn ?
            getCheckIconHTML('grey', true) : null;
}

Misc

you don't need the $_SESSION['id'] !== $author_id check in the elseif. You already checked it in the if, so you know that the user is not logged in. If the last else is entered, something went wrong.
variable names should start with a lower-case letter.
your spacing is sometimes off.
I would move the code that checks if a user is logged in into a user class or something. If you just have checks like this all over the place, it will be hard to change the functionality later on.


You don't need to use Set since indexes can never repeat.  Use a List isntead.
You don't need to keep track of the count.  You can just get indices.size().  That makes ShowIndexDuplicateData class unnecessary.
You probably should be dealing with int[] rather than Integer[].  There aren't many reasons to have a Integer[]

With that, you can really simplify this (using java 8):

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
.....

static final String FORMAT = "%s: count=%s, indices=%s%n";

public static void duplicatesInArray(int[] ary) {
    IntStream.range(0,ary.length).boxed()
            .collect(groupingBy(i -> ary[i], toList()))
            .forEach((num, lst) -> System.out.printf(FORMAT, num, lst.size(), lst));
}


Displaying the multiples of a given number

One important note regarding naming in ruby:

The syntax in ruby is that constants (including class and module names) have to start with capital letters and local variables have to start with lower case letters. Instance, class and global variables must start with their respective sigil followed by a letter in any case. Method names must start with a letter in any case, but if they start with a capital letters, they must be called with () when there are no arguments.

The naming convention in ruby is to use snake_case for method names and variables, PascalCase for class and module names and ALL_CAPS for constants other than class and module names.

For method names the convention is to use snake_case for all methods except "constructor"-style functions (e.g. Integer(), Array(), Hash()) where the name of the function is the same as that of the constructed class.

Generally using PascalCase for method names is a bad idea because:

It's against convention and will make people think it's a constructor-style function
If you define a method without arguments, you'll trip yourself up because you'll try to call it as MyMethod instead of MyMethod() which does not work if the method name starts with a capital letter.

General notes on your code:

Using a while loop is usually unidiomatic ruby. Using a while loop to iterate from one number to another number with a constant step-size is always unidiomatic ruby. If the step-size is 1, you can just use each on a range and if it is something else you can use step. So your code would just be written as:

def display_multples(multiples_of, count)
  (multiples_of .. count).each do |i|
    if i % multiples_of == 0
      puts i
    end
  end
end

Now as pdr points out, this is not the optimal algorithm to do this. Instead of iterating between all integers between multiples_of and count and printing those which are divisible by multiples_of, you can just iterate between the numbers between multiples_of and count with a step size of multiples_of, i.e. only iterate over the multiples of multiples_of. However his code contains an unnecessary each (which will also make the code not work on ruby 1.8.6, though that's thankfully becoming less of an issue these days). So the code should just be:

def display_multiples(multiples_of, count)
  (multiplesOf..count).step(multiples_of) do |i|
    puts i
  end
end

However this code still contains one major, non-ruby-specific design-smell: You're mixing the logic to generate the multiples with the code printing it. Generally IO and logic should be separated as much as possible. So what you should do is define a method multiples which generates the multiples and a method print_multiples which prints them.

In ruby the best way to write a method which generates a sequence of values is to write an "iterator method", i.e. a method which yields the elements. That would look like this:

def multiples(multiples_of, count)
  (multiples_of .. count).step(multiples_of) do |i|
    yield i
  end
end

def print_multiples(multiples_of, count)
  multiples(multiples_of, count) do |i|
    puts i
  end
end

You can also define multiples as:

def multiples(multiples_of, count, &blk)
  (multiples_of .. count).step(multiples_of, &blk)
end

In 1.8.7+ this also has the benefit of returning an Enumerator if no block is given. so if you don't just want to print it, you can also use Enumerable methods like map, select etc. on it.


Implementation of the FNV-1a hash algorithm for 32- and 64-bit

If you were being completely asinine you could move the Initialize method to a new common ancestor class. The amount of code you would write for that common class would exceed the amount of code you would save from duplication though, in other words, not worth it. Alternatively, you can move the Reset logic in to the Initialize method, and remove Reset entirely, and just call Initialize in the constructor.

I think two factors come in to play here:

The basic Object-model of the Hashing systems is pretty well structured. The common-code is already abstracted to higher inheritance levels, so the amount of required duplication is really small (Kudos to the .net library team).
By design, the FNV1a algorithm is simple and fast. The only difference between the 64 and 32 bit versions is the value and type of the primes and initializers. Because these values are different the core algorithm (due to the low-level bitwise operations) need to be different.

In other words, your code is as good as it gets. Good job. Now, when you get around to the 128, 256, 512, and 1024-bit versions of the FNV1a algorithm, you may find some other opportunities for logic sharing. I suspect that the loops required using a common int-based infrastructure will make things possible.


Executing a task at a particular time in the morning using ScheduledExecutorService

According to the javadoc, a Calendar instance is initialized with the current date and time. So instead of this:

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR_OF_DAY);

You don't need to create a separate Date object,
so you can simplify like this for the same effect:

Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);

It would be good to split this code into multiple reusable and testable functions.
For example you could have a function that returns the hours until some target hour:

private int getHoursUntilTarget(int targetHour) {
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    return hour < targetHour ? targetHour - hour : targetHour - hour + 24;
}

Now the target hour is a parameter, this is reusable and flexible, and eliminates the magic number 6 that was duplicated at multiple places.
Also note that I changed the ternary expression a bit, I think targetHour - hour + 24 is more natural, and easier to understand due it's symmetry with targetHour - hour.

You can move the scheduling to another method, which can now have a single responsibility (scheduling) and not worry about calculating hours.

Here's a unit test to verify that getHoursUntilTarget works well:

@Test
public void testGetHoursUntilTarget() {
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    assertEquals(24, getHoursUntilTarget(hour));
    assertEquals(1, getHoursUntilTarget(hour + 1));
    assertEquals(23, getHoursUntilTarget(hour - 1));
}

Note that at 5:59 AM, the hours until target will be 1, even though 6 AM is only one minute away. This is how it was in your original code, I hope that's ok with you.

There is some noise in your post:

System.out.println("Comuted Delay for next 5 AM: "+intDelayInHour);
scheduler.scheduleAtFixedRate(new MyTask(), intDelayInHour, 24, TimeUnit.HOURS);

"next 5 AM" is not consistent with the rest of your code (you used 6 everywhere else),
and you don't have a variable intDelayInHour but you have delayInHour.
Review more carefully before you post.


Here you do 4 things at the same time. Your are

Walking over all the files of the directory
Comparing the filename to a pattern
Formatting the filename
Appending the filename to a file

To find out what is the slower step, you should decouple this

def find_files(root):
    for path, subdirs, files in os.walk(root):
        for filename in files:
            yield filename

def filter_filename(files, pattern):
    for filename in files:
        if fnmatch(filename,pattern):
            yield filename

def format_filenames(files, root):
    for filename in files:
        yield str(os.path.join(filename)) + '\n'

def writelines(out_file, files):
    for filename in files:
        out_file.write(filename)
    # or:
    # out_file.writelines(files)

def main(root, pattern, filename_out):
    files = find_files(root)
    files_filtered = filter_filename(files, pattern)
    files_formatted = format_filenames(files, root)
    with open(filename_out, 'w') as out_file:
        writelines(out_file, files_formatted)

Then Afterwards, there are 4 things you can time individually to find out the largest culprit in time consumption and work on that one:

files = list(find_files(root))
files_filtered = list(filter_filename(files, pattern))
files_formatted = list(format_filenames(files, root))
with open(filename_out, 'w') as out_file: writelines(out_file, files_formatted)


Simple Tip Calculator with JavaScript Console App

A couple of things to consider:

When dealing with a switch statement, if a case utilizes the return keyword then you do not need to also include a break. When the return is hit, no further code in that function will be reached.
You should handle unexpected inputs; for example, serviceQuality should account for non-numeric inputs, or a number that is not 1-5. Look into try/catch statements and using a default case on your switch.
Because you are not reusing headerMessage, this function is not really required.
Your variable names are fairly unintuitive; consider changing them so that it's more obvious what each thing is such as enterBill -> billAmount and enterOption -> serviceOption. It might be worth using those same names as the serviceQuality arguments too.


Whenever the above code gets rerun you're re-instantiating those functions. So the first thing I would recommend is to define the callbacks outside of the immediate scope of whatever's re-running it so they only get instantiated once.

// In a galaxy not so far away…
var animationComplete = function() {
    $amount.text('$'+amount.toFixed(2));
    $diff.text('$'+(o.max - amount).toFixed(2));
    $percent.text(Math.floor(percent));
}, animationStep = function(now, fx) {
    …
};

// meanwhile, back at the farm…
$bar.animate({width:percent+"%"}, {
    duration : o.time,
    easing   : 'swing',
    complete : animationComplete,
    step : animationStep // Got rid of a trailing comma here…
});

Without more context it's hard to say what else you can get away with. You could truncate all your values toFixed(2) early, which would simplify the math for very fractional numbers, but probably not enough for anyone to notice. If, at an earlier point you multiply all your numbers by 100, then you could deal entirely with integers, but there could be some output formatting constraints that make that hard.

All that said, it's likely your animation jitters have nothing to do with the performance of the above JavaScript. You might see some small gains by using CSS transitions and animations instead, which theoretically allow the browser to take better advantage of graphics hardware. (You can still trigger the actual css value changes with JavaScript.)


Function for approximating a sine signal

how to optimize this code regarding memory consumption and performance. (?)

Consider redefining the angle measurement.  It appears int phase is 0.36 degrees.  A natural choice would be 1024 phase to 1 revolution.  Now the problem becomes one using a binary angle measure. Not only does this simplify small things like scaling, it opens up coding choices  as there are many trig function code bases designed withs BAMS, Binary Angular Measurement System.
Code uses double constants and so makes for likely slower computation on an embedded system.  If all that is needed is float, uses float constants and float math.

// return(0.4053*2*3.1415*(phase % 1000)/1000*(3.1415 - ...
return(0.4053f*2*3.1415f*(phase % 1000)/1000*(3.1415f ...

OP reports phase guaranteed to be positive. yet it is minor to adjust code for full int range.

// if(phase % 1000 <= 500)
phase %= 1000;
if (phase < 0) phase += 1000;
if (phase <= 500)

Accuracy: Using 3.1415 for machine_pi can be improved at no computational cost by using  #define MACHINE_PI 3.141592653589793f.  This will improve the end points in the 5th or 6th decimal place.  Use 0.405284734572655f instead of 0.4053 to insure sine(90° (250 phase)) is 1.0f.
If your processor lacks a built-in FP hardware, I recommend a fast integer only solution.  e.g. CORDIC or a small linear interpolation should only low precision be needed.

Using a parabola model like OP's  (1 cycle = 1024 BAM).  The below code is effectively the same preciseness as OP's code with only integer math: and, or, +, -, *, negate and shift.

Input  range [0R 2πR]  mapped to [0 to 1024]
Output range [-1.0 1.0] mapped to [-16,384 16,384]

int_fast16_t sin_bam(int angle_bam) {
  angle_bam %= 1024;
  if (angle_bam < 0)
    angle_bam += 1024;
  uint_fast16_t sub_angle = angle_bam % (1024u / 2);
  int_fast16_t sn = unsigned_mult16x16_into_32(sub_angle, (1024/2 - sub_angle)) / 4;
  if (angle_bam & 512) {
    sn = -sn;
  }
  return sn;
}


Your recent questions give me impression, that you are purposely trying to to find new ways to mock C# syntax. :) You know this saying from MSDN: "code is read way more often, than it is written"? I think you have to keep this in mind, when designing those things. I would definitely have a WTF-moment, if I were to see int Age = (AdultAge)43 in code. I then would have to go and look for AdultAge and Constrain implementations in order to figure out what is going on there. I would rather have this:

Validator.ValidateEmail("test@example.com");

or this:

reference.ThrowIfNull();

or even this:

var age = (Age)21;
if (age.IsAdult) ...

Because those options are easy to read and easy to understand. They feel natural. Your code does not. It's clever, but it is obscure and it is easy to get wrong:

int Age1 = (AdultAge)43; // OK
var Age2 = (AdultAge)43; // OK?
double Age3 = (AdultAge)43.1; // OK?
var Age4 = String.Format("Age: {0}", (AdultAge)43); // OK?


Hash Map Library for any type (Void Pointers)

Bug

Suppose there are 2 keys that hash to the same bucket (i.e. HashLocation).  If you add key #1 and then search for key #2, mapGet() will return the data for key #1 instead of returning NULL.  The problem is here:

if (theHashLocation->numberNodes==1) {
    HashMapNode* dataNode = theHashLocation->nodes[0];
    return dataNode->data;
}

Here, you assume that if there is only one node in the bucket, that it must match the key you are looking for.  But you need to still compare the key to see if it matches.

Unnecessary array of pointers

Your hasharray inside HashMap is an array of pointers to HashLocations.  There's no need for hasharray to be an array of pointers.  It should simply be an array of HashLocations instead.  Using one contiguous array is simpler (less allocations) and better for cache locality.

Bad reallocation strategy

The way you resize each bucket when it grows is by reallocating by one element larger.  This will use \$O(n^2)\$ time because of all the recopying required.  You should use a better reallocation strategy such as doubling the size every time and keeping track of how many elements are being used.

Poor hash function

Your hash function simply adds each character of the string together.  This is a poor hash function which will result in many hash collisions.  You should try something different such as rotating the hash by 5 bits every time you add the next character in.  Here is a StackOverflow question about string hashes, and a short webpage describing a few string hashes, linked from that question.


Should I use const in this function argument?

Yes.

Better conveys to a user code's functionality. Consider the user may only see the declaration void kcr_scene_update(const struct KCR_Scene* scene); (in some header file) and not the definition.

Allows increased applicability.  Function can be called with  const struct KCR_Scene* some_pointer.  Without a const in the function signature, the caller is obliged to pass a non-const pointer.

Optimization: Some optimization will only take place when the reference data is const.  This issue applies especially to older compilers.

good practice to put const in these methods when I know there's some mutation going on?

Need to see detail of struct KCR_Scene and struct KCR_Display to know what changes are really occurring in code.

I now see OP really needs to provide more info  - making answer wiki.


This is border line a bad question, as not enough code is given to properly review it.

The variables a -> g look terrible, I would create an array with the numbers you need:

var dataPoints = [1.16,1.19,1.22,1.26,1.30,1.35,1.40];

Then I would would loop over those points and create an averages object

var averages = {},
    value, x;
for(var i = 0, length = dataPoints.length ; i < length ; i++ ){
  value = dataPoints[i];
  x = Math.pow(value, -(time-lastTime));
  averages[value] = x * lastAverages[value] + (1-x) * distance;
}

I cannot tell whether the math is correct, if it is not correct, then this question does not belong here :)


Match a simple balanced language using a queue

As Konrad Rudolph points out in comments on the other question, this is probably about Pushdown Automata, for which the wikipedia page has some useful examples, and this stackoverflow answer is very helpful.

Using a stack

The stack is used to preserve data while iterating along the input. We move left-to-right from character to character, making a decision based on the current character, and the contents of the stack.

If the input becomes invalid at a certain point (e.g. it contains a 'c', or has too many 'b's, etc.), we can reject it. Otherwise we continue until we have processed the entire input.

For the instructions you've been given, we don't actually need a stack. A counter would suffice. However, a stack would allow balancing multiple sets of characters (e.g. balancing strings of parentheses ([]())[]).

At every 'a' we encounter, we push it onto the stack. At every 'b' we encounter, we pop one off the stack. If we are ever attempting to pop something off an empty stack, the input is not balanced. At the end of the input, the stack must be empty (we popped off the same number of 'b's as the number of 'a's we pushed on).

bool is_balanced(std::string const& input)
{
    if (input.empty()) // n == 0
        return false;

    std::stack<char> stack;
    bool is_first_word = true;

    for (auto c : input)
        if (!pda(stack, is_first_word, c))
            return false;

    return stack.empty();
}

The queue

As you noticed, having the input contained in a queue limits how it can be processed. We don't know the length of the input in advance. We can only pop off one character at a time and process it.

More usually in C++, input like this would come from a stream of some sort.

Note, however, that the core of the algorithm remains exactly the same:

bool is_balanced(std::queue<char>& input)
{
    if (input.empty()) // n == 0
        return false;

    std::stack<char> stack;
    bool is_first_word = true;

    while (!input.empty())
    {
        auto c = input.front();
        input.pop();

        if (!pda(stack, is_first_word, c))
            return false;
    }

    return stack.empty();
}

Making Decisions

The details of the pda function are left to the reader ;) , but it looks something like this:

bool pda(std::stack<char>& stack, bool& is_first_word, char c)
{
    if (c == 'a')
    {
        // check the stack, push / pop, return true / false
    }
    else if (c == 'b')
    {
        // check the stack, push / pop, return true / false
    }
    else
        return false; // invalid character
}

It checks the current character 'c', checks the stack, and pushes / pops if necessary. It returns true if we should keep processing input, and false otherwise.

Weird Things

There are a few slightly unusual things about the instructions you've been given:

Empty input is invalid (n must be >= 1). Often an empty input would be considered a balanced string. This is a simple check to make though.
Only 'a' and 'b' characters means the stack is technically redundant. Usually one would think about balancing parentheses, as in the linked stackoverflow question.
The wording implies that inputs like "abab" are invalid, as this would be considered more than one "word" in the specified language. This is the reason for the is_first_word boolean above. It might be simpler to just ignore this to start with.


I think that yes, the code can be structured somewhat better.
First of all, I'd tend to "RAII all the things". Code like this at the end of main makes me extremely suspicious:
    SDL_DestroyWindow(window.getWindow());
    SDL_Quit();

I'd strongly prefer that those be handled in the destructor of some object so they happen automatically.
So, I'd rename CreateWindow to just Window. Then I'd add a destructor that called SDL_DestroyWindow, so it'll automatically clean itself up when it goes out of scope.
class Window {
public:
    Window(int x, int y, int w, int h, bool fullScreen = false) {
        pWindow = SDL_CreateWindow("", x, y, w, h, fullScreen);
        if (pWindow == nullptr)
            throw std::runtime_error("Unable to create window");
    }

    ~Window() { SDL_DestroyWindow(pWindow); }

    operator SDL_Window*() { return pWindow; }

private:
    SDL_Window *pWindow;
};

Likewise I'd add an Application class (or something on that order that calls SDL_Init in its ctor, and SDL_Quit(); in its dtor, so simply defining a variable of that type automatically initializes SDL, and cleans up before it goes out of scope.
class Application {
public:
    Application() {
        if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        {
            std::stringstream buffer;
            buffer << "Could not intialize SDL properly: " << SDL_GetError();

            throw std::runtime_error(buffer.str());
        }
    }

    ~Application() {
        SDL_Quit();
    }
};

...and of course, Renderer should clean up after itself as well:
    ~Renderer() {
        SDL_DestroyRenderer(pRenderer);
    }

I'd also add definitions of copy assignment, move assignment, copy construction, and move construction to Renderer, Window and Application, so somebody won't accidentally do something nasty and breaking with them. In this case, they're probably move-only classes, so we'd do something on this order:
    Renderer(Renderer const &) = delete;
    Renderer(Renderer &&other) {
        pRenderer = other.pRenderer;
        other.pRenderer = nullptr;
    }
    Renderer &operator=(Renderer const &) = delete;
    Renderer &operator=(Renderer && other) {
        pRenderer = other.pRenderer;
        other.pRenderer = nullptr;
        return *this;
    }

Window would probably be similar in this regard, and Application should probably delete all of them.
I'd also have each of the classes report problems with construction by throwing an exception, rather than leaving it to client code to detect the problem when (for example) it has failed to create a window.
    Window(int x, int y, int w, int h, bool fullScreen = false) {
        pWindow = SDL_CreateWindow("", x, y, w, h, fullScreen);
        if (pWindow == nullptr)
            throw std::runtime_error("Unable to create window");
    }
}

Rather than Events::handleEvents being passed a Boolean in a structure, I'd have it just return a value to indicate when the program should exit:
    bool handleEvents()
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
                return false;
        }
        return true;
    }

I'd also put all of these in a namespace named something like sdl (or sdl2, or something on that order).
With that "stuff" in place, our main can shrink to something on this order:
int main(int argc, char* argv[])
{
    try {
        sdl::Application app;

        sdl::Window window(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1600, 1200);
        sdl::Renderer renderer(window);
        sdl::Events events;

        while (events.handleEvents())
        {
            renderer.clearScreen(255, 255, 255, 255);
            renderer.render();
            renderer.update();
        }
    }
    catch(std::exception const &e) {
        std::cerr << e.what() << "\n";
    }
}

Although I haven't shown it above, I'd at least be tempted to require that a reference to an sdl::Application be passed to the ctor when you create an sdl::Window object. This assures that you've created an sdl::Application object first, thereby assuring that SDL is initialized before you try to create a window with it.


Cleaning up file resources in a DRY manner

I think this can be written more cleanly with flatMap

  flatMap[U](f: (T) ⇒ Try[U]): Try[U]

  Returns the given function applied to the value from this Success or returns this if this is a Failure.

val isReportSent = Try {
 ...
}.flatMap(_ => Try { sendReport(...) })

cleanUp(output, file)

isReportSent.get


Rather than creating a function named My_module, and assigning it to module.exports, you can just directly assign a function to module.exports, like this:

module.exports = function() {
    ...
}

Secondly, why are you ending all your functions and variables in My_module with an underscore, _? It doesn't do anything, and if it's not serving a real naming purpose, it can be removed.


Prim's algorithm for minimal spanning trees

Java developers prefer intention revealing names as opposed to mathematical single letter identifiers. So it might be better to use edge instead of e and so on.
Most common type parameter name in Java is T as opposed to a, so maybe using at least 't' (if not a normal name like nodeType) to prevent confusion and better explain ADTs.
loop might look like a syntax construct, especially because its definition follows afterwards.
Just a detail, but initialSet instead of startSet would be clearer to me - same holds for startNode.
I would replace where with let, because it would make one construct less (although idiomatic one) and it is a convention in mainstream languages to write declarations/definitions before use.
I would also adjust 'loop' signature, so the solution isn't between input arguments - I wold make it the last argument.
I wouldn't use the apostrophe ('), although I understand it is common in math and theory of programming, but among backquoutes (`) for infix operators it might be confusing.
I think it would help if the function composition operator (.) was surrounded with whitespace - it would better show that it is a different kind of '.' than the one in import Data.List(sort, deleteBy), which might be easier to understand for Java developers.

I am not a Haskell guru and I don't have 10+ years of Java experience, so take this as a personal opinion. It might also help quite a lot to show the same implemented in Java - the benefits of features you describe and syntax constructs would be clearer. Feel free to comment on this answer, I am open to discussion.


PHP Class that handles all includes / required files

Mixing

You are mixing 2 things:

class loading
"template" loading

You aren't over complicating things - you try to over simplify them.

Class loading

In your solution you are loading all classes if only (for example) 2 of them required to serve the request the loading of the other 52321 class is just a waste of time and resources.

Read about automatic class loading: Autoloading Classes

With this feature in your mind you can create a custom logic to load the necessary classes (name resolution, class location in file system etc.).

Template

The other thing what you want is loading your templates into the rendering process. This is hard to do it right, all depends on your "framework" solutions for example naming conventions, is your app frame an MVC based stuff etc.


C# easier ways to filter values in data-grid by month

Why not something simple like this:
var filter = Months.SelectedIndex == 0 ? null :
    $" where month(date_purchased) = {Months.SelectedIndex};"

Also that dictionary initialization code is a lot of copy & paste, you could easily write it like this:
var allOptions = new Dictionary<string, string>()
{
    ["0"] = "All"
};

int idx = 1;
foreach(var month in DateTimeFormatInfo.CurrentInfo.MonthNames)
    allOptions.Add((idx++).ToString(), month);

Edit: also don't use data sets if you're only returning one data table, use the table versions of the database API instead.


Call URL x times where x is in the JSON response after the first call

Instead of a for loop, consider a do {} while (pageCount <= numberOfPages)
loop and use an increment operator inside the loop. For this to work though both pageCount and numberOfPages need to have scoping outside of the loop, ie instantiated before the do{ } statement.

do{ } while () loops are guaranteed to run once, then perform the test in the while () to check if they continue. while( ){ } loops perform the check, then run until a value of false is found.

    int number = 1;
    int expectedNumber;
    do {
      HttpEntity<String> requestEntity = new HttpEntity<String>(getBody(number), getHeader());
      ResponseEntity<Stuff> responseEntity =
          HttpClient.getInstance().getClient()
              .exchange(uri, HttpMethod.POST, requestEntity, Stuff.class);
      Stuff response = responseEntity.getBody();
      // do stuff with response here.
      expectedNumber = (int) response.getPaginationResponse().getTotalPages();
      number++;
    } while (number <= expectedNumber && expectedNumber > 0);


Problems like this are often "academic" in nature (although the principles can be applied to other problem-spaces too).

In this instance, I believe that the challenge is to use the correct form of "modulo" and integer-division type arithmetic and to have a "simple" conversion function for each target element.

Your initial output array creation looks good:

int[] dest = new int[src.length * src[0].length * blockWidth * blockHeight];

Note that a zero-sized, or null src array will cause an Exception to be thrown when indexing src[0]. You should probably be more defensive about that...

if (src == null || src.length == 0) {
    return new int[0];
}

Now, in your dest, the value of each cell is a function of its index. There are a few critical values:

target rowsize -> source row-size * block-width
source row -> ( target index / target rowsize) / block-height
source column -> ( target index % target rowsize ) / block-width

Now, the above logic is far from "obvious", but it makes for a remarkably simple loop:

public static int[] expand(int[][] src, int blockWidth, int blockHeight) {
    int span = src[0].length * blockWidth;
    int[] dest = new int[src.length * blockHeight * span];
    for (int i = 0; i < dest.length; i++) {
        dest[i] = src[(i / span) / blockHeight][(i % span) / blockWidth];
    }
    return dest;
}

You can see the above running in ideone: https://ideone.com/sJhksT

Note that the concept of describing an element in an output array as a function of the output index is sometimes a nice "trick" and neatens things up. You have to be able to spot this, though, in real code. Note that the above code basically says dest[i] = fn(i) where fn(i) is some function taking i as an argument.

Your code, on the other hand, works off the source index, and it tries to calculate the indexes in the output array from the source location. That's not "wrong", but as you can see, it makes for a nested, and ugly loop.

Knowing when to reverse the logic is more of an art than a science, but being able to identify these logic inversions is important.


Write to a CV::Mat from a higher scope within a function

Assuming the matrix is always empty when passed into the function, the more normal way to write this would be to avoid any side effects and make cv_matrix the return type. i.e

cv::Mat read_matrix_from_param(ros::NodeHandle nodehandle, const std::string& param)
{
    cv::Mat cv_matrix

    ...
    return cv_matrix;
}

As a side point you should pass in param and possibly nodehandle, as const & to avoid unnecessary copies.

If this is not the case and you may pass in non-empty matrices ( I think that wouldn't make sense here ), then I would say using a non-const ref is fine. Alternative you could use a pointer i.e.

void read_matrix_from_param(ros::NodeHandle nodehandle, std::string param, cv::Mat *cv_matrix)
{
    ...

    cv::Mat(_rows, _cols, CV_64F, _data.data()).copyTo(*cv_matrix);
}

called as

read_matrix_from_param(private_nh, std::string("camera_matrix"), &test_matrix1);

Personally I wouldn't use a pointer and Core C++ Guidelines recommends a reference, but looks like it is the style recommended by google see https://softwareengineering.stackexchange.com/questions/299021/non-optional-pointers-vs-non-const-references-in-c . If you are using clang-tidy google style guidelines are an option in that I believe so that may be where this warning is coming from.


Overall Observations
The more code you provide the better the reviews you will get. There are 2 statements, 1 in the question and 1 in the comments after the question that almost make it off-topic for the Code Review site:

... my real code does not print for each iteration, this is for easy testing.
I have another function that calculates that "free space".

As provided in the question the code is almost unreadable and therefore would be a problem for maintenance. If I were an teacher grading this code the best grade I can give it is a C (70%) because it compiles and runs. The variable names are meaningful. In a professional environment if I were your manager we would have a long talk in private about why it is important to make the code more readable.
In a professional environment you are very unlikely to be the only one maintaining the code for multiple reasons:

You may get promoted and not assigned to maintain the code anymore.
You may quit and get another job.
A bug may exist in the code that needs to be fixed and you are assigned to a higher priority project so someone else will be assigned to fix the code.

There are more reasons than just the 3 above. For all these reasons I will be addressing coding style here.
Possible Optimizations
The first rule of optimization is don't optimize, the second is find all the bottlenecks in the code (bottlenecks being functions that slow down the code). The primary way to optimize C++ code is to use the built in compiler optimization using the -O through -O3 compiler command lines. This will generally produce very fast code. It will be very difficult to provide optimizations for this code as currently presented, but if you are compiling for debug one possible optimization might be to use the C++ iterators provided for each of the container classes such as vector.
You might also want to make the variables iterators_number and iterators_range constants since they don't change.
    const int iterators_number = 3;
    const int iterators_range = 3;

Avoid using namespace std;
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
Declare Variable as Necessary
As far as I can tell the variable move_index does not need to maintain it's value between iterations of the while (true) loop so it should be declared within the loop, the declaration should include the initialization of the variable in almost all cases, but definitely in this case.
Don't Use One line for Loops or if Statements
The code contains this line:
        for (int i = 0; i < iterators_number; i++) cout << options_iteration[i] << " ";

On my first time through the code I missed the fact that the for loop had an action. This code should be on 2 lines at least but preferably 4. 2 lines:
        for (int i = 0; i < iterators_number; i++)
            cout << options_iteration[i] << " ";

Why 4 lines? One of the easiest mistakes to make when maintaining code is to add a statement to a for loop or if statement without adding the braces necessary to make it part of the loop. So when creating new code it is better to add the to begin with:
        for (int i = 0; i < iterators_number; i++)
        {
            std::cout << options_iteration[i] << " ";
        }

I didn't come up with this, it was forced on me by a company coding standard, however, I saw the value of it having made that kind of mistake a number of times.
This version of the code is slightly longer but muc more readable and easier to maintain:
#include <vector>
#include <iostream>

int main() {
    int iterators_number = 3; // Number of iterators, bubble sort for example uses 2, note: this is not for bubble sorting.
    int iterators_range = 3; // The maximum value for the iterators values, can be the size of the array for example.

    std::vector<int> options_iteration(iterators_number, 0);

    while (true) {
        for (int i = 0; i < iterators_number; i++)
        {
            std::cout << options_iteration[i] << " ";
        }
        std::cout << std::endl;

        int move_index = iterators_number - 1;
        for ( ;
            (move_index >= 0) && (options_iteration[move_index] > iterators_range - 1);
            move_index--)
            ;
        if (move_index < 0)
            break;

        int new_value = options_iteration[move_index] + 1;
        for ( ; move_index < iterators_number; move_index++)
        {
            options_iteration[move_index] = new_value;
        }
    }

    return 0;
}


Longest Palindromic Substring better approach

Unnecessary else after return

In the body of an if, if you end up returning something in that body, an else is not required. A return will exit the body of the function, so the code in the else won't be run. So, you can simply move the code in the else to the outside, after the if. This may have been confusing, but take a look at the updated code to see what I'm talking about.

enumerate()

Instead of using range(len()), use enumerate(). This will allow you to access both the index and the value at that position, and enumerate works for other iterables as well. It's useful here because instead of writing arr[j] over and over, you can simply write value, which is the value at arr[j].

_ for unused loop variables

Also touching on enumerate- When you only want to use one of the values (in your code, you have both cases present), use an _ in that place. This indicates to you and other readers that that variable is to be ignored, and isn't necessary.

Parameter Spacing

When using : in parameters, make sure there is exactly one space after the :.

Operator Spacing

Make sure to space out your operators when assigning and performing arithmetic on variables. It makes it much easier to read, and looks nicer.

return True

Instead of explicitly returning true if the if condition is true, simply return that condition. It will return the boolean value that is returned from that condition.

function_naming

I know you can't change the function names (assuming this is coming from a code challenge website), but remember that method names are to be in snake_case, not camelCase or PascalCase. This is in reference to PEP-8 Method Naming Guidelines. Thanks to @SᴀᴍOnᴇᴌᴀ for pointing this out to me.

Updated Code

class Solution:

    def longestPalindrome(self, s: 'str') -> 'str':
        if s == "":
            return ""
        ## Find all the substrings
        arr = []
        for i, value in enumerate(s):
            char = value
            arr.append(char)
            for j in range(i + 1, len(s) - 1):
                char += s[j]
                arr.append(char)

        ##Find the palindrome with a longest length
        max_length = 0
        for _, value  in enumerate(arr):
            if self.isPalindrome(value):
                if len(value) > max_length:
                    max_length = len(value)
                    index = value
        return index

    def isPalindrome(self, s: 'str')->'str':
        return s == s[::-1]


This is a bit hard to answer, but let's try nevertheless:

From a computational point of view, using a scripting language like python for iterative algorithms doesn't make the least sense -- your PC is going to be far more occupied by translating your python code to executable structures than it will be with executing the core algorithm. For example, every number in python (assuming a CPython implementation of the runtime environment) is an object -- which makes number-number multiplication far more expensive than the actual multiplication. Now, I assume your question is "if I did this in a compiled language, with fixed length numerical types, would this algorithm perform optimally"?
approximating a square root in software is bound to be horrendously expensive compared to just calculating the floating point square root; modern general purpose CPUs even have instructions that can take the square root of several numbers at once, in just a few cycles!
I just have to stress this once more: "efficient" doesn't really make sense in this context, without actually specifying your measurement for efficiency. If your measurement is "how long does it take to have N significant digits", most probably even the most naive C implementation would beat the hell out of your Python program -- just because python is such a capable scripting language, which requires a lot of indirection. You could specify things like "minimum number of multiplications plus additions", but you'd totally neglect possibly different cost for these operations, and, much worse, memory movement complexity etc. Now, if you're actually into this kind of discussion, think about what kind of architecture you actually try to optimize for: A single threaded computer with uniform multiply, add, memory address loading and storage costs has never really existed; the norm today are hyperthreaded multicore processors with a limited number of SIMD registers and multilevel caches, which can make algorithms which "look good on paper" perform terribly because they just misuse the capabilities of the architecture, whilst stupid implementation might work exceptionally well because of possible compile- and execution-time optimization.


I don't think your code agrees with your spec: Your code looks like it can only implement a function built from three line segments.

You shouldn't need explicit resize.

bounce (lo, hi) x dx = let
  (bounces, remainder) = divMod (add dx $ x-lo) $ hi-lo
  in (if even bounces then lo + remainder else hi - remainder
     ,bounces /= 0)


A nice little guessing game you've got here.  Skill will only get you 70%, you still need luck to win.

Quoted Stings

The Python language gives you 4 different syntaxes for creating strings: "...", '...', """...""", and '''...'''.  The first two will allow you to embed quotes and double quotes, respectively, without escaping.  The latter two will allow you to embed either quote, as well as new-lines, without needing escapes.

            print("Sorry, you didn't type \"YES\" or \"NO\"...")

Here you want double quotes inside the string, and since you're using double quotes for your string, you've had to escape them.  If you had used a triple-quoted string:

            print('''Sorry, you didn't type "YES" or "NO"...''')

no escaping is necessary.

Code Organization

Your code presently looks like this:

import random

print("Welcome to the Guessing Game!")
user_name = input("What should I call you? ")
print("Hello, " + user_name)

def gameplay():
    ... # contents omitted for brevity

gameplay()

You've got imports, mainline code, a function definition, then more mainline code.  You should group all the mainline code together, not have it separated by other function definitions.

import random

def gameplay():
    ... # contents omitted for brevity

print("Welcome to the Guessing Game!")
user_name = input("What should I call you? ")
print("Hello, " + user_name)

gameplay()

Main Guard

It is highly recommended all mainline code be protected by a main guard:

import random

def gameplay():
    ... # contents omitted for brevity

if __name__ == '__main__':
    print("Welcome to the Guessing Game!")
    user_name = input("What should I call you? ")
    print("Hello, " + user_name)

    gameplay()

This allows the file to be imported by other modules.  You might think that this game code will never be imported by another module, because it is stand-alone code, but if you want to run any tests on the code, this file gets imported and the game starts to run messing up the test framework.  So always use this main guard.

Unnecessary Recursion

gameplay() calls restart_game().  Then restart_game() can call either gameplay() or restart_game().  Both of these are recursive calls, which add more and more frames to the program stack.  Eventually, the Python program stack will exceed its maximum limit and the program will crash.  The user will likely get bored long before the stack overflows, but some automated testing script which is testing various guessing strategies might play thousands of games within a second, and there the program would crash.

Note: Some languages utilize something called "Tail Call Optimization" (TCO) and optimize out these tail-recursive calls.  Python is not one of them; it doesn't do TCO.

Each of these recursive calls is easily replaced by a simple loop.  Let's start with the inner loop:

Do you want to play again?

This is a simple YES/NO question.  Many programs might need it (although they might not exactly phrase the question about a game.  You hid the function inside the gameplay() function, which was fine because it was tightly coupled to that outer function, but making it more general means we'll want it moved out to become its own top-level function:

def yes_or_no(prompt: str) -> bool:
    """
    Ask a "yes or no" question.

    The question will be repeated until the user responds with "YES" or "NO",
    but the user doesn't need to capitalize their response.

    Parameters:
        prompt: the yes/no question to ask the user.

    Returns:
        ``True`` if the user responds "YES", ``False`` if the user responds "NO".
    """

    user_reply = input(prompt).upper()
    while user_reply not in {"YES", "NO"}:
        print('Sorry, you didn't type "YES" or "NO")
        user_reply = input(prompt).upper()

    return user_reply == "YES"

A couple of points to highlight:

Type hints (eg, prompt: str, and -> bool) are optional, but very useful.
"""docstrings""" are also very useful.  If you run your program in an REPL (such as IDLE), type help(yes_or_no) at the >>> prompt, after the program has run.
The user input is converted to uppercase once, immediately after input() returns a value.  It is not converted to uppercase on each test (eg, user_reply.upper() == "YES" and user.reply.upper() == "NO")
The while-loop repeats the question, if invalid input is given.  No recursion.
The user_reply not in { ... } is an efficient way of testing for an invalid response.

Using the yes_or_no() reply

If the user answers "YES", your code recursively called gameplay() for another game.  Now that we have our yes_or_no() question function, let's use it and eliminate that recursion.  Let's refactor the mainline code into a guessing_game() function in the process:

import random

def gameplay():
    ... # contents omitted for brevity

def guessing_game():
    print("Welcome to the Guessing Game!")
    user_name = input("What should I call you? ")
    print("Hello, " + user_name)

    play_again = True
    while play_again:
        gameplay()
        play_again = yes_or_no("Do you want to play again? " +
                               "Type YES if you want to play again or NO if you want to quit... "):

    print("Script terminating. Exiting game...")

if __name__ == '__main__':

Now, we are calling gameplay() in a loop, instead of recursively.

The Guessing Loop

    while user_guess != number and not(out_of_guesses):
        if no_of_guesses < guess_limit:
            user_guess = ...
            ...
            no_of_guesses += 1
        else:
            out_of_guesses = True

This loop makes my head hurt.  You are looping once per guess, to a maximum of guess_limit guesses, plus one additional loop iteration to set out_of_guesses = True to terminate the loop.  It is that extra iteration that is really bizarre.  It works, but ... (shudder).

Let's try a completely different loop structure.  We have a guess_limit; let's make a loop based on that:

    for guess_number in range(guess_limit):
        user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... "))

That alone will ask the user to guess 3 times.  If they guess the number, we want to break out of the loop early.

    for guess_number in range(guess_limit):
        user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... "))

        if user_guess == number:
            print("You guessed it! Congratulations, you win the game!")
            break

But what about when they fail to guess it?  If the for loop finishes all iterations without ever break-ing out of the loop, it will execute an optional else: clause:

    for guess_number in range(guess_limit):
        user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... "))

        if user_guess == number:
            print("You guessed it! Congratulations, you win the game!")
            break

    else:
        print("You ran out of guesses, try again")

The complete function, with the low/high guessing hints added back in:

def gameplay(guess_limit=3):
    """
    A number guessing game.

    A random integer will be selected between 1 and 10.  You have to guess the
    number within the allotted number of guesses.

    Parameters:
        guess_limit: Number of guesses to allow.  Allow more guesses for an easier game
    """

    number = random.randint(1, 10)

    for guess_number in range(guess_limit):
        user_guess = int(input("Guess the number from 1 to 10 that I'm thinking of... "))

        if user_guess == number:
            print("You guessed it! Congratulations, you win the game!")
            break

        if user_guess < number:
            print("Your number was too low...")
        else:
            print("Your number was too high...")

    else:
        print("You ran out of guesses, try again")

I've made guess_limit a parameter, with a default of 3, to demonstrate another Python feature: default arguments.  gameplay() will play the game as normal, but you could call the function with gameplay(4) to make an easier variant of the game.


CSS list-style with Font-Awesome toolkit

Properly formatted CSS can make your styles vastly more readable, helping you find bugs as well as making it easier to work with.

This:

ul.long_arrow_right_red,ul.long_arrow_right_gold     {list-style: none;}
ul.long_arrow_right_gold li:before {content:"\f178"; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:gold;}
ul.long_arrow_right_red  li:before {content:"\f178"; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:red;}

Should instead be something like this:

ul.long_arrow_right_red,
ul.long_arrow_right_gold {
    list-style: none;
}

ul.long_arrow_right_gold li:before {
    content: "\f178";
    font-family: FontAwesome;
    display: block;
    float: left;
    width: 1.5em;
    color: gold;
}

ul.long_arrow_right_red li:before {
    content: "\f178";
    font-family: FontAwesome;
    display: block;
    float: left;
    width: 1.5em;
    color: red;
}

If you want to have the code "minified" then do that before you deploy it, source code should aim for readability and maintainability, rather than length / character count.