High performance primitive dynamic array

There is a small bug: In the method add(int, int), it should probably be

if (index > length || index < 0)
    throw new ArrayIndexOutOfBoundsException(index);

instead of

if (index >= length || index < 0)
    throw new ArrayIndexOutOfBoundsException(index);

Inserting at the index length would just mean appending an element to the end of the iVector, so an index of length wouldn't be invalid.
Also, data.length + data.length/2 might overflow for very large values of length. You could prepare for this by checking whether Integer.MAX_VALUE - data.length/2 >= data.length.
In the method ensureCapacity(int), it would suffice to copy length elements instead of data.length elements, since the values of all elements in data with an index equal to or greater than length are irrelevant.
You could simply call add(length, value) from add(int value), because right now, the code of add(int) is effectively duplicated in add(int, int). If the reason for this is performance due to the unnecessity of argument validation, this would probably only be relevant for a very large number of successive additions, and for this, you could make a separate bulk method like addAll (which could also employ other optimizations like calling System.arraycopy instead of manually copying each element via iteration).
public void remove(){
    if(length == 0) return;
    --length;
}

Can be written more concisely as:

public void remove(){
    if(length != 0) --length;
}

remove() returns void whereas remove(int index) returns the value previously at index. This is inconsistent. I suggest you make remove() also return the previously last element.
It occurred to me that, if the internal array can contain "vacant lots" at the end, it could also contain vacant lots at the beginning. For example, consider this array with a capacity of 10, containing 6 elements:

abcfgh----

Now, if you want to delete a from the array, your code would do this:

bcfgh-----

I.e. delete the first element and shift all subsequent elements to the left by one position. But it would be much more efficient to do this:

-bcfgh----

This would also require a pointer to the first element in addition to a field that stores the number of elements in the iVector. And if you want to insert or delete an element, you could calculate for each direction how many elements would have to be shifted, and then perform the cheaper of the two variants and update the respective pointer accordingly. For example, if you now want to insert e between c and f, a "left-push" would require two elements to be moved (bc), whereas a "right-push" would require three elements to be moved (fgh), so the left-push variant would be cheaper:

bcefgh----

In fact, the array could even wrap around. If you now want to insert d before e, you could do this:

cdefgh---b

While this would make simple get or set operations a tiny bit more expensive, because you would have to calculate the index for the internal array from the public index for the iVector, I guess that this can save quite a bit of performance for add or remove operations on the lower half of the iVector.

Update

So I've tried to implement the wraparound suggestion myself, and the code now seems to be about twice as fast as your version when removing and inserting from/to random positions in the vector. When only operating on the upper half, it is, of course, a little bit slower, because the overhead is never compensated for by shifting fewer elements than your original code. Here is my implementation:

public class IntArrayList {
    private int[] data;
    private int size;
    private int indexOfFirstElement;

    public IntArrayList() {
        this(10);
    }

    public IntArrayList(int initialCapacity) {
        data = new int[Math.max(initialCapacity, 10)];
        size = 0;
        indexOfFirstElement = 0;
    }

    public int size() {
        return size;
    }

    /**
     * Returns the index of the element in the internal array that is
     * {@code offset} positions away from the element at the index
     * {@code index}, wrapping around the array if necessary.
     * {@code offset} can be negative, in which case the distance will be
     * traveled to the left of the original element rather than to the right.
     * This method assumes that the passed index is valid and that the
     * absolute value of {@code offset} is not greater
     * than the length of the internal array. If these conditions are not
     * met, the returned index might not be valid.
     *
     * @param index  a valid index for the internal array
     * @param offset the distance from the element at index {@code index}; may be negative
     * @return the index of the array element at the specified distance
     */
    private int indexForOffset(int index, int offset) {
        int offsetIndex = index + offset; //might overflow
        if (data.length - index <= offset) { //includes cases where the previous line overflows
            offsetIndex -= data.length;
        } else if (offsetIndex < 0) { //cannot be the result of an overflow
            offsetIndex += data.length;
        }
        return offsetIndex;
    }

    public void ensureCapacity(final int capacity) {
        if (capacity > data.length) {
            int[] newData = new int[capacity];
            if (size != 0) {
                if (indexOfFirstElement <= indexForOffset(indexOfFirstElement, size - 1)) {
                    System.arraycopy(data, indexOfFirstElement, newData, 0, size);
                } else {
                    System.arraycopy(data, indexOfFirstElement, newData, 0, data.length - indexOfFirstElement);
                    System.arraycopy(data, 0, newData, data.length - indexOfFirstElement, indexOfFirstElement + size - data.length);
                }
            }
            data = newData;
            indexOfFirstElement = 0;
        }
    }

    /**
     * Converts an index for this {@code IntArrayList} to the
     * corresponding index for the internal array. This method
     * assumes that the passed index is valid. If it is not,
     * the returned index might not be valid as well.
     *
     * @param publicIndex A valid index for this {@code IntArrayList}
     * @return the index pointing to the corresponding element in the internal array
     */
    private int internalArrayIndex(int publicIndex) {
        int internalArrayIndex = publicIndex + indexOfFirstElement;
        if (internalArrayIndex < 0 || internalArrayIndex >= data.length) {
            internalArrayIndex -= data.length;
        }
        return internalArrayIndex;
    }

    public void add(final int value) {
        add(size, value);
    }

    public void add(final int index, final int value) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }

        if (size == data.length) {
            if (data.length == Integer.MAX_VALUE) {
                throw new OutOfMemoryError();
            } else {
                int newCapacity = data.length + data.length / 2; // Grow by approx. 1.5x
                if (newCapacity < 0) { //overflow
                    newCapacity = Integer.MAX_VALUE;
                }
                ensureCapacity(newCapacity);
            }
        }

        int internalInsertionIndex = internalArrayIndex(index);
        if (index >= (size + 1) >>> 1) { //right-push
            moveRangeWrapping(data, internalInsertionIndex, 1, size - index);
        } else { //left-push
            internalInsertionIndex = indexForOffset(internalInsertionIndex, -1);
            moveRangeWrapping(data, indexOfFirstElement, -1, index);
            indexOfFirstElement = indexForOffset(indexOfFirstElement, -1);
        }
        data[internalInsertionIndex] = value;
        size++;
    }

    public void set(final int index, final int value) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }
        data[internalArrayIndex(index)] = value;
    }

    public int get(final int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException(index);
        }
        return data[internalArrayIndex(index)];
    }

    public int remove() {
        return remove(size - 1);
    }

    public int remove(int index) {
        final int result = get(index);

        int internalDeletionIndex = internalArrayIndex(index);

        if (index >= size / 2) { //right-side-pull
            moveRangeWrapping(data, indexForOffset(internalDeletionIndex, 1), -1, size - index - 1);
        } else { //left-side-pull
            moveRangeWrapping(data, indexOfFirstElement, 1, index);
            indexOfFirstElement = indexForOffset(indexOfFirstElement, 1);
        }

        size--;
        return result;
    }

    public void clear() {
        size = 0;
        indexOfFirstElement = 0;
    }

    @Override
    public int hashCode() {
        int hashCode = 1;
        for (int i = 0; i < size; i++) {
            hashCode = 31 * hashCode + get(i);
        }
        return hashCode;
    }

    //moves a range without wrapping around
    private static void moveRange(int[] array, int sourceStartPosition, int destinationStartPosition, int length) {
        if (sourceStartPosition < 0 || destinationStartPosition < 0 || length < 0
                || sourceStartPosition > array.length - length
                || destinationStartPosition > array.length - length) {
            throw new IndexOutOfBoundsException();
        }
        int offset = destinationStartPosition - sourceStartPosition;
        if (offset > 0) {
            for (int i = destinationStartPosition + length - 1; i >= destinationStartPosition; i--) {
                array[i] = array[i - offset];
            }
        } else if (offset < 0) {
            for (int i = destinationStartPosition; i < destinationStartPosition + length; i++) {
                array[i] = array[i - offset];
            }
        }
    }

    //moves a range, wrapping around if necessary; requires that the foremost element
    //in the direction to be moved would not overwrite another element from the range to be moved
    private static void moveRangeWrapping(int[] array, int sourceStartPosition, int offset, int length) {
        if (length < 0 || length > array.length - Math.abs(offset)
                || sourceStartPosition < 0 || sourceStartPosition >= array.length) {
            throw new IndexOutOfBoundsException();
        }
        if (offset > 0) {
            if (sourceStartPosition > array.length - length - offset) {
                if (sourceStartPosition > array.length - length) {
                    moveRange(array, 0, offset, sourceStartPosition + length - array.length);
                }
                int tempStartPosition = Math.max(array.length - offset, sourceStartPosition);
                moveRange(array, tempStartPosition, tempStartPosition + offset - array.length, (sourceStartPosition < array.length - length ? sourceStartPosition + length : array.length) - tempStartPosition);
            }
            if (array.length - offset > sourceStartPosition) {
                moveRange(array, sourceStartPosition, sourceStartPosition + offset, Math.min(length, array.length - offset - sourceStartPosition));
            }
        } else if (offset < 0) {
            //sourceEndPosition is from 1 to array.length, inclusive
            int sourceEndPosition = sourceStartPosition + length;
            if (sourceEndPosition > array.length || sourceEndPosition < 0) {
                sourceEndPosition -= array.length;
            }

            if (sourceEndPosition + offset < length) {
                if (sourceEndPosition < length) {
                    moveRange(array, sourceStartPosition, sourceStartPosition + offset, array.length - sourceStartPosition);
                }
                int tempStartPosition = Math.max(0, sourceEndPosition - length);
                moveRange(array, tempStartPosition, tempStartPosition + offset + array.length, Math.min(-offset, sourceEndPosition) - tempStartPosition);
            }
            if (sourceEndPosition + offset > 0) {
                int tempStartPosition = Math.max(-offset, sourceEndPosition - length);
                moveRange(array, tempStartPosition, tempStartPosition + offset, sourceEndPosition - tempStartPosition);
            }
        }
    }
}

I've renamed length to size because I found length just too confusing with data.length always coming up somewhere. I've also replaced some of your ArrayIndexOutOfBoundsExceptions with IndexOutOfBoundsExceptions, since an ArrayIndexOutOfBoundsException is only meant for arrays, and not for any index-based data structure.

Unfortunately, the method moveRangeWrapping is an eyesore. Maybe this can be mitigated by introducing more local variables, but the problem is the constant threat of overflows, which often requires the comparison statements in a way that they don't lend themselves to use local variables (e.g. if (sourceStartPosition > array.length - length) instead of if (sourceStartPosition + length > array.length)), so I'm not sure how much can be done about this.

In addition, I've implemented hashCode() so that it produces a hash equivalent to the hash code of an analogous List<Integer>, which can be used both for testing purposes and to prevent clever compiler optimizations (hopefully).


PHP loop to generate an HTML form for the days in the coming week

Initial Thoughts

Initially I was thinking of suggesting a view class that could hold the states and weekdays in instance variables, then have methods to get the header for each state and then display the cells for each weekday, but that seems like a lot of extra overhead just to display a table, and wouldn't provide the desired separation of business logic and display templates.

Simple improvements

As GrumpyCrouton mention in the SO answer, PHP Short echo tags could be used to shorten the inline echo statements (i.e. <?php echo to <?=).

$d could be eliminated by using the associative array syntax of foreach

  foreach (array_expression as $key => $value)
               statement
  1

foreach($weekdays as $d => $weekday) {
    //$d doesn't need to be incremented since it is the keys - e.g. 0, 1, 2, etc.
}

Or just used array_keys() since the weekday value isn't used...

foreach(array_keys($weekdays) as $d) {
    //$d doesn't need to be incremented since it is the keys - e.g. 0, 1, 2, etc.
}

One could define a template using Heredoc syntax, like:

$cellTemplate = <<<CELL

    <input name="date-%s" />

CELL;

Then that could be used for each table cell:

foreach ( $states as $state ) { ?>
  <tr class="<?= $state; ?>">
    <?= $state; ?>
    <?php
    foreach ( $weekdays as $d => $weekday ) {
        $dateName = $date->addDay( $d )->format('[Y][m][d]') . '[' . $state . ']';
        echo sprintf($cellTemplate, $dateName);
      }
      ?>

<?php
}
?>

A demonstration can be seen here. Note that instead of using the Carbon DateTime I am using PHP's DateTime class along with DateInterval to accomplish the date addition with DateTime::add().

Template Engines

One could also utilize a template engine, like Smarty, Symfony’s Twig, Laravel’s Blade, etc.

Here is an example with a Smarty template. I like bumperbox's notion of storing the formatted weekdays in an array and using that in later on. That array could also be generated using array_map() (though accessing $date inside the callback would require a use statement):

$formattedWeekdays = array_map(function($d, $weekday) use ($date) {
    return $date->addDay( $d )->format('[Y][m][d]');
}, array_keys($weekdays), $weekdays);
$smarty->assign('states', $states);
$smarty->assign('formattedWeekdays', $formattedWeekdays);
$smarty->display('../templates/weekdays.tpl');

And that template file (i.e. weekdays.tpl) might look like this:

    {foreach $states as $state}

        {$state}
        {foreach $formattedWeekdays as $formattedWeekday }

            <input name="date-{$formattedWeekday}[{$state}]" />

        {/foreach}

    {/foreach}

That way the display logic is separate from the business logic. As this wikibooks page alludes to, the HTML is separated from the PHP code so multiple people (e.g. graphics designer, developers, etc.) can manage the separate parts since they are de-coupled.

1http://php.net/manual/en/control-structures.foreach.php


Haskell version of HackerRank problem solution "NumberTheory/Restaurant"

getNumLoaves :: IO Int
getNumLoaves = readLn

parseInt :: String -> Int
parseInt = read

Theses functions are useless. It's useful when you're writing the code and it's not done yet, but Haskell can actually deduce the types based on what the other functions parameters type, like getLoafDimensions need an int, so readLn must return an int, otherwise it wouldn't compile

Your tuplefy function can be simplified by removing the case of, which is basically the same as this form of pattern matching

tuplefy :: [a] -> (a, a)
tuplefy [a, b] = (a, b)
tuplefy _      = error "each line of input must consist of 2 integer values."

By the way, the error message is wrong, because that function can accept a list of any type

Both readLn and getLine are defined in the prelude, so you don't need to import them, so you don't need to import System.IO


Bash script to share snippets of code using rsync

Your read calls perform \ expansion: if the line ends with \, the shell continues reading the next line and returns the text without the backslash-newline sequence; any other backslash quotes the next character (i.e. the backslash is ignored, except that \\ yields \). This is probably not desirable; use read -r to avoid this behavior. Also, for future reference, note that whitespace at the beginning and end of the input is stripped (you need to set IFS to the empty string to avoid this, but here stripping whitespace is desirable); see Understanding IFS and the linked posts.

Furthermore, since this script is designed for interactive use, you should use read -e to enable editing of the input line (with readline). It would also be nicer to have the prompt together with the input line: use read -p 'Server name: ' and so on instead of calling echo (and don't SHOUT). For example:

if [[ -z $SERVER ]]; then
    read -rep 'Server name: ' SERVER
fi

rsync -avz --progress -e ssh "$UN"@"$SERVER":"$remoteSnippetFile" "$localSnippetFile"

This looks a little more complicated than it needs to be, you can write "$UN@$SERVER:$remoteSnippetFile".

The following part has a bug and is not as readable as it could be:

echo -e "<time>"$TIME"</time>\n" >> "$localSnippetFile"
echo -e ""$snippetTitle"" >> "$localSnippetFile"
echo "

" >> "$localSnippetFile"

The bug is that $TIME and $snippetTitle undergo word splitting and filename generation (i.e. globbing). For example, if $snippetTitle is The A* algorithm and the current directory contains the files Astar.tex, Astar.pdf and test.c, then you're writing The Astar.pdf Astar.tex algorithm to the file. Always use double quotes around variable and command substitutions, unless you know why you must leave them off and why it's safe to do so. (Exception: you may leave off the double quotes in contexts where they are explicitly not needed, such as inside [[ … ]].)

The readability improvement is to use a here document.

cat <<EOF >>"$localSnippetFile"
<time>$TIME</time>
$snippetTitle

EOF

nano "$localSnippetFile"

glenn jackman has already mentioned this: it's rude to impose your editor on the user. There is a standard for letting the user choose an editor: use the VISUAL environment variable, falling back to EDITOR. Use a sensible fallback if neither variable is set.

if [[ -z ${VISUAL=$EDITOR} ]]; then
  for VISUAL in sensible-editor nano vi; do
    if type "$VISUAL" >/dev/null 2>/dev/null; then break; fi
  done
fi

Drop this …

       while [[ $? = 1 ]]; do
           syncSnippet
       done

… and instead change syncSnippet to first call read until the user enters an accepted input, and then perform the actions based on this input.

while
    read -p "Sync snippet file now [y/n]: " -rN1 yn
    [[ $yn != [YNyn] ]]
do :; done
if [[ $yn = [Yy] ]]; then
  rsync …
fi


FizzBuzz is a popular interview question so following good programming practices are a good idea.

One key part of working with people on a larger project is readable code.  Your code is very difficult to read because it is all aligned at the left side.  There are also no spaces between things which can be valuable for grouping blocks of code.  Something like this would be much more likely to impress your potential employer:

// Bhaskar's fizzbuzz in JavaScript/jquery

$("#btnfb").click(function () {
    var numfiz = $("#fizz").val();
    var numbuz = $("#buzz").val();
    var outputarray = [];

    for (var loop = 1; loop <= 100; loop++) {
        if (loop % numfiz === 0 & loop % numbuz === 0) {
            outputarray.push("Fizzbuzz");
        } else if (loop % numfiz === 0) {
            outputarray.push("Fizz");
        } else if (loop % numbuz === 0) {
            outputarray.push("Buzz");
        } else {
            outputarray.push(loop);
        }
    $("fzbzout").html(outputarray.join(", "));
    $('#myModel5').modal('show');
});

By formatting the code this way it became immediately apparent that the for loop didn't have a closing }.  Even if you have to do this on a whiteboard I would still stick with formatting things like this.  For more detailed rules than "indent inside squigglies" check out Google's JavaScript style guide.

A second key part of working with others on software projects is providing useful comments.  I skip this on whiteboard exercises because I'm probably going to have to verbally walk someone through the code anyways.  But skipping it when I've got a keyboard available to me seems like a red flag that I would write code that cannot be maintained by anyone else.


Faster way to group email-date pairs by date without many nested for loops?

A good function will should accept the data as a parameter and return the resulting data structure.  Call print(emails_by_date(email_date_table)) to put it all together.

Two Pythonic techniques you want to use are:

dict.setdefault(key[, default]), which gets rid of the need for if, as well as the requirement for the input to be grouped chronologically
Multiple assignment in the for-loop, which removes the ugly [0] and [1] indexing:

  If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

  The function could be written as:

def emails_by_date(pairs):
    ret = {}
    for email, date in pairs:
        ret.setdefault(date, []).append(email)
    return ret


I am challenged by a few things here:

First the inheritance model makes no sense in real world terms.  Why would an email class inherit from a user class?  Try to think in real-world terms about the objects in your system and you will more often than not, end up with a better design.  Here I would think that a user class could have a property that holds the email object(s) that belong to the user, but I don't see how an email, when defined in terms of it's own object would inherit from a user, which would have a wholly separate set of properties it has and actions (methods) it can perform than what an email object does.  So why use inheritance here at all?
You don't really consider what might truly be common amongst two wholly different objects that exist in your database, that might be points for common inheritance.  What do users and emails have in common?

They both represent a database table
They both have columns
They both have some unique index field
They likely both need methods to populate (saturate) the object based on some lookup criteria (by unique id for example).

So what does this mean?  It means you probably want to consider having a base class (typically abstract ) that is usually what is called a "model" (the "M" part of "ORM" as mentioned in the comments to the question above).  A typical model class might present some skeleton functionality like:

table property (or class constant) that defines the table in DB that the class represents
primary_key property (or class constant) the defines the primary key field for the table
various class properties (or an array/object of properties) that represent the field available on the object
a findById() method that does basic primary key lookup and object saturarion that might have a common implementation amongst inheriting models.
a delete() method
other methods that might represent common object behavior.

A very simple model skeleton might look like

abstract class Model
{
    // DB schema fields
    protected static $table = null;
    protected static $primaryKey = null;
    // could also have other static field like
    // properties to express relationships (foreign key/tables)
    protected static $hasMany = null;
    protected static $belongsTo = null;

    public function __construct($primaryKey = null) {
        // optional allow instantiation by passing primary key
        if (!is_null($primaryKey)) {
            return self::getByPrimaryKey($primaryKey);
        }
    }

    public static function getByPrimaryKey($primaryKey) {
        self::validatePrimaryKey($primaryKey);
        $fields = self::getObjectFields(true);
        // here is simple case
        // perhaps this code varies if there are relationships and you want to
        // populate related objects as well here.
        $sql = '
SELECT `' . self::$primaryKey .'` AS id, `' . implode('`, `', $fields) . '`
FROM `' . self::$table . '`
WHERE `' . self::$primaryKey . '` = :id
LIMIT 1';

        // not shown - execute prepared statement against DB using $sql
        // assume data is populated into $row
        // saturate and return object if successful
        $returnObj = new self();
        foreach($row as $field => $value) {
            $returnObj->{$field} = $value;
        }
        return $returnObj;
    }

    // override if you need to "hide" certain fields from being saturated
    // requires PHP >= 5.3.0 due to reliance on late static binding
    public static function getObjectFields() {
        $properties = get_object_vars(get_called_class());
        // remove id field, which we will consider as standard field name for
        // primary key and thus needing special treatment
        unset($properties['id']);
        return array_keys($properties);
    }

    // override this function on per-class basis if primary key is not
    // integer value
    public static function validatePrimaryKey($primaryKey) {
        if (!is_int($primaryKey)) {
            throw new InvalidArgmuentException(
                'Integer primary key value required.'
            );
        }
    }

    // maybe some other function you want to force inheriting class to implement
    public static abstract function create() {}
    public static abstract function delete($primaryKey) {}
    public abstract function update() {}
    // etc.
}

class User extends Model
{
    protected static $table = 'users';
    protected static $primaryKey = 'user_id';
    protected static $hasMany = [
        // field name => class info
        'emails' => [
            'class' => 'Email',
            'key' => ['email_id']
         ]
    ];

    protected $id = null;
    protected $name = null;
    protected $passwordHash = null;
    protected $emails = [];

    // perhaps override here to provide logic to also saturate emails
    // if you did not implement that generically in Model
    public static function getByPrimaryKey($primaryKey) {
        // some logic
    }

    // implement abstract functions from base class
    public static function create() {
        // some logic to create a new DB record of this type
    }

    public static function delete($primaryKey) {
        // some logic to delete object of given primary key from DB
    }

    public function update() {
        // some logic to persist object state to DB
    }

    // perhaps some custom methods
    public static function getUserByEmail() {
        // would require working with relate email table a condition for
        // returning User object
    }

    // perhaps some logic to retrieve use object based on login credential
    // or return null if invalid
    public function getUserByLogin($username, $password) {
       // some logic
    }

    // and so on...

    // some getters
    public getName() {
        return $this->name;
    }

    public getPassswordHash() {
        return $this->passwordHash;
    }

    public getEmails() {
        return $this->emails;
    }

    // and so on...
}

class Email extends Model
{
    protected static $table = 'emails';
    protected static $primaryKey = 'email_id';
    protected static $belongsTo = [
        'User'
    ];

    protected $address = null;
    protected $confirmed = null;

    // not shown - implement abstract methods
    // not shown - getters
}

Again, this is pretty basic representation of a typical model inheritance approach.  You can look into popular PHP ORM's to get more full-featured behavior and to get a better idea for how they handle table realtionships and such.

By the fact that you are using password field instead of passwordHash or similar, I am wondering if you are not properly hashing your passwords. This should be considered mandatory for storage of password data.


There are several functions that I would have factored out to make the code more clear:

bool isFactorOf(int possibleFactor, int number) {
    return number % possibleFactor == 0;
}

bool isPrime(int number) {
    int i;
    int max = ceil(sqrt(num));
    for(i = 2; i <= max; ++i) {
        if(isFactorOf(i, num)) {
            return false;
        }
    }
    return true;
}

Note:

I reverted the order of testing the factor (because smaller numbers are more likely to be factors)
the test can end at the sqrt() because if there was a factor bigger than that, there would have been a corresponding factor smaller than that which we would have found earlier in the loop

The stack should be one data structure with checkable size like:

#define MAX_STACK_SIZE 100
typedef struct {
   int size;
   int data[MAX_STACK_SIZE];
} Stack;

void initialize_stack(Stack *stack) {
    stack->size = 0;
}

void push(Stack *stack, int value) {
    assert(stack->size < MAX_STACK_SIZE);
    stack->size++;
    stack->data[stack->size] = value;
}

int pop(Stack *stack) {
    assert(stack->size > 0);
    return stack->data[stack->size--];
}

bool empty(Stack *stack) {
    return stack->size == 0
}

Now the main loop:

At first lets rewrite your solution with the new functions:

while(numberGiven >= num){
    // prime factors
    while(isFactorOf(num, numberGiven) && isPrime(num)){
        push(&stack, num);
        numberGiven /= num;
    }
    num++;
}

I also removed the unnecessary continue (the loop would continue anyway). Using the short-circuit behavior of && already gives an optimization: The primeness is not tested if num is not a factor. Of course it should not be evaluated multiple times so this is more efficient:

while(numberGiven >= num){
    if(isFactorOf(num, numberGiven) && isPrime(num)) {
        do {
            push(&stack, num);
            numberGiven /= num;
        } while(isFactorOf(num, numberGiven));
    }
    num++;
}

Now we only do the checks once.
The next easy improvement would be to make bigger steps with num as above 2 each prime must be odd (which means step sizes of 2).

The next big speed improvement would come from using a list of precomputed primes (for example by sieving) to avoid the slow primeness test.

The factor finding should go in its own function as well:

Stack primeFactorsOf(int number) {
    Stack stack;
    initialize_stack(&stack);
    int possibleFactor = 2
    while(number >= possibleFactor){
        if(isFactorOf(possibleFactor, number) && isPrime(possibleFactor)) {
            do {
                push(&stack, possibleFactor);
                number /= possibleFactor;
            } while(isFactorOf(possibleFactor, number));
        }
        possibleFactor++;
    }
    return stack;
}

Which leaves your main function as:

int main() {
    int givenNumber;
    Stack factorStack;
    initialize_stack(&factorStack);
    printf("Enter the number : ");
    scanf("%d",&givenNumber);
    factorStack = primeFactorsOf(givenNumber);
    while(!empty(&factorStack)){
        printf("%d\n", pop(&factorStack));
    }
    return 0;
}

Addendum

After thinking a bit more about the algorithm I realized that you can completely remove the primeness check because you test from the lowest to the highest factor. Thus you will always find prime factors before you can find the composite factors because they are composed of these (smaller) prime factors.
Leaving out the rather slow primeness check should give you another significant performance boost.


The program already looks correct and simple enough, yet there are some thing that can be improved.

First and most important, you should have a unit test for the important part of the program. To extract this part, create a function bool is_jolly(const std::vector<int> &numbers). Then you can easily write a test that calls this function and checks whether the returned value is what you expect.

There is a bug. When the sequence of number contains two numbers whose difference is 2147483648, the abs function will return a negative value, making your program crash. The difference might also be any other number, so you need to check whether the array index is valid. For a start, you could replace array[index] with array.at(index), which throws an exception instead of crashing.

When you loop over an array, the array index should be of type std::size_t instead of it. Enable the compiler warnings, and it will complain about a comparison between signed and unsigned.

Variable names should not contain the word not. Just try to evaluate if (!not_jolly != false) in your head, or the double negation not_jolly == false. It would be easier to read if it were just if (is_jolly) { … }.

Nitpick: after a semicolon, there should be a space (see the for loops).

To use the algorithm std::fill, you have to include its header. From the top of my head, it should be <algorithm>.

When writing a line to the output, you can merge the strings, e.g. std::cout << "Jolly\n"; — the form you are currently using is perfectly fine, I'm just mentioning this as a shorter alternative.

What you did great:

Indenting your source code consistenly, so that it is easily readable
Importing only a few names from the std namespace
Checking for errors when reading from std::cin (at least in one case)
Writing short and easy to understand code


You'd be better off setting the gutter width as a ratio.
You can use math: fluid to create a fluid layout. Your column widths will then be calculated relative to the container without the need for specifying column width.
Sorry, don't know enough about Susy to give you general code improvement advice.


The simplest solution is extract one function that will form the marker from the parameters and them call it as many times as markers count is:

var markers = [];    // probably you don't need this array
function CreateMarker(lat, lng, markerTitle, markerUrl)
{
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    title: markerTitle,
    url: markerUrl
});
google.maps.event.addListener(marker, 'click', function() {
    $("#tabs").tabs('select', marker.url)
});

markers.push(marker); // you can omit this step if you are not going to work with markers after
}

function initializeMap() {
var myOptions = {
    zoom: 9,
    center: new google.maps.LatLng(42.2340464046899, -71.0956621170044),
    mapTypeId: google.maps.MapTypeId.TERRAIN,
    scrollwheel: false
};

CreateMarker(42.2340464046899, -71.0956621170044, "Pin 1", "#tabs-pin1");
// repeat this call for every marker
}


Given n numbers, find out the least k numbers from them

I assume you can use C++11.

Use initializer lists:

std::vector<int>nums;
nums.push_back(56);
nums.push_back(5);
nums.push_back(6);
nums.push_back(60);
nums.push_back(-6);
nums.push_back(3);
nums.push_back(600);

becomes

std::vector<int> nums = {56, 5, 6, 60, -6, 3, 600};

Use range based for:

nums = getKLeastNumbers(nums, 1);

for(int i=0; i<nums.size(); i++)
{
    std::cout<<nums.at(i)<<std::endl;
}

becomes

for (auto &i : getKLeastNumbers(nums, 1))
    std::cout << i << '\n';

Do not hide bugs. If you detect that someone used your function wrong tell them instead of letting them wonder why the return value doesn't make sense.

if(k<=0 || k > nums.size())
{
    return tmpNums;
}

becomes

assert(k <= 0 && k > nums.size());

or

if (k <=0 || k > nums.size())
    throw std::range_error("k must be bigger than 0 and less than num's size");

You seem to be using the heap functions correctly, however, there are functions more suitable for that. I would pick std::partial_sort.

std::vector<int> getKLeastNumbers(std::vector<int> &nums, int k)
{
    std::partial_sort(std::begin(nums), std::begin(nums) + k, std::end(nums));
    return { std::begin(nums), std::begin(nums) + k };
}

The declaration for getKLeastNumbers is a bit strange. nums is not const and gets modified which feels unexpected. Why can I not use getKLeastNumbers on a const std::vector?. I would prefer a const & to preserve the original value, allow const vector and to be able to initialize nums with an initializer list directly.


Improving performance of VBA data validation script in Access with large data size

There are a couple of micro-optimizations to be made. They probably won't give you the boost you're looking for, but it's worth trying.

First, you can explicitly define the return type. When you don't define one, the compiler defines it as a Variant type, which incurs a lot of overheard compared to the "regular" data types.

For clarity, this

Public Function validateHireDate(hireDate as String)

Is equivalent to this

Public Function validateHireDate(hireDate as String) As Variant

And really should be

Public Function validateHireDate(hireDate as String) As String

But I find it a bit odd that a validation routine is returning a string. I would consider returning a boolean instead. It has a smaller memory footprint than a string and is, in theory, faster than a string.

The second thing you can do is manually short circuit the logic, but you'll have to sacrifice some DRYness to do it.

If Not IsDate(hireDate) Or IsNull(hireDate) Then
    validateHireDate = "Invalid hire date"
Else
    validateHireDate = "Hire date reviewed"
End if

VBA does't have short circuiting logical operations, so no matter what the return value of IsDate(hireDate) is, IsNull(hireDate) executes every time as well. We can unroll the logic a bit to make it more efficient, but be sure to leave a comment explaining your actions to your future self. If you're anything like me, you'll instantly want to undo this optimization the next time you see it if there's nothing telling you not to.

If IsNull(hireDate) Then
    validateHireDate = "Invalid hire date"

Else If Not IsDate(hireDate) Then
    validateHireDate = "Invalid hire date"

Else
    validateHireDate = "Hire date reviewed"
End if

Now, the order here maybe important, and I might not have it right. First, verify that IsDate() can handle a null value. If it can, then you need to study the data to determine which is the more common error state. You want the most common case to come first in order to optimize the logic.

I like your validateEmployeeManager function. You're evaluating the most likely situation first and exiting as fast as possible. You can explicitly declare the return type, but I see no further room for optimization. It's a well written function.

Finally, I would just encourage you to think about whether you need to do this in VBA at all. Access is a SQL based program and, like any SQL, it's better to use set based operations than procedure based ones. I would argue that it's perhaps even more important with Access. You've already noticed how slow the COM based VBA interaction is compared to a regular query, so why not move this logic into a query, or a series of queries? You're not doing anything here that can't be accomplished with the IIF and ISNULL functions. Even a faithful translation should be faster than even the optimized version of the VBA code. Although, I would also encourage you to investigate ways to do this truly set based instead.

Some psuedo-SQL for your first function.

SELECT IIF(ISNULL(Emp.HireDate),"Invalid",IIF(ISDATE(Emp.HireDate,"Invalid","Reviewed"))
FROM Employees

That's the faithful translation. I would find out if the requirements can be adjusted to only return the records that are in error. If the valid records are of no interest to the business, then something like this becomes possible.

SELECT * --don't actually select all
FROM Employees
WHERE HireDate IS NULL
    OR (NOT ISDATE(HireDate))

Which returns only the invalid records.


Representing historical prices of certain financial instruments

What about a slightly different way of creating your classes?

class Quarter
{
    int Year { get; set; }
    List<DailyPrice> Prices { get; set; }
}
class DailyPrice
{
    public DailyPrice(DateTime? date, double? price)
    {
        Date = date;
        Price = price;
        QuarterPeriod = FindOrCreateQuarterObject(this);
    }
    public DateTime? Date { get; set; }
    public double? Price { get; set; }
    public Quarter QuarterPeriod { get; set; }
}

As you create your DailyPrice objects, you can add to the pointer list in the appropriate quarter.  That way if you are collecting aggregate data by quarter all you have to do is spin through your quarters, and then do the aggregation on each quarter's list.

It takes a little more time upfront, and a few more pointers, but you'll save time if you plan to do multiple calculations.


Scripts should have a shebang line. If you happen to be running in a shell other than 'sh' or compoatible, then this script will fail. Add:

#!/bin/sh

as the very first line.

The rest of the script looks fine enough.

The script has a duplicate declaration:

$i -A INPUT -i lo -j ACCEPT

That line says that, if the computer is talking to itself (on the lo interface , the 'localhost'...), that it is allowed to listen to itself.

The other line:

$i -A INPUT -p icmp --icmp-type any -j ACCEPT

says that the computer will listen and respond to 'ping' requests.

The computer will also allow the two standard webserver ports (http and https) but that assumes your webserver is running on those ports.

Also allowed is ssh (port 22).

In essence, the script is doing what you need. You have a server that can listen on the standard http, https and ssh ports only on the public interfaces. You can also ping it.

What is unusual is the very restrictive outbound rules. This is nice, if you can live with it, but, for example, your computer will not be able to connect to anything else, so, it cannot use:

NTP
DNS
send mail
ping other computers
ssh out
etc.

It is recommended practice to have a default-DROP policy for OUTPUT, but, in practice, I have seen very few servers that actually do that.... it is hard to live with.


White spaces are free, use them

Your code is hard to read as all operators are cramped together.

Avoid branches

A missed branch prediction can force your CPU to discard all speculative execution it has done. Although modern CPU's are pretty good at branch prediction, it's a good practice to avoid branches when possible. And in your case it will reduce iterations in the loop.

int screenx = -(int)camerax - blocksize;
for (int x = 0; x < sizex; x++){
    screenx += blocksize;
    if (screenx > -blocksize && screenx < gamewidth){

should be:

int screenx = -(int)camerax - blocksize;
int xstart = Math.max(0, -(blocksize + screenx) / blocksize);
int xend = Math.min(sizex, (gamewidth - screenx) / blocksize);
screenx += blocksize * xstart; // Edit: We need to keep this value updated too.
for (int x = xstart; x < xend; ++x){
    screenx += blocksize;

and similarly for the inner loop. Depending on the ratio camera size to level size (if I'm interpreting your code correctly) this can give a big speedup.

Hint: The y direction iteration start and end values are independent of the current iteration in x direction so calculate the yend and ystart before entering the first loop.

Caution: The above xstart and xend may be off-by-one as I don't know what all the variables are, adjust to taste.

Edit: Oops just realized this is what Neil mentioned in the first point on his answer. But I'll leave this here as it's an example of what he said.

Edit2: Missed the incrementation of screenx prior to entering the loop.


Check if there's exactly one match in a vector

The standard library find functions return the .end() iterator for the container if they fail to find anything. We could follow the same convention, instead of using std::optional.

Rather than nesting the checks, we could split it into two separate loops, and use  std::find_if from the <algorithm> header, something like this:

auto const is_in_range = [&] (int item) { return std::abs(item - zero) < range; };

auto const first = std::find_if(data.begin(), data.end(), is_in_range);

if (first == data.end())
    return data.end(); // found nothing

auto const second = std::find_if(std::next(first), data.end(), is_in_range);

if (second != data.end())
    return data.end(); // found a second entry

return first;


Populate null fields in an object through reflection

A different option is to fix this at the creation of the XmlSerializer.  The XmlSerializer constructor can take a parameter for XmlAttributeOverrides

You could create a method to auto add the XmlElementAttribute, if missing, or set the IsNullable to true.

public static XmlAttributeOverrides AddIsNullableTrue(Type type)
{
    var xmlOverrides = new XmlAttributeOverrides();
    foreach (
        var prop in
            type.GetProperties()
                .Where(p => !p.PropertyType.IsValueType || p.PropertyType == typeof (string)))
    {
        var xmlAttributes = new XmlAttributes();
        var attr = prop.GetCustomAttribute<XmlElementAttribute>();
        if (attr != null)
        {
            attr.IsNullable = true;
        }
        else
        {
            attr = new XmlElementAttribute() {IsNullable = true};
        }
        xmlAttributes.XmlElements.Add(attr);
        xmlOverrides.Add(type, prop.Name, xmlAttributes);
    }
    return xmlOverrides;
}

Now when you create your XmlSerializer you just need to pass in the XmlAttributeOverrides

XmlSerializer SerializerObj = new XmlSerializer(typeof(TestClass), AddIsNullableTrue(typeof(TestClass)));

This example is assuming the class is called TestClass.  Now you don't need to populate null fields and fields will be output to XML that are null.


Your design is a little bit confusing. You define your class as a template class, but just about everything takes and returns a double. Generally, you should try and be consistent: will this class work for any numeric-like T? Then make sure it has constructors that take a T instead of a double:

threevector(T a = T(), T b = T(), T c = T())

Similarly for the overloaded operators that multiply/divide by a scalar, and so on.

The name threevector is awkward. At the least it should be three_vector, but that's still a little awkward. vector_3d is more of the "standard" name for this kind of thing.

Your include guards should generally be in all-caps. This is because they are global in scope, and you want to do as much as possible to minimize the possibility of potential name clashes.

#ifndef threevector_h_ // should be THREE_VECTOR_H_
#define threevector_h_ // or VECTOR_3D_H_

You have some semi-colons where they aren't needed:

threevector(const double a = 0, const double b = 0, const double c = 0):
container({{a,b,c}}) {}; //standard constructor
threevector(const threevector& a): container(a.container) {}; // <--- Not needed

Comments like //standard constructor are obvious and don't really need to be there. Further, your copy constructor and copy assignment operator are redundant; the compiler generated ones are sufficient.

It's often easiest to write operator+ (and -, * etc) in terms of operator+=:

vector_3d operator+(const vector_3d& a, const vector_3d& b)
{
     vector_3d result(a);
     result += b;
     return result;
}

For something this simple, it's unlikely you'll be able to speed it up much. The only potential that I can see is replacing the call to pow() in:

double abs_sq() const {return pow(abs(),2);}

with something like:

T abs_sq() const
{
    const T ab = abs();  // abs() should also return a T
    return ab * ab;
}

which avoids the overhead of a function call to pow. In practice, this is unlikely to make much of a difference, however.


I don't get the point of returning the stack from the handle_vertex function. The return value is never used (and the stack which is passed as an argument is modified in place).
The topological_sort functions prints the stack, doesn't return anything and then it's returned value is printed: print(topological_sort(graph)). There're two reasonable options here:

not printing the returned value of the topological_sort and just calling it instead
Returning the stack from it instead of printing it inside the function.

The neighbors name here: for neighbors in graph[vertex] is misleading. This variable represent just one neighbor at a time. I don't see why would you make it plural.


Console application for providing detailed error messages

Make a function that writes an error message (String) to the console, then exits with failure error code. But I'm not sure whether this would mess up your returns and overall control flow.

Other than that, I don't know. Yes, you can golf the string to "Unable to open X : " + x + ", it does not exist on the server", but all you're doing is making the error message harder to find when debugging later.

That said, "pretty" is pretty (Hah) abstract. As it is now, the code is perfectly readable, and it doesn't contain too much duplication. It doesn't contain any performance issues either. What you're seeing here is your code reaching the lowest Kolmogorov Complexity it can.

But let's say, for the heck of it, you were to create some sort of function that takes a catalogName and returns either null or a Catalog object. In case of null, you have to call another function to get the error message. If you did that, you're just relocating the if statements. It also makes the design confusing. Basically, I don't think you can because you have to check and you have to report. In my opinion, you did that the prettiest way possible.


Draw crosshairs on the screen - ZedGraph

Mis-Matching curly braces are not a good thing, you do it all over the place, it makes your code hard to read

   if (fromKeyboard)
       point = curve.Points[index1];
    else if (lineGraphControl1.Graph.XAxis.Mode == XAxisMode.Parameter)
    {
        ZedGraph.CurveItem outputCurve;
        p.FindNearestPoint(mousePoint, curve, out outputCurve, out index1);
        if (index1 >= 0)
           point = curve.Points[index1];
    }
    else
    {

it should look like this

   if (fromKeyboard)
   {
       point = curve.Points[index1];
   }
   else if (lineGraphControl1.Graph.XAxis.Mode == XAxisMode.Parameter)
   {
        ZedGraph.CurveItem outputCurve;
        p.FindNearestPoint(mousePoint, curve, out outputCurve, out index1);
        if (index1 >= 0)
           point = curve.Points[index1];
   }
   else
   {

Indentation only on an if statement all by itself is fine, I personally don't like it, but when an else statement is added to the if statement, it starts to muddy the waters around your if statement and make it look sloppy.

The single, one-line if statements should also have a buffer zone after them as well.


Two-layer RAII to support a critical section

We can simplify that a lot.

You are not really using RAII on the CriticalSection as you declare it in one place then initialize it in another. But CRITICAL_SECTION is a type as you pass a pointer around.

Why not simplify a bit:

class GetLock;
class CriticalSection {
public:
    CriticalSection() {
        InitializeCriticalSection(&m_CS); // get a pointer to the member
    }
    ~CriticalSection() {
        DeleteCriticalSection(&m_CS);
    }
private:
    friend class GetLock;   // Only GetLock should be locking/unlocking this object.
    void lock() {
        EnterCriticalSection(&m_CS);
    }
    void unlock{
        LeaveCriticalSection(&m_CS);
    }
private:
    CRITICAL_SECTION    m_CS;   // Make this a member
                                // Now make the constructor initialize it.
}

Now its use case becomes.

CriticalSection  criticalSection;

int main() {
    // Critical section variable already up and running.
}

If we look at the GetLock.
I would not passes pointers as parameters. This means people can accidentally pass a nullptr and thus cause your code to break. Always pass by reference if you have to have parameter there.

class GetLock {
public:
    // Pass a reference to the CriticalSection
    GetLock(CriticalSection& plock)
        : m_csg(plock)
    {
        m_csg.lock();
    }
    ~GetLock(void) {
        m_csg.unlock();
    }
private:
    CriticalSectionGuard& m_csg;   // Keep a reference to the critical section.
};

Now this can be used like:

DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
    GetLock lock(criticalSection);

    return 1;
}

Note the difference above to your version:

    GetLock(&CSG);   // This creates a temporary object.
                     // This object is destroyed at the end of the
                     // statement (which is the ;).
                     // This mean you call lock() and unlock() before
                     // the end of the line.

I should also note that using global variables is considered bad practice. You should try and design your program so that you pass the things being manipulated around as parameters (or part of an object). I can't really suggest an improvement with knowing more about the code.


I'd rather use the FacebookAuthorId and FacebookLocationPostId as primary keys, because your logic ensures them to be unique. In case of your current solution you would still require (unique) indexes on these fields (in order for lookups to be efficient) so there is no reason not to use them as primary keys.
Given suggest optimization you don't need to check/insert an author record   LocationPost_Save, just use the merge to insert/update the data in the table, and create a separate Author_Save SP that will do the same job for Authors.

Having said that, assuming that you are using one of the high-level languages :) and you're developing a long-living solution I would actually recommend you to use one of the ORMs available for your language to interact with the database. It'll take a bit longer at the beginning, but you'll get a more flexible solution in a long term.


Recursing function to create dir in python

First, os.makedirs already creates all the intermediate directories in the path. That is its job. So there is no need to use recursion.

There is also no need to use os.path.exists, because you are using the exist_ok=True argument with os.makedirs. This means that os.makedirs will not error out if the directory already exists.*

Your type hint for the return type should be None, since you are not returning any values.

I would also change the name of your function. I think the name makedir is too close to os.makedirs, which is confusing.

import os

def makedirs_for_file(filepath: str) -> None:
    os.makedirs(os.path.dirname(filepath), exist_ok=True)

*Unless you are using a Python version before 3.4.1. In this case, os.makedirs may still error out, depending on the mode of the existing directory. See the documentation for more details.


square the elements of a sorted list and give the output in sorted order

If you start at both ends and compare these values, you can step down towards the center, unshifting the values, squaring them and unshifting them to the resulting array.

You don't need to square the values until you add them to the array. You can compare to find the greater value by negating the left side.

One \$O(n)\$ solution is as follows

function sortSquares(arr) {
    const res = [];
    var start = 0; end = arr.length - 1, idx = end;
    while (start <= end) {
        res[idx--] = (-arr[start] > arr[end] ? arr[start++] : arr[end--]) ** 2;
    }
    return res;
}

// Test code
[
    [-9,-5,-0.5,0.6,1, 2, 3,8],
    [1, 2, 3,8],
    [-10, -8, -3, -1, -1, 1, 1, 1],
    [0.6,1, 2, 3,8],
    [-9,-6,-3,-2,-1],
    [-9,-6,-3,-2,-1,1,2,3,6,9],
].forEach(a => log(a, sortSquares(a)));

function log(data, data1) {
   data = "[" + data + "] -=>> [" + data1 + "]";
   info.appendChild(Object.assign(document.createElement("div"),{textContent: data}));
}


Well, it's a good idea to minimize dependency on global state.
Doing so enhances testability and reduces dependencies, especially the hidden type.

Still, if you have such pervasively used state as Game, it's a valid thought to make it global instead of passing it around everywhere.
Pass the arguments needed, no more, no less.
It could be. Or not. In any case, it would reduce your flexibility in using your code for example for a tic-tac-toe contest.

Now lets critic your code:

validPos seems to be redundant, being a simple function of board. Or is there some extra magic?
Avoid dynamic allocation where it doesn't help. That means the memory-used is scoped and the block is reasonably small, like those allocations in main.
Anyway, avoid repeating your types to avoid mismatches. It should have been:

Game *game = malloc(sizeof *game);

Parameter names are valuable space for documenting an arguments use.
At least scoreBoard and declareWinner could use a bit more:

void declareWinner(Game *, Player* winner, Player* looser);
void scoreBoard(Player *, Player *, int round);
// documented my guesses what the pertinent arguments mean


Check a string to see if it is a palindrome

I would prefer the first one for a few reasons.

It's more readable and easily understandable in my opinion.
There's only one string, so less overhead. (Which is negligible unless this is being called a lot.)
There's only one array. Reverse creates a second array.

That being said, an actual review is in order.

Methods that return a boolean value should have names of the form IsSomething or HasSomething. A great name would be IsPalindrome.
Neither method accepts anything but a string. Numbers can be palindromic too. Wouldn't it be a nice addition if we could pass an integer to it as well? (Without explicitly calling .ToString() before passing it in that is.)
I like that you're only checking for i < j instead of i <= j. It saves a useless iteration when there are an odd number of characters.
I also like the while loop. It's a lot cleaner than the for loop suggested by another answer.
I won't speak much on the second method, because I think @elios provided a nice implementation of it.


Vector4

An invalid input (out of range index) should never silently return an arbitrary result. If you just return Vector4.Zero you will hide bugs in your code. Computations will be wrong and you will need to debug step by step your code to understand where. Especially for complex expressions this is tedious and time consuming. Throw an exception for wrong inputs!

Also you should use a proper name for parameters, a is almost meaningless.

if (index > 3 || index < 0)
    throw new ArgumentOutOfRangeException("index", index, "Must be in range [0..4)");

Logic to return element value is hard to read:

  return (a == 0 ? row1 : (a == 1 ? row2 : (a == 2 ? row3 : row4)));

Let's see few alternatives:

switch (index) {
    case 0: return row1;
    case 1: return row2;
    case 2: return row3;
    case 3: return row4;
    default:
        throw new ArgumentOutOfRange(...);
}

Or:

if (index == 0)
    return row1;
else if (index == 1)
    return row2;
else if (index == 2)
    return row3;
else if (index == 3)
    return row4;
else
    throw new ArgumentOutOfRange(...);

Why did you name row1 variable you access with index 0? It's an implementation detail but it may cause subtle bugs. Keep names self-descriptive and coherent (BTW why vector elements are called rowX, can't it be a column vector?)

However bigger problem is logic itself. There is no reason to have four separate variables. Array access is pretty fast and highly optimized (moreover using that if logic you may highly impact performance if JIT compiler won't generate CMOV assembly instruction instead of multiple CMP and JZ (because they're not branch-predictor friendly). Your final code should then be:

private Vector4 _columns = ...

public Vector4 this[int columnIndex]
{
    get { return _columns[columnIndex]; }
    set
    {
        if (value == null)
            throw new ArgumentNullException();

        _vectors[columnIndex] = value;
    }
}

Matrix4

With Vector4 simplified code you will also simplify SwapColumns(), essentially it may be your original unchanged code. What's the C# feature related to properties you want to have? If Vector4 is an immutable type then you may go with a struct (and note it may be mutable internally).

In general if you're coding for performance in a multi-threaded environment (like a game) I think you should seriously consider to keep your Matrix4 an immutable struct. When you really need to swap columns you create a new object. If it's not an operation you perform thousands times per second it will let you (and eventually JIT compiler) to perform optimizations and avoid locks.

Also take a look to SIMD extensions in .NET Framework. SIMD instructions may greatly improve performance.


Is using a set a good solution for avoiding having the same return value twice, if the two solutions are equal? (I am worrying that they might not be always exactly equal, due to imprecision in calculation.)

Instead of a set, IMO a vector would be a better structure.  It is essentially a "list of solutions."  Instead of your (set [x1 x2... simply wrap it in a vector:

(vec (hash-set x1 x2))

There's nothing wrong with using a set, but vectors are more common. Sets tend to be used more for utility in computation, rather than as a way to convey expression results.  There are always exceptions, and you could very well make one here if you chose to do so.

  Independently whether sets should be used for this particular problem or not, is there a better way to compare two sets for equality, with a custom function between the elements? (C.f., line (1))

I'm not the expert on floating-point comparisons, but I wonder if the following would work, or if it's too naive:

(def s1 #{1.0 2.0})
(def s2 #{1 2})
(= (set (map double s1)) (set (map double s2)))  ; true


The point of FizzBuzz is to weed out obviously unqualified candidates, not to over-optimize the solution or to show off.  Your code is a fine interview answer.

Make sure that your braces all match up.  It would be more conventional to use 4 or 8 spaces per level of indentation.

My main suggestion — and this is an opinionated nitpick — is to tone down the comments, because comments that restate obvious code give the impression that you might be unfamiliar with the language.  Experienced programmers never write // Go from 1 to 100 to explain for (int i = 1; i <= 100; i++).  If you feel compelled to demonstrate your documentation skills, write some JavaDoc instead.


From a once-over:

You keep creating the same function in Pub.ajax:

    xhr.onload = function () {
        if (this.status === 200) {
            config_ajax.callback(xhr.responseText);
        }
    };

You could consider assigning this function once to a var onloadFunction which you then assign like this : xhr.onload = onloadFunction. On the whole, Pub.ajax needs to be reviewed by you with DRY in mind.
getBlockedProperty could be written in a much shorter fashion:

function getBlockedProperty(item) {
  return item ? item.blocked : false;
}

getIndexFromToken is odd, I have no idea what it really does, not a single variable or parameter is called token and there is not a single line of comment.
publik.addItem could use Object Literal Notation to make it more succint:

publik.addItem = function (callback) {
    var temp = {
      blocked : false;
      callback : callback;
      response_text : null;
    };
    queue.push(temp);
};

lowerCamelCasing -> You are not using it everywhere
A minor observation, would it not be much easier to just send synchronous requests instead of building a custom queue ?


You really don't need:

    System.out.print("Enter your first number: ");
    numOne = userInput.nextFloat();
    System.out.print("Enter your second number: ");
    numTwo = userInput.nextFloat();

four times. Just get the function first and then the two numbers independent of which function was chosen.

Also, do you really need to write functions for simple mathematical operations?

Finally, you don't need getAnswer(answer); four times either.


funcs.h

Neither funcs.c nor funcs.h require anything from stdio.h or string.h, so you shouldn't be including those there, move them to main.c instead. But you should get into the habit of adding include guards to your headers. So either use this at the top:

#pragma once

Or, to be completely standard and portable:

#ifndef FUNCS_H
#define FUNCS_H

// contents of header here

#endif // FUNCS_H

funcs.c

The static encode mapping is fine as you have it, but would also be fine inside the get_index_digit function (static also of course). Since that is the only direct user, it would be slightly better inside in my opinion.

I'd change your signature and preamble for the encoder to:

#include <assert.h>
// ...

char get_base64_digit(const unsigned int base64, unsigned int digit_number)
{
  assert(digit_number < 4);
  // ...

Passing a negative index or anything greater than 3 is a programming error, it should be caught as early as possible and be a hard failure.

You can get rid of the switch by collapsing all cases:

return get_index_digit((base64 >> (18 - 6*digit_number)) & 077);

Note that this masks the bits even for the zero case, which is safer. But you might want instead to assert on the fact that the bits above index 18 are all zeros - slightly different contract. (I'd prefer just masking them off though.)

main.c

char* text = argc == 2 ? argv[1] : '\0';

That '\0' is bad. Happens to work, but doesn't convey the right information. text is a pointer, not a char. Replace with:

char* text = argc == 2 ? argv[1] : NULL;

But that's actually not a good idea either. What you actually need is an empty string (or bail out).

const char* text = argc == 2 ? argv[1] : "";

Then you have:

unsigned final, temp;

But you're not using temp anywhere, except for setting it to zero. And you're always initializing final to zero in the for loop. So to help simplifying that for a bit:

unsigned final = 0;

Also a slight inconsistency: you're using unsigned here, but used unsigned int in the declaration for get_base64_digit - pick one version and stick to that (they are completely identical).

As for the loop:

for (int x = final = temp = 0; x < (remainder == 0 ? text_len : text_len - remainder); x += 3) {

That line is too long, and more complex than it needs to be. Removing final and temp will help:

for (int x = 0; x < (remainder == 0 ? text_len : text_len - remainder); x += 3) {

And might help you to see that the conditional is unnecessary. If remainder is zero, text_len and text_len - remainder have the same value. So:

for (int x = 0; x < text_len - remainder; x += 3) {

Or move that subtraction out of the loop for an even simpler structure.

The last lines are a bit odd:

} else
        return 0;

return 0;

Remove the else, it is not useful. Also mixing braced and non-braced blocks in an if/else chain isn't a good idea. This is a matter of style, but always using braces is usually safer. If you want to omit them for single-statement blocks, only do that if you only have single-statement blocks in the if/else chain.

Last tidbit: you sometimes have ){ (no space), and sometimes ) { (one space). Stick to one, preferably the one with the space. You also sometimes have an empty line at the start of blocks, sometimes not. If you feel like a bit of vertical separation is good there, try putting the { that starts the block on its own line (as I did in the get_base64_digit above), and look at the Linux coding style guidelines for some other tips that you may, or may not :-), like.

clang-format is an excellent auto-format tool, and a lot of dev tools (including Vim and Emacs) can be made to use it. Try it out.


LeetCode: Maximum XOR of Two Numbers in an Array

In XorTreeNode you're not using the field Val

public void Insert(int[] nums)
public int GetMax(int[] nums)

Having two methods that must take the same data to operate on is hazardous and should be avoided. Either provide the data to the constructor or you should only have one public method with the data set as argument:

public int FindMaxXor(int[] nums) { Insert(nums); return GetMax(nums) }

You can invert a bit in the following way:

bit ^ 1

It can be used to simplify this:

                int bit = (num >> i) & 1;
                if (cur.children[bit == 1 ? 0 : 1] != null)
                {
                    xorValue += (1 << i);
                    cur = cur.children[bit == 1 ? 0 : 1];
                }
                else
                {
                    cur = cur.children[bit];
                }

to

        int bit = ((num >> i) & 1) ^ 1;
        if (cur.children[bit] != null)
        {
          xorValue += (1 << i);
          cur = cur.children[bit];
        }
        else
        {
          cur = cur.children[bit ^ 1];
        }

You can insert numbers and search for max in the same operation, because every new number only need to compare with already existing numbers.

So you can change GetMax(...) to:

private int GetMax(int num)
{
  XorTreeNode cur = _root;
  int xorValue = 0;
  for (int i = _numBits; cur != null && i >= 0; i--)
  {
    int bit = ((num >> i) & 1) ^ 1;
    if (cur.children[bit] != null)
    {
      xorValue += (1 << i);
      cur = cur.children[bit];
    }
    else
    {
      cur = cur.children[bit ^ 1];
    }
  }

  return xorValue;
}

and Insert(...) to:

public int FindMaxXor(int[] nums)
{
  int result = int.MinValue;

  foreach (var num in nums)
  {
    result = Math.Max(result, GetMax(num));

    XorTreeNode cur = _root;
    for (int i = _numBits; i >= 0; i--)
    {
      int bit = (num >> i) & 1;
      if (cur.children[bit] == null)
      {
        cur.children[bit] = new XorTreeNode();
      }
      cur = cur.children[bit];
    }
  }

  return result;
}

where _numBits is defined as a class const field:

private const int _numBits = 31;

If you know that the nums array contains only small values there might be a significant performance improvement in finding the leftmost significant bit:

  int max = nums.Max();
  while (max > 0)
  {
    _numBits++;
    max >>= 1;
  }

in the start of the Insert(...) method. _numBits should then not be const and initialized to zero obviously.
If the numbers span over the entire int+ domain this may slow the entire process.


Clean up after shell script that is run via k8s pod on a gpu node for health check

#!/bin/bash

Why not plain /bin/sh?  I don't see any non-POSIX shell constructs in there.

sort | uniq

We could replace with sort -u (that's a standard option).

     echo "Found pending blacklist on ${bad_gpu}"
     exit 1

That message should go to standard error stream: >&2.  The same may be true of the other informational messages.

 for bad_gpu in "{$bad_gpus}"; do

Really?  "{$bad_gpus}" is a single token; I think you meant $bad_gpus there.  Especially as we then expand $bad_gpu unquoted in the next line.

grep Pending| grep Yes > /dev/null 2>&1

If Pending and Yes always occur in the same order, we could simplify to a single command (and we don't need the redirection):

grep -q 'Pending.*Yes'

   if [ $? -eq 0 ]; then

That's an antipattern - it's a sign that you need to move the preceding statement into the if:

if nvidia-smi -i "$bad_gpu" ...
then


C++ operator overloading for rationalNumber

Style:

Use an initialiser list for constructors, with meaningful parameter names. example at the end.
Please use the right type for negative - true/false makes it a lot easier to read and understand inline what type negative is.
Naming: The toString() is easier expressed by returning a std::string - that can be used as-is or forwarded to std::cout or other logs. If you want to use a log output, (e.g. std::cout) it can be trivially implemented using a template operator<< with a generic ostream input - in this case it is not required (see below)
The operator+ can be expressed in a single line, without the temporary added variable.
it is desirable to make gcd an non-member file-local static function (static gcd(int a, int b)) the rationale being that the logic:

doesn't depend on the state (or const-ness) of the Rational object (so non-member)
doesn't need to access the (private/protected) innards of Rational(so non-static, non-friend)

In main, the for loop can be shortened (in general, if a function call chain helps avoid a temp variable, do so). example at the end.

The same logic (avoiding a temp variable) holds for defining r3 and r4 inlined when adding them to the map.

vector v is unused.
Include what you use: vector, map, iostream, cmath (and iterator if you decide to use ostream_iterator.
maps don't require an input iterator during insertion. Use std::make_pair(a, b) to cut down on the verbose template boilerplate.

Logical Issues:

Translation into abs and negative is done in the ctor and not followed up well in other places. This will fail for negative test cases. hint: why is negative required as a member?
adding 1/4 and 1/2 results in 6/8 - while this isn't incorrect, this defeats the purpose. Invoke gcd there.
Depending on how you want your object to behave, handle the case of (den == 0), either by explicity asserting against its occurence, or by adding special handling for arithmetic operators. You don't want a 1/0 + 5/2 == 2/0 comparison.

Constructor style preferred:

RationalNumber() : num(1), den(1), negative(false) {}
RationalNumber(int numerator, int denominator)
: num(abs(numerator))
, den(abs(denominator))
, negative((numerator < 0) == (denominator < 0))
{
    //use gcd here
}

Terser loop style suggestions:

for (map<RationalNumber, string>::iterator it = S.begin(); it != S.end();++it)
{
    std::cout << "comparing:" << itr->first.toString() << itr->second << std::endl;
}

or the even terser lambda:

transform(S.begin(), S.end(), ostream_iterator<string>(cout, '\n'),
    [] (const pair<RationalNumber, string>& p) { return p.first.toString() + " " + p.second; });

edits:
Moved code examples to the end - as code indents don't work in between bulleted points.


PHP Custom $_GET checker function performance

If your aim is to go DRY, I would consider taking it one step further. You are writing a function for a common use case indeed, but one could wonder if this is only used for $_GET variables. What about $_POST or $_SESSION or some none magic array your application uses...

I'm used to working with Laravel, and this framework offers a very basic support method called array_get (docs here). I use it so often, it should really be part of core php.

Allow me to rewrite your function to this API. (Note that I'll leave . syntax for nested arrays out, though it has proven useful to me it would take us to far.)

function array_get($array, $key, $default = null) {
  if (! array_key_exists($key, $array)) {
    return $default;
  }

  if (is_null($array[$key])) {
    return $default;
  }

  return $array[$key];
}

// usage
$get = array_get($_GET, 'myKey', 'default');
$post = array_get($_POST, 'myKey', 'default');
$session = array_get($_SESION, 'myKey', 'default');
$value = array_get($myArray, 'myKey', 'default');

I'm not sure about you $empty parameter. It doesn't feel entirely right to me to have it in there, but I may be wrong.

If you decide to stick with your function, try to clean it up a bit.

I feel the comments are obsolete when you are performing such trivial, perfectly readable tasks.
All the else statements are obsolete, they just clutter the code.
Nesting control structures is rarely a good idea. It makes the code harder to read. You'll be surprised how rarely you have to nest control structures if you take this rule into account. If you have to, you are probably doing something else wrong (single responsibility? extract another function perhaps)
Nice job on the early returns!

Have a look at this:

function getset( $get, $default, $allowEmpty=FALSE ) {
    if (! isset($_GET[$get]) ) {
        return $default;
    }

    if ($allowEmpty) {
        return $_GET[$get];
    }

    if ( $_GET[$get] === '' ) {
        return $default;
    }

    return $_GET[$get];
}

update:
Concerning your question about the $allowEmpty, I think you are approaching the problem from the wrong angle. Either you want a variable to have a value, or you want to default a missing variable.

// default
$foo = array_get($_GET, 'foo', 'default');

// required
$bar = array_get($_GET, 'bar');
if (is_null($bar)) {
  // required var missing
}

I feel cramming that $allowEmpty into the function violates he SRP somewhat. You are not just getting a value from an array anymore, you are validating it as well.

Do feel free to add it however, it is your code after all. It should be as simple as adding a fourth parameter to the array_get function and checking it similar to the way I provided in the refactored getset function.


Calling methods of another module from a module, from a class extending both?

Since inheritance and interface both has some problems of their own, high level languages like ruby, python supports a different way for organizing code- Mixin.

The code you have written involves mixin, you can see this as interface with implemented methods.When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.

say we have a module for debugging. we want to use this in many classes and modules. we can just include this debug module to our classes and all methods for debugging will be added in the code as own method of our class.

see the code bellow:

module Debugger
  def log
    #do stuff
    puts "#{Time.now}: This is a log"
  end
end

class C
  include Debugger

  def initialize
    #do stuff
  end

  def run
    #do stuff
    log
  end

end

c =  C.new
c.run


It seems you're allergic to for loops for some reason; for example, in ft_strnew:

for (size_t i = 0; i < size; i++)

There are examples elsewhere.

Don't predeclare your variables, e.g.

int     i;
int     j;

This hasn't been needed for 20 years. Declare them where they're used.

Replace this entire loop:

size_t  i;
i = 0;
while (i < size)
{
    temp[i] = '\0';
    i++;
}
temp[i] = '\0';

With this:

memset(temp, '\0', size+1);

Otherwise, your entire approach to arbitrary-size integer math is a quite slow one. (Other libraries have solved this, but it's nice that you're trying to learn.) You can't be doing this character by character; rather you need to do it integer by integer. Do some googling about arbitrary-precision integer arithmetic on 64-bit architectures.

A comment on something you said:

  They work correctly but the larger the numbers the longer the time it takes.

No arbitrary-precision library can escape this. The execution time of even the best libraries will scale according to the size of the input when it exceeds the size of the machine word.


I think a simple way to address the problem is by building the board first then printing it:
empty_row :: String
empty_row = "+---+---+---+"

board_repr :: type of b -> String
board_repr b = empty_row + concat ( map (\x -> (build_row x b) + empty_row ) [0, 1, 2] )

main = print (board_repr b)

Take this as pseudo-code pointing in an interesting direction by separating the concerns of building a representation and printing it.


You have similar code and similar performance issue in your other question about points instead of lines.  I answered that one here. Some of my answers can apply here particularly as to the repeated use of .ToArray()?

If you skipped everything as arrays and went with IEnumerable<Line> or IEnumerable<Point> for inputs, output, and anything inbetween then you might see some performance benefit.  Might.  Don't know until you run it.  But sounds like you are talking about big collections.

If you try using IEnumerable and things are still slow, I'd try to use Parallel.For with a range partitioner.

That should address your major concern.  On a minor concern, the Line class is good enough and looks like something I once wrote.  I eventually switched from StartPoint and EndPoint to Point1 and Point2 since some readers may think StartPoint should somehow be 'less than' when compared to EndPoint or that it should be drawn like a vector that somehow starts at StartPoint and is then drawn to EndPoint.  To avoid such needless notions, I went with the generic Point1 and Point2.


Why are you using an abstract class in the first place?

I more think you should use a factory method. You could store the headers and the parser in a class, but make it an immutable class.

Another note, or maybe just my personal opinion: It is to my knowledge not a Java convention to prefix all member fields with m.

The only really valuable code that you have is this:

mCreator = new RequestCreator.Builder()
    .headers(getHeaders())
    .parser(getParser())
    .build();

and

mRequest = mCreator.createRequest(UserService.class);

So let's make factory methods!

public class Requests {

    public static RequestCreator newCreator(Headers headers, Parser parser) {
        mCreator = new RequestCreator.Builder()
            .headers(headers)
            .parser(parser)
            .build();
    }
}

public class UserRequest {

    private interface UserService {
        @GET("/users/{id}")
        User getUser(String id);
    }

    public static Request<User> createUserRequest(Headers headers) {
        return Requests.newCreator(headers, null).createRequest(UserService.class);
    }

}

Problem solved(?)


User Confirmation using a Userform Modeless and DoEvents

Yup, it's wrong1 :)

Forms (and literally everything in Windows) already run their own message loop: whenever you feel the need to wrap a form with a no-op "wait until user does something" DoEvents loop, you are essentially forcing your form into a procedural dialog paradigm, keeping the VBA runtime much, much more busy than it needs to be.

Embrace the objects!

The idiomatic way to handle this in VBA is to adopt an event-driven paradigm: instead of wait-looping for a state change and essentially "poll" your form periodically until its .IsHiden (typo?) state changes, have a presenter class that's responsible for dealing with the state of the form, by responding to its events.

Dim Ui As New UserForm1

Instead of a local (auto-instantiated?) object variable, make that a WithEvents variable at module level (that's why you need a class: only class modules can have WithEvents variables).

Option Explicit
Private WithEvents UI As UserForm1

Private Sub Class_Initialize()
    Set UI = New UserForm1
End Sub

Now this class can handle any of the UI events - whether they're inherited from the UserForm base class, or custom-defined on the UserForm1 default interface, like this:

Public Event ByeBye()

Private Sub CommandButton1_Click()
    Debug.Print "YES!!!!"
    this.Confirmed = True
    this.IsHiden = True
    Me.Hide
    RaiseEvent ByeBye
End Sub

Note the indentation is made more consistent (and arguably better, IMO) by adding an indent level for all members.

Doing this allows the presenter class (the one that declares a WithEvents instance of the form) to handle this ByeBye event:

Private Sub UI_ByeBye()
    'form is no longer displayed
End Sub

Note that this is an entirely different paradigm: you can't do stuff in the same procedure that's responsible for showing the form anymore - it forces you to separate the responsibilies!

1 Only because the form isn't modal though: a modal form suspends execution, which makes the explicit loop useless; the form's state can be read on the statement that immediately follows the call to .Show, since that next instruction will only run after the form is dismissed. That isn't the case for a non-modal form, so instead of loop-waiting, we need to embrace the asynchronous nature of the non-modal messenging, with events.


Solving the coin change algorithm using 10 coins

I'm really struggling to read your code, but I'm trying to take a crack at it. In the mean time, here are some things about your code in general – not about the algorithm you use.

Static fields. You do not want to use static fields for bl, ex etc. My guess is you added them because you set them in the main method, which is static by definition. static means that bl etc. will be shared by all objects of that class – you do not want that.

The best way to fix this is to initialize the field directly or in a constructor, not externally. In other words, something like private boolean bl = false; will do, or put all the default values in a constructor:

public Numbers() {
    bl = false;
    list = new ArrayList<Integer>();
    // etc.
}

Aside from the static problem, think of code re-usage: someone who just wants to use your Numbers class shouldn't have to care about what bl and ex (etc.) do, so they shouldn't have to initialize them. It's not only inconvenient for another user, but it's also dangerous to let the inner workings of your class at the mercy of the user.

Mixing fields and parameters

Two examples:

public void test(int k) {
    int r = 0;
    for (int i = k; i>0; i--) { // use of k
        if(!ex) {
            if(sum(list) + i > target) { // use of target

public void printFill(ArrayList lt) {
    int i = 0;
    for ( i = 0; i< lt.size()-1; i ++) {
        System.out.print(lt.get(i)+","); // use of lt
    }
    // ...
    i = list.get(list.size()-1); // use of list

k and target in the first example, lt and list in the second example are the same, and this is very dangerous. You want to either stick with the parameter or the field only, but please avoid using a class field and a parameter interchangeably.

The most important point here is to decide whether to use a parameter or the field. printFill seems to be an important part of your algorithm, so I would personally tend to use the field rather than the parameter here, because the code is so specific that it will hardly be re-usable for something else.

As for test(), I would remove the target field altogether as it's only used interchangeably with the parameter k in test(int k). I don't see much sense in keeping the value after test() returned its result. It is more convenient for a user to do numbers.test(25) than numbers.setTarget(25); numbers.test();.

Further issues. The spacing one is somewhat minor, so please take it with a grain of salt.

Naming. Your code is hard to understand because I have no idea what bl stands for. test and test1 also don't hint at what the methods do, either. printFill doesn't fill anything but removes elements from the list.
Structure. If you're finding yourself getting lost in your own code, it's probably a good idea to restructure your code a little. Particularly, I would suggest abstracting the printing and "filling" (removing) sections of printFill into individual methods. You generally want methods that have one purpose only, and then you combine them later on.
Exception handling. Exception handling is a complex subject and it's hard to keep one's solutions elegant and sensible. The first steps for that are not to catch the general exception Exception but the specific one, and to actually handle it once it occurs. In your case, you're catching some of the type IndexOutOfBoundsException, which can be prevented by doing appropriate checks in your loops.
Spacing/coding style. Some people use for (int i = 0; i < 5; i++) {, others for(int i=0; i<5; i++){ (among other variants) – there have always been heated debates about which is the "best way." Regardless of what you prefer, what is important is that you're consequent. This is maybe petty, but I feel that a consequent coding style seems more professional and it shows that care has been put into creating the code. However, that may just be my personal opinion.

Edit. There's one somewhat confusing feat in the code, namely that test() uses recursion but a loop as well. Generally, for clean recursion or looping, one would want to shy away from combinations. This seems to be an efficient solution to output the solutions, since you never store a lot in a list and output as soon as possible. I do believe that this would not be a recommendable approach if one wanted to store the solutions in a list, for instance.

I have split printFill(), I've renamed a lot of the variables and I've put the actual implementation of test() into a private method. A user can call test(24) or test(24, 5) for a maximum of five number in the combination and we'll take care of the rest from there.

As to optimization, look out especially for the line i = mainTarget - sum(list) + 1; which had unnecessary recursion calls, as well as if(ex) { return; } which looped unnecessarily but did nothing previously.

List<Integer> l = new ArrayList<Integer>(); – it is good practice to use an interface type as main type (List) and the implementation type (ArrayList) only for the actual initialization. But that's not a big thing and I think you'll want to care about that a little further down the road. :)

I have added some Javadoc but not consequently to all methods.

import java.util.ArrayList;
import java.util.List;

public class Numbers {
    private List<Integer> list;
    private boolean setNewStart;
    private boolean ex;
    private int newStart;

    public static void main(String[] args) {
        Numbers numbers = new Numbers();
        numbers.test(24);
    }

    public Numbers() {
        list = new ArrayList<Integer>();
        setNewStart = false;
        ex = false;
    }

    /**
     * Outputs all possible combinations for a number
     * @param target The number to compute combinations for
     */
    public void test(int target) {
        list = new ArrayList<Integer>();
        test(target, target, 10);
    }

    /**
     * Outputs all possible combinations for a number
     * @param target The number to compute combinations for
     * @param maxSize The maximum number of numbers for the combination
     */
    public void test(int target, int maxSize) {
        list = new ArrayList<Integer>();
        test(target, target, maxSize);
    }

    private void test(int tempTarget, int mainTarget, int maxSize) {
        for(int i = tempTarget; i > 0; i--) {
            if(ex) {
                return;
            }

            if(sum(list) + i > mainTarget) {
                // +1 because of the loop's i--
                i = mainTarget - sum(list) + 1;
                continue;
            }
            else if(list.size() >= maxSize) {
                int firstElem = list.get(0);
                if(firstElem * maxSize >= mainTarget) {
                    i = firstElem;
                    list.clear();
                }
            }
            else { /* sum(list) + i <= mainTarget && list.size() < maxSize */
                list.add(i);
                if(sum(list) == mainTarget) {
                    printList(list);
                    emptyList();

                    if(setNewStart) {
                        i = newStart;
                        setNewStart = false;
                    }
                }
                else {
                    test(i, mainTarget, maxSize);
                }
            }
        }
    }

    // Change helper functions to private

    /**
     * Empty the list appropriately to prepare
     * for the next possibility.
     */
    private void emptyList() {
        int lastElem = list.get(list.size()-1);

        if(lastElem > 1) {
            list.remove(list.size()-1);
            // commented out loop as it never happened
        }
        else if(lastElem == 1) {
            while(list.size() > 0 && list.get(list.size()-1) == 1) {
                list.remove(list.size()-1);
            }

            if(list.size() > 0) {
                setNewStart = true;
                // No -1 because of loop in test()
                newStart = list.remove(list.size()-1);
            }
            else {
                ex = true;
            }
        }
    }

    private int sum(List<Integer> list) {
        int sum = 0;
        for(int i = 0; i < list.size(); i++) {
            sum = sum + list.get(i);
        }
        return sum;
    }

    private void printList(List<Integer> list) {
        for(int i = 0; i < list.size()-1; i++) {
            System.out.print(list.get(i) + ",");
        }
        System.out.println(list.get( list.size()-1 ));
    }
}


Not a comprehensive review, but I'll list a few things which came to my notice right away:

Define the login_limit variable as login_limit_count to keep it consistent with login_limit_window.
Instead of defining the above 2 as class attributes, define them as constants in config/constants.php file.
Use === in the condition: ($this->form_validation->run() == FALSE)
The login method inside your user_model doesn't actually log-in the user. It just fetches the user details based off of $username. No need to provide it with $password and rename it to get_user or similar. Alternatively, put the password_verify inside the model, and return a user on successful login.
A select * is very bad. You should always know what values you'd be using from the result.
Hardcoding $route_url inside each controller method, and then calling check_request_route can be avoided using $_SERVER['REQUEST_URI'] variable and defining a hook. The hooks need to be enabled first in config/config.php. This way, you can track visits to multiple pages from a single location.


Generic function for loading a function from a DLL library

Just like Dangph, I wonder why you need this. There are other better approaches suggested in the previous comments.

Even if this is useful, Your solution is not great:
 1. You repeatedly load the library and the function.
 2. There is no way for you to free the loaded libraries.

Here is a better way to do it:

type
  TFunctionLoader = class
  private
    FLibraries: TStrings;   // This stores the library handles and names
    FFunctions: TStrings;   // This stores the function pointers and names
  public
    constructor Create;
    destructor Destroy; override;
    function LoadFunction(const LibraryName, FunctionName: string;
                          out FunctionPointer: Pointer): Boolean;
  end;

{ TFunctionLoader }

constructor TFunctionLoader.Create;
begin
  FLibraries := TStringList.Create;
  FFunctions := TStringList.Create;
end;

destructor TFunctionLoader.Destroy;
var
  i: Integer;
begin
  for i := 0 to FLibraries.Count - 1 do     // free all opened libraries
    Windows.FreeLibrary(THandle(FLibraries.Objects[i]));
  FLibraries.Free;                          // free other objects
  FFunctions.Free;
end;

function TFunctionLoader.LoadFunction(const LibraryName, FunctionName: string;
  out FunctionPointer: Pointer): Boolean;
var
  i: Integer;
  LibraryHandle: THandle;
begin
  i := FFunctions.IndexOf(FunctionName);    // Is the function already loaded?
  if i >= 0 then
  begin                                     // Yes, just return the stored pointer
    FunctionPointer := Pointer(FFunctions.Objects[i]);
    Exit(True);
  end;

  i := FLibraries.IndexOf(LibraryName);     // No, test if the library is already loaded
  if i < 0 then
  begin                                     // No, load it and store in FLibraries
    LibraryHandle := Windows.LoadLibrary(PChar(LibraryName));
    if LibraryHandle = 0 then Exit(False);  // Failed, quit
    i := FLibraries.AddObject(LibraryName, TObject(LibraryHandle));
  end;

  // Load the function from the library
  FunctionPointer := Windows.GetProcAddress(THandle(FLibraries.Objects[i]),
                                            PChar(FunctionName));
  Result := Assigned(FunctionPointer);      // succeeded?
  if Result then                            // Add the function to FFunctions
    FFunctions.AddObject(FunctionName, TObject(FunctionPointer));
end;

With above you can define var FunctionLoader: TFunctionLoader; somewhere and add this to the end of the unit

initialization
  FunctionLoader := TFunctionLoader.Create;
finalization
  FunctionLoader.Free;
end.

Use it as

Result := FunctionLoader.LoadFunction('User32.dll', 'BlockInput', @BlockInput)
          and BlockInput(not Enable);

All functions and libraries will be loaded only once and will be automatically freed.


Javascript map/filter/reduce over facebook messenger data

A big inefficiency of the initial approach is that for each person (which is actually a person's name) messages collection will be traversed 4 times.

To significantly optimize the traversal algorithm the current one is substituted with a single loop with multiple conditions per iteration.
All the needed specific counts are declared beforehand and used as accumulators.The Consolidate conditional expression technique is applied based on a common condition m.sender_name === personName.

The final optimized version:

people.forEach((personName) => {
    let stat = {'name': personName, 'messageCount': 0, 'photoMessageCount': 0,
               'videoGifMessageCount': 0, 'audioMessageCount': 0};
    messages.forEach((m) => {
        if (m.sender_name === personName) {
            stat.messageCount++;
            if (m.photos) stat.photoMessageCount++;
            if (m.gifs || m.videos) stat.videoGifMessageCount++;
            if (m.audio_files) stat.audioMessageCount++;
        }
    });
    stat.richContentMessageCount = stat.photoMessageCount + stat.videoGifMessageCount
                                   + stat.audioMessageCount;
    stats.push(stat);
});

In case if your stats array is intended to be used only for accumulating statistics from people.forEach(...) iterated once - prefer Array.map approach to create stats array with the results at once:

let stats = people.map((personName) => {
    let stat = {'name': personName, 'messageCount': 0, 'photoMessageCount': 0,
               'videoGifMessageCount': 0, 'audioMessageCount': 0};
    // all the logic here
    // ...
    return stat;
});