Set filRange = ws.Range("D2:E36419").SpecialCells(xlCellTypeVisible)

Hard coding range references will makes your code unnecessarily inflexible.  It is best to create a dynamic range reference that will resize itself to fit the data.

With ws
    Set filRange = .Range("D2:E" & .Rows.Count).End(xlUp)
End With

The filRange  is set to 2 columns.  I am assuming that column 1 is the key column and column 2 is the value column.  If this is the case then you should either adjust your fill range:

With ws
    Set filRange = .Range("D2" & Cells(.Rows.Count, "D").End(xlUp))
End With

Or adjust your search:

Set found = filRange.Columns(1).Find(key)

Range.CurrentRegion is a convenient way to create a dynamic range.

Set filRange = ws.CurrentRegion.Columns("D")

Question:

Do we think putting every pair in a new Dictionary structure would work? I'm thinking once everything is in the Dictionary, searching for my keys should be quick (does Dictionary use hashing?).

Answer:
Yes and yes.  Dictionaries use hashing for super fast look ups.  You may find this article interesting EXCEL VLOOKUP VS INDEX MATCH VS SQL VS VBA.
The reason that we use dictionaries in the first place is for the super fast look ups.  The problem in your project setup is that you are using Range.Find() for your lookups.
Its hard to give advice about what is the best approach with just a small snippet of code. Proving a more detailed question with all your relevant code, data samples, and perhaps a test stub will give you the best results.
Solution
Whatever you decide to do the key is to loop over the range values once and use the dictionary lookup up the values.  Personally, I would write a function that returns a dictionary that holds the filtered keys and values and compare it to partsDict.
Function GetFilteredRangeMap(Target As Range, KeyColumn As Variant, ValueColumnOffset As Variant) As Scripting.Dictionary

    Dim Column As Range

    Rem Set Column to the Visible Cells in the Key Column Range
    With Target.CurrentRegion.Columns(KeyColumn)
        On Error Resume Next
        Set Column = .SpecialCells(xlCellTypeVisible)
        On Error GoTo 0
    End With

    If Not Column Is Nothing Then
        Dim Map As New Scripting.Dictionary
        Dim Cell As Range
        For Each Cell In Column
            Map(KeyPrefix & Cell.Value) = Cell.Offset(ValueColumnOffset)
        Next
    End If

    Set GetFilteredRangeMap = Map
End Function

Usage

Dim Target As Range
Set Target = Sheet2.Range("A1").CurrentRegion

Dim Map As New Scripting.Dictionary
Set Map = GetFilteredRangeMap(Target, 1, 2)


C++ call std::list of objects instead of C linked list

Based on your answer and the comments from @user673679, with some modifications:

Removing using namespace std.
Using unique_ptr to transparently handle object allocation and deallocation. Remember to create items with make_unique.
forward_list is just fine for a FIFO queue.

Note that I don't use a range-based for loop because I only iterate the list once (run function and remove element).

#include "ctask.h" // Ctask, Ca and Cb definitions
#include <forward_list>
#include <iterator>
#include <memory>

class TaskQueue {
public:
   TaskQueue() :
     _tasks(),
     _last( _tasks.before_begin() )
   {
   }

   ~TaskQueue() = default;

   void add( std::unique_ptr<Ctask>&& t ) {
     _last = _tasks.insert_after( _last, std::move(t) );
   }

   void run_all() {
     task_list::iterator prev = _tasks.before_begin();
     task_list::iterator curr = _tasks.begin();
     while( curr != _tasks.end() ) {
        (*curr)->run();
        curr = _tasks.erase_after(prev);
     }
     _last = prev;
   }

private:
   typedef std::forward_list<std::unique_ptr<Ctask>> task_list;
   task_list           _tasks;
   task_list::iterator _last;
};

int main(void) {
    TaskQueue queue;
    queue.add(std::make_unique<Ca>());
    queue.add(std::make_unique<Cb>());
    queue.run_all();
    return 0;
}

Edit: I realized that you can make run_all more readable since you are basically removing all the elements from the queue, so that the while loop doesn't actually depend on _last value. The simplified function would be:

   void TaskQueue::run_all() {
     while( !_tasks.empty() ) {
        _tasks.front()->run();
        _tasks.pop_front();
     }
     _last = _tasks.before_begin();
   }


You could combine your two SQL queries so you don't have to hit the database twice.

The new SQL statement would be something like this:

SELECT
    q.id, q.question_number, q.chapter_id, q.section_id,
    q.question_txt, q.answers, q.feedbacks, q.correct_answer,
    q.question_type, q.module, q.shuffle_answer,
    q.tags, COALESCE(t.id, 0) As tagged
FROM questions q
     LEFT JOIN tagged t ON q.question_number = t.question_number AND t.user_id = ?
WHERE q.question_number=?

The COALESCE function would return the id from the tagged table if one exists, otherwise it returns 0.  This eliminates the need for your final if/else statement and gives you a direct mapping for $row->tagged.

You should also release all result sets and close all connections before issuing a return statement.  Any code after a return statement will not be executed.


Basic, single-threaded implementation of SynchronizationContext

You don't need to implement Dispose pattern if you have no unmanaged resources to dispose. Unless you get paid per line of code, that is :)
You should not dispose objects you did not create (unless you implement a wrapper). In your case, you should not dispose reset event in WorkItem class, since you did not create it there. Instead, you should use

using(var reset = new ManualResetEventSlim())
{
    _workItems.Enqueue (new WorkItem (d, state, reset));
    ...
}

this code:

while (true)
{
    synchronizationContext.Send(_ => Console.WriteLine("Hello!"), null)

    while (synchronizationContext.HasWorkItems) {
        synchronizationContext.ExecuteWorkItem ();
    }
}

will hang your application. You should either remove resetEvent from Send method and simply execute all queued WorkItems there (bad approach) or move this loop:

    while (synchronizationContext.HasWorkItems) {
        synchronizationContext.ExecuteWorkItem ();
    }

to sepatrate thread (better approach). Might look like:

public sealed class CustomSynchronizationContext : SynchronizationContext, IDisposable
{
     public CustomSynchronizationContext()
     {
         _thread = new Thread(() =>
               {
                   while(true)
                   {
                       _itemQueuedEvent.WaitOne();
                       if (_disposed) return;
                       ExecuteWorkItem();
                   }
               });
         _thread.Start();
     }

 ........
}

You will probably encounter some synchronization issues, but nothing that can not be solved.


Firstly, to answer your first question, QString is definitely not immutable. Directly from the documentation:

  This operation is typically very fast (constant time), because QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time.

I'm not a fan of the nested ternary statements in tool_unhex. Also, it does no error checking to make sure that whatever it is passed is actually a valid hex character. This is dangerous, as you use an unsigned short to store the shifted value of the character. If it's some character that's above F or f, then shifting and adding will potentially overflow and cause hard to track down bugs. For example, if there was a g that got in there somehow:

'g' - 'a' + 10;   // Equals 16
unsigned short w = (16 << 12) + (16 << 8) + (16 << 4) + 16;  // Overflow

I'd suggest changing it to the following:

#include <cctype>

// Converts the given (ASCII encoded) hex character to
// an integer value 0 - 15.
// throw std::out_of_range if the given character is not
// a valid hex character.
int tool_unhex(char c)
{
    if(std::isdigit(c))
        return c - '0';
    else if(c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    else if(c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    throw std::out_of_range("Not a hex character");
}

If you're sure that the character passed in will always be in range, this should be documented somewhere. Also, it should be documented that this will ONLY work for ASCII and ASCII-compatible encodings.

Your unescape method has some confusing parts. The comments and the code don't match.

char* s = (char*)sOrg;

Why cast away the constness of sOrg? You don't modify s anyway, so just work directly on the (const) sOrg.

str = "";

If you're just going to clear the QString passed in straight away, why not just create and return it instead of taking it as a reference?

if ( *s == '%' ) {
    if(*(s+1) == 'u')
    {
        s++;
        if ( *++s != '\0' ) {
            w = (wchar_t) (tool_unhex( *s ) << 12);
        }
        if ( *++s != '\0' ) {
            w += (wchar_t) (tool_unhex( *s ) << 8);
        }
        if ( *++s != '\0' ) {
            w += (wchar_t) (tool_unhex( *s ) << 4);
        }
        if ( *++s != '\0' ) {
            w += (wchar_t) tool_unhex( *s );
        }

        str += QString::fromUtf16(&w, 1);
    }
}

This can certainly be simplified with a loop.

In the end, I came up with something like this:

QString unescape2QString(const char *sOrg)
{
    QString str;

    for ( ; *sOrg != '\0'; ++sOrg ) {
        if (*sOrg == '%' && *(sOrg+1) == 'u') {
        {
           unsigned short w = 0;
           ++sOrg;
            // Left shift value
            int i = 12;
            while(*++sOrg != '\0' && i >= 0) {
                w += (wchar_t) (tool_unhex(*sOrg) << i);
                i -= 4;
            }
            str += QString::fromUtf16(&w, 1);
        }
        else
        {
            str += QString::fromAscii(s, 1);
        }
    }
    return str;
}

This definitely needs some documentation as to what exactly it's doing, as it is absolutely not clear currently.


Fast Thread- and multiprocess-safe file operations in python under Linux

Are there any issues with the code that I should be aware of? (besides from what I already said)

If you haven't, maybe read
Everything you never wanted to know about file locking;
I guess the takeaway is that you should make sure that you're actually
getting what you want with the Python fcntl module.

The code looks good to me in general, apart from the bad error handling.

When fcntl.flock throws, the file descriptor from os.open isn't
closed.  This is generally bad and can bite you in the future.

You don't have to care about unlocking as that's done then closing the
file descriptor anyway.

And another issue you missed is that the yield has to be wrapped in a
try/catch in order for the cleanup to run,
c.f. contextmanager.

In summary it should look somewhat like this:

@contextmanager
def locked_open(filename, mode=M_READ, blocking=True):
    open_mode, flock_flags, mode_str = MODES[mode]
    flock_flags = flock_flags | BLOCKING_FLAGS[blocking]

    fd = os.open(filename, open_mode)
    try:
        fcntl.flock(fd, flock_flags)
        fileobj = os.fdopen(fd, mode_str)

        try:
            yield fileobj
        finally:
            fileobj.flush()
            os.fdatasync(fd)
    finally:
        os.close(fd)

  Are my tests sufficient?

You didn't actually test the interaction between multiple threads and
processes.  Since you're only locking a file descriptor once this will
work as it is though.

  Any suggestions regarding performance?
  Are there any easier ways to achieve same result?

You'd have to measure that, but since you're using this from a single
application only, using in- and shared-memory locks (from
multiprocessing) could be a faster alternative instead of going
through the filesystem.  But it's way more effort on your end with all
three access modes as you wrote them here and with multiple processes
you'd easily run into more failure modes - I doubt it's worth it.
That said, if you can get away with less features for locking, then you could still investigate it.


There are some bugs related to parameter handling:

Splitting by ", ": In #build_where, you split the skill parameter by ", ".  However, you example has just "skills"=>"3,8" — with no space after the comma.  Splitting will therefore fail.
SQL injection vulnerability: Parts of the value of the skills parameter end up in the SQL query's WHERE clause, but you never validated, escaped, or parameterized the query.  You use the city, state, and country parameters with similar carelessness, interpolating values directly into an ORDER BY clause.  If a user tries to specify St. John's as the city, the query will break due to the apostrophe being treated as a quotation mark.  A malicious user can exploit that to do nasty things to your database.

I also suspect that

Job.select(:id).joins(:skills)

is the wrong thing to do.  That produces an INNER JOIN.  Any job that has no special required skills will therefore not appear in the join result.  I'm guessing that a LEFT OUTER JOIN would be more appropriate.

As for the skills filter itself, the WHERE clause you want in SQL is

WHERE "skills"."id" IN (3, 8)

(Writing 'skills'.'id' results in much brokenness.  To quote identifiers in PostgreSQL, use double-quotes.  Single quotes are used to quote literal strings, not identifiers.)

I would therefore write it as

def restrict_skills(search_jobs, skills_filters)
  # Check for non-empty string consisting only of digits, commas, and spaces
  if skills_filters.match(/\A[0-9, ]+\Z/)
     search_jobs.where(%Q{"skills"."id" IN (#{skills_filters})})
  end
end

Usually, I recommend parameterizing queries.  Escaping is my second choice.  Validating is normally my third choice.  However, here I've used validation instead of parameterizing and escaping because validation is easy: just check that the skills parameter consists of just digits, commas, and spaces.  It also happens that the SQL IN clause expects comma-delimited integers here.

I've also changed the helper method to manipulate the query-building object rather than to return a fragment of SQL.


Fitting multiple images in a given width

Fit images to width.

To make n images fit a width while keeping each image's aspect do the following.

Get the height that the images need to be to fit.

// images is an array of loaded images
// width is the width to fit
// returns the height images must be to fit.
function getFitSize(images,width){
    var totalWidth = 0;  // Holds the total aspect width
    // sum aspect for each image for total aspect width
    images.forEach(img=>{
        totalWidth +=  img.width / img.height;
    })
    // then get height to fit the required width
    return width / totalWidth;  // the height for all to fit
}

var height = getFitSize(images,500); // fit images to 500 pixels across

With the height you just need to use that to scale the width by the aspect and set the height.

Size each image.

image.width = height * (image.width / image.height); // the image width that
                                                     // will fit
image.height = height;

Example

A Javascript example showing usage of above method. Images are loaded one at a time and made to fit the available page width.

const imageURLList = [ "https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Renaissance_Center%2C_Detroit%2C_Michigan_from_S_2014-12-07.jpg/380px-Renaissance_Center%2C_Detroit%2C_Michigan_from_S_2014-12-07.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Paulus_Moreelse_-_Zelfportret.jpg/300px-Paulus_Moreelse_-_Zelfportret.jpg",
"https://upload.wikimedia.org/wikipedia/en/thumb/b/bb/Maull_%26_Fox_-_Fanny_Bullock_Workman.jpg/300px-Maull_%26_Fox_-_Fanny_Bullock_Workman.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Toompea_loss_2014.jpg/380px-Toompea_loss_2014.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Winslow_Homer_-_The_Gulf_Stream_-_Metropolitan_Museum_of_Art.jpg/350px-Winslow_Homer_-_The_Gulf_Stream_-_Metropolitan_Museum_of_Art.jpg"
];
const images = [];
function getFitSize(images,width){
    var totalWidth = 0;
    images.forEach(img=>{ totalWidth +=  img.naturalWidth / img.naturalHeight })
    return width / totalWidth;
}
// load images one at a time for effect only
function loadImage(){
    const image = new Image;
    image.src = imageURLList.shift();
    image.onload = function(){
        images.push(image);
        const width = imageContainer.getBoundingClientRect().width;
        const height = Math.floor(getFitSize(images,width));
        images.forEach(image => {
            image.style.width = Math.floor(height * (image.width / image.height)) + "px";
            image.style.height = height + "px";
        });
        imageContainer.appendChild(image);
        if(imageURLList.length > 0){
            loadingInfo.textContent = "Loading image " + (images.length +1);
            setTimeout(loadImage,2000);
        }else{
            loadingInfo.textContent = "Loading complete";
        }
    }
}
loadingInfo.textContent = "Loading image " + (images.length +1);
setTimeout(loadImage,2000);
#imageContainer {width : 100%;}
body { font-family : arial; margin: 0px; overflow: hidden;}
.noEdge {margin: 0px;  padding : 0px; }
.atr { font-size : small; }
Fit images to width.

Images from Wikipedia:Picture of the day/January 2017


Concise coding

After moving the documentation of the function after the line containing def as the convention stands we have:

def whoCan(doThis):
    '''
    This is a simple function that prevents me from repeating myself.
    Usage:
        whoCan('execute')
    will return 'Who can execute?'

    If I use `print` instead of `return` here, this is the output:

     Who can read?
     None

    Why is that?
    '''
    return "Who can %s?" % doThis

The second paragraph is just a doubt that is not really relevant to this function (the reason is that: using print creates a function with no return of which the return is implicitly None, that is printed by raw_input), so we can remove it:

def whoCan(doThis):
    '''
    This is a simple function that prevents me from repeating myself.
    Usage:
        whoCan('execute')
    will return 'Who can execute?'
    '''
    return "Who can %s?" % doThis

I can already see that it is a (simple) function, and functions are usually used to avoid repetition so we can remove it too:

def whoCan(doThis):
    '''
    Usage:
        whoCan('execute')
    will return 'Who can execute?'
    '''
    return "Who can %s?" % doThis

In fact we may remove this whole function as it is just doing "Who can {}?".format(action) where x is the input.

To avoid repetition we will use a generator expression:

read, write, execute = (raw_input("Who can {}?".format(action)) for action in ('read', 'write', 'execute'))

The last part can be shortened with a dictionary and a function that calls sum on a generator expression:

name_to_val = {'ow' : 4, 'gr' : 2, 'ot' : 1}

def chmod_value(x):
    return sum(name_to_val(name) for name in name_to_val.keys() if name in x)

You also do not need to initialize variables with zero, in fact you do not need variables at all:

print [chmod_value(x) for x in (read, write, execute)]


Efficiently shift elements right by one in an __mm256 vector

With AVX2, it could be done with one vpermps aka _mm256_permutevar8x32_ps:

auto shifted = _mm256_permutevar8x32_ps(v256f_stats, _mm256_set_epi32(6, 5, 4, 3, 2, 1, 0, 0));

Clang rewrites the original shuffle into the same assembly.

Here is an alternative with just AVX1:

auto stats00 = _mm256_permute2f128_ps(v256f_stats, v256f_stats, 0);
stats00 = _mm256_blend_ps(stats00, v256f_stats, 0b01111111);
auto shifted = _mm256_permute_ps(stats00, _MM_SHUFFLE(2, 1, 0, 3));

Roughly the same idea as the original, but reworked so that the _mm256_permute_ps comes after the blend so it only needs to be done once.

This time Clang is too clever for its own good, it replaces the blend/shuffle with two shuffles, which is worse because the blend was cheaper (p015, while the shuffles are p5).


Implementing Python-like slice in JavaScript

Throwing errors

You should only throw errors, not strings.

throw new Error("Slice step cannot be zero");

Leveraging existing API

What you're doing looks very similar to the existing slice except for the last parameter, step. This could be more compact if you used built-in slice for everything and then apply the step afterward.

function slice(collection, start, end, step) {
    var slice = collection.slice || Array.prototype.slice,
        sliced = slice.call(collection, start, end),
        result, length, i;

    if (!step) {
        return sliced;
    }
    result = [];
    length = sliced.length;
    i = (step > 0) ? 0 : length - 1;
    for (; i < length && i >= 0; i += step) {
        result.push(sliced[i]);
    }
    return typeof collection == "string" ? result.join("") : result;
}

This would require you to pass undefined in the places you have null in your usage examples. If you want to be able to pass null, you can add if (start === null) start = undefined, and the same for end.


Here are some things that may help you improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Use nullptr rather than NULL

Modern C++ uses nullptr rather than NULL.  See this answer for why and how it's useful.

Use more whitespace

Lines like this one:

cout<<"Linked List is"<<endl;

become much easier to read and understand with a little more whitespace:

cout << "Linked List is" << endl;

Use consistent formatting

The code seems to have inconsistent indentation and inconsistent placement of brackets {}.  It doesn't matter as much which convention you use as much as it matters that you follow some convention.  Doing so makes your code easier to read, understand and maintain.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.  For instance, the line quoted above could be written like this:

std::cout << "Linked List is\n";

Prefer modern initializers for constructors

The constructor use the more modern initializer style rather than the old style you're currently using.  Instead of this:

    linklist(){
        start=NULL;
    }

you could use this:

    linklist() : start{nullptr} {}

This uses the more consistent {} form for initializing start (and so requires a C++11 compiler) but this can be done using older C++99 if needed.  There is not a significant difference in this code, but it's a good habit to get into using.

Use const where practical

The display member functions of linklist does not alter the underlying object and therefore should be declared const:

void display() const;

Make your class destructor virtual

If there's any chance that your class will be derived from, the class destructor should be virtual to avoid problems with collections of objects. See this question for more details on why.  If it can't be derived from, enforce that by declaring the class final.

With that said, as @isanae has correctly pointed out, you shouldn't be left with the impression that those are the only options.  For a plain old concrete class such as this one, you can reasonably just leave it as it is right now.

Return something useful from functions

The merge function takes two sorted linked lists and returns a new one; or it should.  Right now it's declared like this

void linklist::merge(linklist l1, linklist l2,linklist& l3)

but it would make much more sense like this:

linklist linklist::merge(linklist l1, linklist l2)

Better still would be for the first list to be implicit so that one could write this:

l3 = l1.merge(l2);

To do that, I'd write the function like this:

linklist linklist::merge(const linklist &l2) const {
    linklist l3;
    node *nodes[2]{start, l2.start};

    while (nodes[0] && nodes[1]) {
        size_t index = nodes[0]->data < nodes[1]->data ? 0 : 1;
        l3.append(nodes[index]->data);
        nodes[index] = nodes[index]->link;
    }
    l3 += nodes[0];   // one of the lists is empty at this point
    l3 += nodes[1];
    return l3;
}

Note that this assumes the existence of an operator+= which might be implemented like this:

linklist &operator +=(const node *p) {
    while (p) {
        append(p->data);
        p = p->link;
    }
    return *this;
}

Use operator<< instead of display

It would be convenient to be able to redirect the output to something other than std::cout, so the usual idiom is to use something like this:

friend std::ostream& operator<<(std::ostream& out, const linklist &list) {
    for (auto temp=list.start; temp; temp=temp->link) {
        out << temp->data << "  ";
    }
    return out << '\n';
}

Now we can use it within main like this:

std::cout << "finished merging\n" << l1 << l2 << l3;

Consider using a template

As the code is currently written, it can only store a single int as data, but with only a very minor change in the code, it could become a template.  The first few lines could look like this:

template <class T>
class linklist{
private:
    struct node{
        T data;
        node* link;

Thereafter, anywhere you specifically refer to an int for the data, replace it with the templated type T and you now have a generic container.  For your int version, you can write this:

linklist<int> l1;

Consider providing a std::initializer_list constructor

linklist(std::initializer_list<T> list) : start{nullptr} {
    for (auto item : list) {
        append(item);
    }
}

Implementing all of the suggestions above give a main like this:

int main()
{
    linklist<int> l1{2, 5, 23, 34, 45};
    linklist<int> l2{6, 9, 35, 98};

    std::cout << "Before merging\n" << l1 << l2;
    auto l3 = l1.merge(l2);
    std::cout << "After merging\n" << l1 << l2 << l3;
}

Don't destroy passed objects

Right now the code destroys the passed objects in creating the new list.  That's not a good design, especially because the lists are not even passed by reference, so it would be very surprising to someone looking at the code. That can be fixed with the following suggestion.

Create a copy constructor if you need one

The compiler will create a default copy constructor which does a shallow copy, but this won't work for data structures, like yours, which use pointers.  Instead, if you really want to create a new linklist from an existing one, you'll need to create your own copy constructor:

linklist(const linklist &other) : start{nullptr} {
    for (auto temp = other.start; temp; temp = temp->link) {
        append(temp->data);
    }
}

Consider using smart pointers

Using something like a std::unique_ptr would free you (pun intended) from having to manage the mechanics of new and delete explicitly.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.


You don't need to overload ExpandEnv.  In the const-ref overload, your action is to make a copy of the argument and pass that to the rvalue-ref version.
There's a simple way to get the compiler to do that, and it's pass by value.  Often overlooked, this is exactly the right way to get a modifiable value in your function, by move if possible, and by value if not:
inline std::string ExpandEnv(std::string text)
{
    //...implementation
}

To answer your specific question (even though we've eliminated the relevant code), there's no need for std::move(), as std::string(...) is already an rvalue expression.

Other notes:

Your local style guide may say otherwise, but we normally use PascalCase for names of composite types rather than for functions.  Consistency with the rest of the code base and any libraries may be a factor here, though.

That Windows code instead of getenv() is horrible - I hope I never have to target Windows!  Can _dupenv_s() return true when it has allocated buf?  If so, the error path also needs to free(buf).

buf == nullptr can be written simply as !buf.

In the Windows path, you can avoid the need for local val by giving buf to a unique_ptr to look after it for you (so you can simply return buf; or return {}; for the success and failure cases, respectively):
  char *buf{nullptr};
  size_t sz;
  auto failed = _dupenv_s(&buf, &sz, var);
  std::unique_ptr<char,malloc_deleter> m{buf}; // ensure buf is released automatically
  return failed ? std::string{} : std::string{buf, sz};

Actually, now I've read up on the Windows function, there seems to be no reason not to use std::getenv() - the only difference in behaviour seems to be if a null pointer is passed as argument, and we never do that.

You might want to use a raw string literal to reduce those doubled-backslashes: \$\{([^}]+)\} may be slightly easier to read.

Really, really split that single-line while into separate lines for the condition and statement.  It may even be worth making it a block, and giving names to the match and replacement - notably for match[0] which you also write as match.begin() in that expression.

I'd probably write the argument to GetEnv() as char const* rather than char const[], to help distinguish from actual array arguments (in templates, where the size is a template argument).

Do you want to provide a means to escape ${ when it appears literally in the input?

#Reworked code
#include <string>
#include <regex>
#include <cstdlib>

inline std::string expand_env(std::string text)
{
    static const std::regex env_re{R"--(\$\{([^}]+)\})--"};
    std::smatch match;
    while (std::regex_search(text, match, env_re)) {
        auto const from = match[0];
        auto const var_name = match[1].str().c_str();
        text.replace(from.first, from.second, std::getenv(var_name));
    }
    return text;
}

#include <iostream>
int main()
{
    std::cout << expand_env("${HOME} is where the heart is.\n");
}


Koch Curve algorithm in Python without using Turtle/Logo logic

#!/bin/env python
# coding: utf-8

def kochenize(a,b):
    HFACTOR = (3**0.5)/6

Stylistically, this would better as a global constant although there'll be some runtime cost to that.

    dx = b[0] - a[0]
    dy = b[1] - a[1]
    mid = ( (a[0]+b[0])/2, (a[1]+b[1])/2 )
    p1 = ( a[0]+dx/3, a[1]+dy/3 )
    p3 = ( b[0]-dx/3, b[1]-dy/3 )
    p2 = ( mid[0]-dy*HFACTOR, mid[1]+dx*HFACTOR )

The [0] and [1] all over the place obscures your algorithm. Checkout collections.namedtuple

    return p1, p2, p3

def koch(steps, width):
    arraysize = 4**steps + 1
    points = [(0.0,0.0)]*arraysize
    points[0] = (-width/2., 0.0)
    points[-1] = (width/2., 0.0)
    stepwidth = arraysize - 1
    for n in xrange(steps):
        segment = (arraysize-1)/stepwidth

This loop is slightly confusing to read. To understand the logic of what stepwidth, n and steps are all doing I have to look for it in several places. I'd probably write a generator which produces the decreasing values of stepwidth to encapsulate that

        for s in xrange(segment):
            st = s*stepwidth
            a = (points[st][0], points[st][1])
            b = (points[st+stepwidth][0], points[st+stepwidth][1])
            index1 = st + (stepwidth)/4
            index2 = st + (stepwidth)/2
            index3 = st + ((stepwidth)/4)*3

They way you've coded that, the symmetry between the index is non-obvious. The code would be clearer if you hand't reduce the fractions. Also, index1, index2, index3 are begging to be in a list index

            result = kochenize(a,b)
            points[index1], points[index2], points[index3] = result
        stepwidth /= 4
    return points

if __name__ == '__main__':

I recommend putting the contents of this inside a function called main which you call from here

    TOTALWIDTH = 1000.
    points = koch(7, TOTALWIDTH)

    # If you want a pretty picture (and have Cairo and PIL modules installed)
    if True:

If you want this to be optional check command line arguments or check whether the necessary modules are installed. Putting if True as anything other then a quick hack is frowned upon.

        import cairo, Image

        width = int(TOTALWIDTH)
        height = int(TOTALWIDTH*0.32)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        cr = cairo.Context(surface)

I dislike cr, it doesn't obviously stand for anything.

        cr.set_source_rgb(1,1,1)
        cr.rectangle(0, 0, width, height)
        cr.fill()
        cr.translate(width*0.5, height*0.95)
        cr.scale(1, -1)

        cr.set_source_rgb(0,0,0)
        cr.set_line_width(0.5)
        cr.move_to(*points[0])
        for n in range(len(points)):
            cr.line_to(*points[n])
        cr.stroke()

        im = Image.frombuffer("RGBA", (width, height), surface.get_data(), "raw", "BGRA", 0,1)
        im.show()

If you want more speed, you should look into numpy. It will allow you to do vector operations which will be faster then what you can do in straight python.


Find ASCII codes and replace with characters

Warning: The code below is intended to be compatible with the original post.
Its main benefit is that it retains all of the useful detail discovered in the pattern match (unmatched substrings, relative position of matches), eliminating the need to rescan the line. I'd expect it to be faster for that reason.

It retains the problem that chr is a blunt instrument that can effortlessly
consume many digits (not just one, two, or three), using "wrapping"
(a.k.a. modulo 256 math) to scale the resulting integer down to a legal byte value,
possibly not the one intended.

In other words, this code would fail the conversion of a string with ASCII codes
immediately followed by digits, e.g.
if "From A1 to z52" needs to be expressable as "From #651 to #12252".
So, a different approach may be needed.

One approach is for the conversion step to convert the digit string to integer digits one digit at a time,
doing the (digits*10 + digit) math and stopping (or actually backing up one digit)
when a value of 256 or greater is reached.

Another approach, probably faster, is for the conversion step to convert a substring (up to three digits) of
the digit string to an integer and if it is 256 or greater "back up one digit", dividing
the integer by 10.

In either case, any unused/backed-up digits would be appended to the result
of chr applied to the integer.

In either of these approaches, but especially the first,
some work might be saved by having the regex match at most
three digits instead of any number of digits -- leaving the rest as unmatched characters
at the head of the next "surrounding text" part.
That way, there would be no need to test for integer overflow from way too many digits.

A "higher-tech" approach could go further, enabling the current simple
$parts[$i] = chr($parts[$i]) conversion to be retained.
This would require beefing up the regex so that it matched, in order of preference,
a 3-digit number less than 256 OR a 2-digit number (that possibly had another
unmatched digit following it) OR a 1-digit number (that was not followed by another digit).

That seems like a lot of trouble, except maybe for a regex aficionado, so I'd probably opt for the middle approach, converting and testing a 3-digit substring.

<?php
    $line= 'stuff #65 more #66  and #67; other';
    // break out any #numbers that should be translated to ascii,
    // retaining the surrounding text and the numbers parts.
    // The '#' parts are kept outside the parens to be matched and discarded.
    $parts = preg_split("/\#(\d+)/",$line,NULL,PREG_SPLIT_DELIM_CAPTURE);
    $count = count($parts);
    // Even-indexed entries (possibly empty) contain unchanging surrounding text.

    // Odd-indexed entries are the numbers part of #numbers, so convert them.
    for ($i = 1; $i < $count; $i += 2) {
        $parts[$i] = chr($parts[$i]); // Problem here for input >= 256.
    }

    $line = implode($parts);
?>


Receive a list of names and return a list of users - HackerRank test

I would warn you from using such an approach - it may lead to buggy and unexpected results.Consider the following situation:

names = ['john', 'john', 'tom', 'john']
res1 = username_system(names)
print(res1)    # ['john', 'john1', 'tom', 'john2']

lst = ['a']
res2 = username_system(names, users=lst)
print(res2)   # ['a', 'john3', 'john4', 'tom1', 'john5']

Looking at the 2nd print result ...
Using a mutable data structures as function default arguments is considered as a fragile approach - Python "memorizes"(retains) that mutable arguments content/value between subsequent function's calls. Furthermore, you use 2 of such.Though in some cases it may be viable for defining a specific internal recursive functions - I'd suggest a more robust and faster approach.

As you're mentioned about "memoization", "to make it faster", "O(N)" here's a deterministic profiling stats for your initial function:

import cProfile

# def username_system(...)
names = ['john', 'john', 'tom', 'john']
cProfile.run('username_system(names)')

Output:

         27 function calls (23 primitive calls) in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
      5/1    0.000    0.000    0.000    0.000 test.py:3(username_system)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        4    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
        5    0.000    0.000    0.000    0.000 {method 'copy' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        4    0.000    0.000    0.000    0.000 {method 'keys' of 'dict' objects}
        4    0.000    0.000    0.000    0.000 {method 'remove' of 'list' objects}
        2    0.000    0.000    0.000    0.000 {method 'update' of 'dict' objects}

As you may observe even for that simple input list of 4 names username_system function is called 5 times.

Instead, we'll rely on supplementary collections.defaultdict object that conveniently provides the initial value.Then, traversing over a copy of initial user names only entries that occur more than 1 time (within a dict keys view) will be appended with incremented ordinal suffix:

from collections import defaultdict

def get_unique_usernames(user_names):
    d = defaultdict(int)
    uniq_unames = user_names[:]

    for i, name in enumerate(uniq_unames):
        if name in d:
           uniq_unames[i] += str(d[name])
        d[name] += 1

    return uniq_unames

if __name__ == "__main__":
    names = ['john', 'john', 'tom', 'john']
    print(get_unique_usernames(names))    # ['john', 'john1', 'tom', 'john2']

Comparison of Time execution performance:

initial setup:

from timeit import timeit

names = ['john', 'john', 'tom', 'john']

username_system function:

print(timeit('username_system(names)', 'from __main__ import names, username_system', number=10000))
0.027410352995502762

get_unique_usernames function:

print(timeit('get_unique_usernames(names)', 'from __main__ import names, get_unique_usernames', number=10000))
0.013344291000976227


Adding and Retrieving Players in a simple Pre-Flop Poker Hud with Local Storage

To Your Questions

Is there a benefit to using Classes? Right now I don't see the benefit of having a handle, like, player1 = new Player(arg,arg,etc...), player2 = new Player(arg,arg, etc...)...

Maybe there are benefits, but I can't think of any serious ones now.
The current version is similar to the factory pattern, where the creation of an object is abstracted by a factory - in this case addPlayer:
const player = addPlayer('Harry Potter');

Is there a better way to store to Local Storage? I don't think storing each player with their own key and having a ton of entries is a good idea.

I think storing all players under one key is sufficient and the easiest to manage. But you can get the best of both worlds:
Currently you are saving an array of players. Instead you could save a map where the key is a unique attribute of the player (maybe the name or an id) and the player itself. The benefit would be that you do not need to loop through an array to find a player:
function getPlayersFromStorage(key) {
  /* ... read from storage ... */;
  /* return has the form:
     {
        playername: player
     }
  */
}

const players = getPlayersFromStorage(localStorageKey);
const harryPotter = players["Harry Potter"];

This is only necessary if you need to find players directly.

In my function addPlayer() should I be calling savePlayersToStorage in my localStorageUtils.js?

It depends. Currently the method name addPlayer does not represent what the method does. When I first read the name I thought: "Ah ok, this methods put a player in some collection or maybe the local storage". But then I read the following line and get confused:

players.push(addPlayer(newPlayer));

A better name for addPlayer would be createPlayer and I would not call savePlayersToStorage in it, to have smaller and side effect free functions.
Change Persistenz

I am currently using local storage to store my data. In the future I will use a better persistence strategy

Currently, only the main.js depends on localStorage, and knows the implementation details, which would make it easier to change it in the future. However, to make it easier to change, especially as the code grows and more files depend on the persistence implementation, it should be abstracted as much as possible:
class LocalStorage {
    getAll() { /* ... */ }
    getByName() { /* ... */ }
    save()  { /* ... */ }
}

class OtherStorage {
    getAll() { /* ... */ }
    getByName() { /* ... */ }
    save()  { /* ... */ }
}

When your different storage strategies share the same interface they are easy interchange able:
// Main.js

const storage = new LocalStorage('my-storage-key');
# const storage = new OtherStorage(/* dependencies */);

function main() {
    const players = storage.getAllPlayers();
    const harryPotter = storage.getPlayerByName('Harry Potter');

    const newPlayer = createPlayer('Ron Weasley');
    const storage.save(newPlayer);
}

Read from Store

function getPlayersFromStorage(localStorageKey) {
 if (localStorage.getItem(localStorageKey === null)) {
   localStorage.setItem(localStorageKey);
 }
 let players = JSON.parse(localStorage.getItem(localStorageKey));

 return players;
}

When reading from the store we set an item if the key does not exists with localStorage.setItem(localStorageKey). To set an item is not the responsibility for reading data. Instead we could add some logic which is related for reading. For example if there is stored data under the given key:
function getPlayersFromStorage(localStorageKey) {
    const fromStore = localStorage.getItem(localStorageKey);

    if (fromSore) {
        return [];
    }

    return JSON.parse(fromStore);
}


Replace any number of consecutive underscores with a single space

I think overall it is a nice implementation. It is clear and readeable. The use of constants is nice, makes it easy to refactor the code to make it more generic later on (e.g. replace with given character, not just space). Clear variable names (although I'd try and be consistent, and use current\previous, or cur/prev, most likely the former).

I have two remarks:

I am not a fan of the new line at the start of a function, it is too much, and makes me lose my focus.
I'd change the check if (currentChar != prevChar) to if (prevChar != UNDERSCORE). Although we can know from the check above that currentChar is an underscore, this makes it even more clear.

I don't really think you have what I'd see as duplication, but a possible other way to implement it would be to keep track of wether you are currently in a sequence of underscores. Example:

boolean previousWasUnderscore = false;
for (int i = 0; i < input.length(); i++) {
    final char currentChar = input.charAt(i);
    if (currentChar == UNDERSCORE) {
        if (!previousWasUnderscore ) {
            output.append(SPACE);
            previousWasUnderscore = true;
        }
    } else {
        output.append(currentChar);
        previousWasUnderscore = false;
    }
}


You're working with delegates so the Action variable should be declared as Delegate. Please note that you need to enclose the type in square brackets as Delegate is a reserved word.
Don't use Dim in class-scoped variables, instead apply the access level.
Declare your arrays in a .net fashion. The type should be Object().
All non-public fields should be in lowerCamelCase.
There's no need to apply the Overloads modifier as you're not redeclaring any existing methods.

Apply all the fixes allows you to perform a dynamic invoke.

Public Class WorkItem

    Private action As [Delegate]
    Private args As Object()

    Public Sub [Set](action As Action)
        Me.SetArgs(action)
    End Sub

    Public Sub [Set](Of T)(action As Action(Of T), arg As T)
        Me.SetArgs(action, arg)
    End Sub

    Public Sub [Set](Of T1, T2)(action As Action(Of T1, T2), arg1 As T1, arg2 As T2)
        Me.SetArgs(action, arg1, arg2)
    End Sub

    Private Sub SetArgs(ByVal action As [Delegate], ParamArray args As Object())
        Me.action = action
        Me.args = args
    End Sub

    Public Sub Execute()
        Me.action.DynamicInvoke(Me.args)
    End Sub

End Class

Alternative solution

Another approach would be to wrap the delegate in a parameterless action.

Public Class WorkItem

    Private method As Action

    Public Sub [Set](Of T)(action As Action(Of T), arg As T)
        Me.method = New Action(Sub() action.Invoke(arg))
    End Sub

    Public Sub [Set](Of T1, T2)(action As Action(Of T1, T2), arg1 As T1, arg2 As T2)
        Me.method = New Action(Sub() action.Invoke(arg1, arg2))
    End Sub

    Public Sub [Set](Of T1, T2, T3)(action As Action(Of T1, T2, T3), arg1 As T1, arg2 As T2, arg3 As T3)
        Me.method = New Action(Sub() action.Invoke(arg1, arg2, arg3))
    End Sub

    Public Sub Execute()
        Me.method.Invoke()
    End Sub

End Class

For old compilers

Public Delegate Sub Action()
Public Delegate Sub Action(Of T)(ByVal obj As T)
Public Delegate Sub Action(Of T1, T2)(ByVal arg1 As T1, ByVal arg2 As T2)
Public Delegate Sub Action(Of T1, T2, T3)(ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3)

Public Class WorkItem

    Private Class Closure(Of T)

        Public action As Action(Of T)
        Public arg As T

        Public Sub Invoke()
            Me.action.Invoke(Me.arg)
        End Sub

    End Class

    Private Class Closure(Of T1, T2)

        Public action As Action(Of T1, T2)
        Public arg1 As T1
        Public arg2 As T2

        Public Sub Invoke()
            Me.action.Invoke(Me.arg1, Me.arg2)
        End Sub

    End Class

    Private Class Closure(Of T1, T2, T3)

        Public action As Action(Of T1, T2, T3)
        Public arg1 As T1
        Public arg2 As T2
        Public arg3 As T3

        Public Sub Invoke()
            Me.action.Invoke(Me.arg1, Me.arg2, Me.arg3)
        End Sub

    End Class

    Private method As Action

    Public Sub [Set](Of T)(ByVal action As Action(Of T), ByVal arg As T)
        Dim closure As New Closure(Of T)
        closure.action = action
        closure.arg = arg
        Me.method = New Action(AddressOf closure.Invoke)
    End Sub

    Public Sub [Set](Of T1, T2)(ByVal action As Action(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2)
        Dim closure As New Closure(Of T1, T2)
        closure.action = action
        closure.arg1 = arg1
        closure.arg2 = arg2
        Me.method = New Action(AddressOf closure.Invoke)
    End Sub

    Public Sub [Set](Of T1, T2, T3)(ByVal action As Action(Of T1, T2, T3), ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3)
        Dim closure As New Closure(Of T1, T2, T3)
        closure.action = action
        closure.arg1 = arg1
        closure.arg2 = arg2
        closure.arg3 = arg3
        Me.method = New Action(AddressOf closure.Invoke)
    End Sub

    Public Sub Execute()
        Me.method.Invoke()
    End Sub

End Class


Sum of Even Fibonacci numbers in functional programming

General Notes

The use of map(f1).filter(f2).reduce(f3) is a solid approach to functional programming.
The names of the functions and variables are reasonable.

Things to consider

Scope: The lexical scope of the the const = x => ...; is the global namespace. The values are only used locally. In Javascript this is suboptimal practice.
Lambdas: Javascript lambda notation facilitates passing anonymous functions. One advantage of passing anonymous functions is that it is done locally. const sum... is four lines from the top of the file. .reduce(sum) is only two lines from the bottom.

.reduce((x,y) => x + y)

is almost certainly easier to understand...though it may be harder to write without refactoring.
Intent: The use of const is good to express your intent to program in a functional manner, but it does not really make the code easier to read. One of the 'supposed' rationales for using functional programming is that it is easier to reason about. This is a case where: /* This code is written in a functional style. It does not use mutuation */ at the top of the file might be another way to state the your intent while letting the Javascript look more familiar.

Computer Science

In terms of functional programming, the use of recursion is a step in the right direction. However the recursive code calculating the Fibonacci values:

const fibonacciOf = n => {
    if (n === 0) {
        return 1;
    }
    if (n === 1) {
        return 2;
    }
    return fibonacciOf(n - 1) + fibonacciOf(n - 2);
};

Is "tree recursive" and therefore does a lot of extra work. Tree Recursion is described in The Structure and Interpretation of Computer Programs. Section 1.2.2 has a very helpful illustration that shows how tree recursive algorithms wind up performing substantially more work than is necessary.

Alternative Functional Approach

Recursive Design: Structurally recursive algorithms have two part: a base case and an inductive step. The naive approach to Fibonacci treats n == 0 as the base case and n-1 as the induction. The alternative code treats n as the base case and n + 1 as the induction. This means n - 1 has always been computed previously.

function sumOfEvenFibsLessThan (n) {

    /* Returns the array of Fibonacci numbers less than n */
    var fibsLessThan = function (n) {

        /* Takes an Array, returns an Array */
        var generateFibs = function(fibs) {
            var nextFib = fibs[fibs.length - 1] + fibs[fibs.length - 2];
            // test against max
            if (nextFib >= n) {
                return fibs;
            }
            else {
                // concatinate next number to array
                return generateFibs(fibs.concat([nextFib]));
            }
        };
        // check input validity
        if (n <= 1) {
            return [];
        };
        // check base case
        if (n <= 2) {
            return [1,1];
        };
        // otherwise generate array recursively
        return generateFibs([1,1]);
    };

    return fibsLessThan(n).filter(x => x % 2 === 0).reduce((x,y) => x + y);
}

Lexical Scope: Only sumOfEvenFibsLessThan is in the global namespace.
The map in the map(f1).filter(f2).reduce(f3) pattern can be considered as f1 = x => x (aka "An identity function").
A trampoline is used to start generateFibs. Trampolines are a common functional programming technique to invoke a recursive function with a local lexical scope.


If you're using constants that are collections you'd be better off making them tuples, not lists. Trying to modify a tuple will raise an error as they're immutable, and using the tuple syntax makes it extra clear that these are unchanging constants.

FIXED_IP = (2, 6, 3, 1, 4, 8, 5, 7)
FIXED_EP = (4, 1, 2, 3, 2, 3, 4, 1)

As Caridorc said, using str.join is faster (depending on your version). It would also allow you to make permutate just one line.

def permutate(original, fixed_key):
    return ''.join(original[i - 1] for i in fixed_key)

It would also be a bit faster to pre-convert all your values in bits and key to integers. You can use map to apply a function to every member of a list, and it's faster than doing it in a list. You could do this when creating the zip object.

def xor(bits, key):
    new = ''
    for bit, key_bit in zip(map(int, bits), map(int, key)):
        new += str(((bit + key_bit) % 2))
    return new

Of course if you wanted this could also be made into a str.join, albeit a long one:

def xor(bits, key):
    return ''.join(str(((bit + key_bit) % 2)) for bit, key_bit in
                   zip(map(int, bits), map(int, key)))

There's a lot of functions here but not a lot of documentation. Explaining what individual functions do would make your code a lot easier to read. And I suspect you have some unnecessary duplicate functions, where you could pass a parameter instead of defining a whole new one. But it's hard to know when I don't entirely understand the functions you have here.


Take a destination for the reversed string

Instead of a local pointer, make reverse a void function:

void reverse(char * dst, const char * src, size_t length) {
    for(size_t i = 0; i < length; ++i) {
        dst[i] = src[length - i - 1];
    }
}

The names dst (destination) and src (source) and their order stem from standard library functions like strncpy.

size_t is an unsigned integer type, and large enough to index an array that spans your whole memory. We're allowed to define size_t i in the for loop, therefore our variable doesn't live any longer than necessary.

But you already did that for printArray, so I guess you knew that :)

void printArray(const char * array, size_t length) {
    for (size_t i = 0; i < length; i++) {
        putchar(array[i]);
    }
}

It's good practice to use const <type> * if you don't want to change the data by accident.

Use a function to ask for the string

To keep your main sleek and your code more reusable, provide a function to get the string from the user instead:

int getInput(char * dst, size_t max_len) {
    int length = 0;
    int c;

    while((c = getchar()) != EOF && length < max_len) {
        if(c == '\n')
            return length;

        dst[length++] = c;
    }
    return c == EOF ? EOF : length;
}

This will return EOF if getchar() returned EOF, and the number of read characters otherwise.

Putting all back together

I omit the functions I've already covered above, but if we use them, we end up with the following program:

#include <stdio.h>
#include <string.h>

#define ARRSIZE 1000

int getInput(char * dst, size_t max_len);
void reverse(char * dst, const char * src, size_t length);
void printArray(const char * array, size_t length);

int main(void) {
    int length = 0;
    char buff[ARRSIZE];
    char reversed[ARRSIZE];

    while ((length = getInput(buff, ARRSIZE)) != EOF) {
        reverse(buff, reversed, length);
        printArray(reversed, length);
    }
    return 0;
}

Which, in my opinion, is rather readable. Note that your memset wasn't necessary. After all, we're going to overwrite the values in buff with the next input.


Returning items which are different from their preceding items from a list

The itertools library has a handy function for this problem called groupby:

def f1(xs):
    for _, group_iter in itertools.groupby(xs, key = lambda pair: pair[0]):
        group = list(group_iter)
        yield group[0]

That'll get us the pairs for which the first element changed from the previous one. Now we just need to make sure we're yield-ing the last element. Which will only NOT be yielded if the last group has size more than 1, hence:

def f1(xs):
    for _, group_iter in itertools.groupby(xs, key = lambda pair: pair[0]):
        group = list(group_iter)
        yield group[0]

    # make sure we yield xs[-1]
    if len(group) > 1:
        yield group[-1]


Should I put a JavaScript function in a local or global scope?

I always wrap my code in an IIFE:

(function () {
    'use strict';

    //code here
}());

I also pass in all global variables I am going to use in this code block:

(function (window, document, $) {
    'use strict';

    //code here
}(window, document, jQuery)); //...

If I am going to expose any global variables I explicitly add them to the global scope at the end of this function (but I avoid this if it is at all possible):

(function (window, document, $) {
    'use strict';

    //code here

    window.XXX = somelocalreference;
}(window, document, jQuery)); //...

This way I never unexpectedly leak globals and I can know that my code is not going to give me problems with future changes that my coworkers or myself make.

See also: Responsive/adaptive website code


How to handle returned value if an exception happens in a library code

def parse_ET(self, ETObj):

Python style guide recommends lowercase_with_underscores for both function and parameter names

    if ETObj == None: return None

Use is None to check for None. However, consider whether you really want to support None as a parameter. Why would someone pass None to this function? Do they really want a None in return?

    dict_of_dict = collections.defaultdict(dict)

Avoid names that describe the datastructure. Choose names that describe what you are putting in it.

    try:
        for doc in ETObj.iter("result"):
            id = doc.attrib.get("id")
            for elem in doc.iter("attrib"):
                dict_of_dict[id].setdefault(elem.attrib.get("name"), elem.text)

Can there be duplicate "id" and "name"? If not you don't need to use defaultdict or setdefault

    except Exception, ex:

You should almost never catch generic exceptions. Only catch the actual exceptions you want.

        logging.exception("%s:%s" % (self.__class__, str(ex)))

Don't log errors and try to continue on as if nothing has happened. If your function fails, it should raise an exception. In this case, you probably shouldn't even catch the exception.

    finally:
        return dict_of_docs

finally is for cleanup tasks. Under no circumstances should you putting a return in it.


On top of the other very good answers:

Code organisation and tests

It is a good idea to separate the logic about input/output from the logic computing results. In your case, you could have a function taking an expression as a string and returning a number.

This makes your code easier to understand, easier to reuse and more testable.

Also, it is a good habit to put your code actually calling the logic behind an if __name__ == "__main__": guard.

All of this taken into account, you have:

def eval_math_expr(expr):
    negate = False
    while True:
        try:
            if expr[0] == '-': #for negative numbers
                negate = True #because here the numbers are string format
                expr = expr[1:]
            number1 = Test4Num(expr)[0]
            if negate == True:
                number1 = -number1
                negate = False
            end_number1 = Test4Num(expr)[1]
            expr = expr[end_number1:]
            if expr == '':
                return number1
            op = expr[0]
            expr = expr[1:]
            number2 = Test4Num(expr)[0]
            end_number2 = Test4Num(expr)[1]
            result = operation(op, number1, number2)
            number1 = result
            expr = str(number1) + expr[end_number2:]
        except Exception as e:
            print(e)
            break
    return number1

if __name__ == '__main__':
    interactive = False
    if interactive:
        expr = input('Enter your expression:')
        print(expr + '=')
        print(eval_math_expr(expr))
    else:
        for expr, res in {"2": 2, "2*4": 8, "4+8": 12, "100/3": 33, "2^3": 8}.items():
            result = eval_math_expr(expr)
            if res != result:
                print("Computing", expr, "got", result, "instead of", res)

I also took this chance to remove the silent catch of exceptions which makes things hard to understand when an error occurs.

By the way, bare except (with no explicit exception type caught) and ignored exceptions are usually frowned upon as they make debugging very painful.

Naming

Your function names are not very good. Your could define is_digit, get_number, perform_operation.

Simplify is_digit function

The best data structure for the check you want to perform is a set.
You could write something like:

DIGITS = set('0123456789')

def is_digit(var):
    return var in DIGITS

Simplify perform_operation

The best data structure for the logic you want to perform is a dictionnary mapping operators to functions.

import operator

OPERATIONS = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.floordiv,
    '^' : operator.pow,
}

def perform_operation(string, num1, num2):
    op = OPERATIONS.get(string, None)
    if op is not None:
        return op(num1, num2)
    else:
        return None  # How to handle this?

Note: using floordiv instead of truediv fixes an issue found with tests mentionned above.

Simplify get_number

In Python, you usually don't need to get elements from an object by index. What you want is usually to iterate over the different elements. I highly recommand reading/watching Ned Batchelder talk called "Loop Like A Native". In your case, you could write something like:

def get_number(varstr):
    s = ""
    for c in varstr:
        if not is_digit(c):
            break
        s += c
    return (int(s), len(s))

Using tuple unpacking

As already said, you could use number1, end_number1 = get_number(expr) to call get_number only once.

At this stage, the code looks like:

import operator

DIGITS = set('0123456789')
OPERATIONS = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.floordiv,
    '^' : operator.pow,
}

def is_digit(var):
    return var in DIGITS

def get_number(varstr):
    s = ""
    for c in varstr:
        if not is_digit(c):
            break
        s += c
    return (int(s), len(s))

def perform_operation(string, num1, num2):
    op = OPERATIONS.get(string, None)
    if op is not None:
        return op(num1, num2)
    else:
        return None  # How to handle this?

def eval_math_expr(expr):
    negate = False
    while True:
        try:
            if expr[0] == '-': #for negative numbers
                negate = True #because here the numbers are string format
                expr = expr[1:]
            number1, end_number1 = get_number(expr)
            expr = expr[end_number1:]
            if negate == True:
                number1 = -number1
                negate = False
            if expr == '':
                return number1
            op = expr[0]
            expr = expr[1:]
            number2, end_number2 = get_number(expr)
            result = perform_operation(op, number1, number2)
            number1 = result
            expr = str(number1) + expr[end_number2:]
        except Exception as e:
            print(e)
            break
    return number1

if __name__ == '__main__':
    interactive = False
    if interactive:
        expr = input('Enter your expression:')
        print(expr + '=')
        print(eval_math_expr(expr))
    else:
        for expr, res in {"2": 2, "2*4": 8, "4+8": 12, "100/3": 33, "2^3": 8, "-2": -2, "-2-3": -5}.items():
            result = eval_math_expr(expr)
            if res != result:
                print("Computing", expr, "got", result, "instead of", res)

About negate

You set negate to False at the very beginning and make sure you reset it back to False at each iteration so that the next iteration works fine. It would be clearer to initialise it to False at the beginning of the iteration. You could also set it to negate = expr[0] == '-'.

        negate = expr[0] == '-' #for negative numbers
        if negate:
            expr = expr[1:]
        number1, end_number1 = get_number(expr)
        expr = expr[end_number1:]
        if negate:
            number1 *= -1

An alterative could be to handle this as part of the get_number function.

def get_number(varstr):
    s = ""
    if varstr[0] == '-':
        s += "-"
        varstr = varstr[1:]
    for c in varstr:
        if not is_digit(c):
            break
        s += c
    return (int(s), len(s))

def eval_math_expr(expr):
    while True:
        try:
            number1, end_number1 = get_number(expr)
            expr = expr[end_number1:]
            if expr == '':
                return number1
            op = expr[0]
            expr = expr[1:]
            number2, end_number2 = get_number(expr)
            number1 = perform_operation(op, number1, number2)
            expr = str(number1) + expr[end_number2:]
        except Exception as e:
            print(e)
            break
    return number1

The whole code is:

import operator

DIGITS = set('0123456789')
OPERATIONS = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.floordiv,
    '^' : operator.pow,
}

def is_digit(var):
    return var in DIGITS

def get_number(varstr):
    s = ""
    if varstr[0] == '-':
        s += "-"
        varstr = varstr[1:]
    for c in varstr:
        if not is_digit(c):
            break
        s += c
    return (int(s), len(s))

def perform_operation(string, num1, num2):
    op = OPERATIONS.get(string, None)
    if op is not None:
        return op(num1, num2)
    else:
        return None  # How to handle this?

def eval_math_expr(expr):
    while True:
        try:
            number1, end_number1 = get_number(expr)
            expr = expr[end_number1:]
            if expr == '':
                return number1
            op = expr[0]
            expr = expr[1:]
            number2, end_number2 = get_number(expr)
            number1 = perform_operation(op, number1, number2)
            expr = str(number1) + expr[end_number2:]
        except Exception as e:
            print(e)
            break
    return number1

if __name__ == '__main__':
    interactive = False
    if interactive:
        expr = input('Enter your expression:')
        print(expr + '=')
        print(eval_math_expr(expr))
    else:
        for expr, res in {"2": 2, "2*4": 8, "4+8": 12, "100/3": 33, "2^3": 8, "-2": -2, "-2-3": -5}.items():
            result = eval_math_expr(expr)
            if res != result:
                print("Computing", expr, "got", result, "instead of", res)

Reorganisation in the main function

At the moment, the code parses two number and an operation, computes the operation, convert the result into a string to be parsed at next iteration. Thus, each temporary result gets converted from integer to string then integer. This leads to issues when the result cannot be converted back and forth - for instance when you perform divisions with non-integer result. Also this could be optimised a lot with the following logic:

get the first number and store it as the current number
in each iteration: get the operation and the next number. Compute the operation and store the result as the current number, to be reused at next iteration.
at the end, return the current number.

You could write this:

def eval_math_expr(expr):
    n, end_n = get_number(expr)
    expr = expr[end_n:]
    while expr:
        op, expr = expr[0], expr[1:]
        n2, end_n = get_number(expr)
        n = perform_operation(op, n, n2)
        expr = expr[end_n:]
    return n


You may improve performance:

I would use the modulo operator instead of a function call you aren't benefiting from 100%. Math.DivRem returns a value (quotient) that you don't use. Same result:

var rem = a + b % mod;

Saves you a few unboxing operations and method call

Func<int, int, int, int> modular = (a, b, mod) =>
{
    var rem = a + b % mod;

    if (rem < minvalue)
        rem += minvalue;

    return rem;
};

Saves half the time? http://pastebin.com/XTaLCQh4


Am I using crypt and mcrypt well in this simple encryption class?

Your salt generation mechanism does not seem sufficiently random. You will end up with a very small set of salts.

First of all, time() is not random at all. In second place, rand(0, 1023) is not only a relatively weak random number generator, but also generates too few bits to be enough.

All this - combined with the use of the relatively unsafe md5 algorithm - means that there's a higher-than-ideal risk of salt collision.

Will all of this still cause trouble? Frankly, I don't know. This is definitely better than storing passwords in plain text, or using unsalted hashes, but it's not perfect. Generally, I'm nervous about using not-exactly-random data for security algorithms that are meant to use random data.

For a starting point, try to look at this stackoverflow question. This is what the author does for salt generation:

Use OpenSSL random pseudo bytes, if available. Using a security library to get random data for use in another security function makes me far less nervous than ordinary rand().
Try a *NIX-specific method
If not possible, then use a mix of md5, microtime(better than time since it changes more often) and even the PID.

In particular, note than PHP's md5 normally returns a hexadecimal string with a 32-byte length, but bcrypt expects a string with a length of 22, so that might cause troubles (namely, the salt will not be as secure as it could be)

Also, in your case this won't be a problem, but $2a is ambiguous (but sadly, the correct, unambiguous way might be incompatible with older PHP versions). If you can, consider using $2y instead and see if that works for you.

The PHP documentation recommends using mcrypt_enc_get_iv_size instead of mcrypt_get_iv_size and using that in combination with mcrypt_module_open (although strangely, the documentation for mcrypt_encrypt does use mcrypt_get_iv_size)

Again, you are using not-really-random data for a function that seems to expect random data (specifically, the IV when the supplied IV is "null"). This makes me nervous.


Dealing with messy JSON API and UTF-8 encoding problems

I don't see why del jsonobject[...] would be necessary before
reassigning that key.  Also, the test in the last two lines could
also be simplified to something like
jsonobject.pop('small_encoded_polyline', None) if you don't care
about that key, no?

Also:

Everything could use more error checking.  That is, check expected
types and values instead of falling through the ifs ('imperial',
'metric', what happens if it's neither, or both?).
Unless you really prefer list and dict, it's better to use the
literal syntax [] and {} (the names could be shadowed by some
definition).
The type check for dicts can be better, i.e.
isinstance(foo, dict); if you really want only dict, then it's
still better to use type(foo) is dict instead of comparing strings.
I'd also move that whole if/else into a function,
e.g. maybe_load_json or so.
The value of document after the assignments isn't used anywhere, so
it's safe to remove, though I'd rather use that variable again instead
of introducing document2.
The second branch with 'small_encoded_polyline' seems to have the
wrong level of indentation?  At least it's different from the first
one in that it's only run if the document wasn't a dict.  Assuming
that it's safe to run anyway I'll change that in the code below.
The pattern if foo in json and json[foo] is not None: could be easier
be achieved with if json.get(foo) is not None: as the return value
there defaults to None.
I'm not particularly fond of the habit to reuse input data like with
'points_correct' done here.  It would be cleaner just to have a list
points_correct and assign that to a jsonobject key (and you know,
possibly put the calculation into a separate function as well).

I might have messed up some of the logic now, but I hope you get the
idea:

def maybe_load_json(document):
    if isinstance(document, dict):
        return document
    return json.loads(document)

def cleaned_small_encoded_polylines(documents):
    result = []
    for document in documents:
        #sometimes these document objects turn out to be dicts
        #and sometimes they turn out to be strings
        #even though JSON output is always the same
        #is there a better way to deal with this?
        document = maybe_load_json(document)
        if document.get('small_encoded_polyline') is not None:
            del document['small_encoded_polyline']
            #I thought this line above would modify the original
            #jsonobject since document is a dictionary so I should
            #be working with a pointer to the original object
            #but inspection of jsonobject reveals this not to be the case
            result.append(document)
    return result

...

    r = requests.get(url, headers = {'User-Agent':UA})
    jsonobject = r.json()
    if jsonobject.get('laps') is not None:
        if 'imperial' in jsonobject['laps']:
            laps_array = jsonobject['laps']['imperial']
            type = 'imperial'
        if 'metric' in jsonobject['laps']:
            laps_array = jsonobject['laps']['metric']
            type = 'metric'
        if laps_array is not None:
            jsonobject['laps'][type] = cleaned_small_encoded_polylines(laps_array)

    # this can't be an elif because sometimes json objects
    # have both "points" and "laps"
    if jsonobject.get('points') is not None:
        if 'points' in jsonobject['points']:
            points_correct = []
            laps_array = jsonobject['points']['points']
            if laps_array is not None:
                jsonobject['points']['points'] = cleaned_small_encoded_polylines(laps_array)

    jsonobject.pop('small_encoded_polyline', None)


Using System.Linq library the method can be rewritten like this:

public static int GetRemainingDays(DateTime startDate, DateTime endDate, ISet<DayOfWeek> includedDays)
{
    return Enumerable.Range(0, Int32.MaxValue)
        .Select(n => startDate.AddDays(n+1))
        .TakeWhile(date => date <= endDate)
        .Count(date => includedDays.Contains(date.DayOfWeek));
}

Which can then be more easily called like this:

GetRemainingDays(startDate, endDate,
    new HashSet<DayOfWeek>{DayOfWeek.Wednesday, DayOfWeek.Friday});

Note: You should test this (and the original version) against off-by-one errors.


Instantiating a run-time implementation of an interface

Two parts to this review:

the 1-liner for the newInstance()
the general mechanism of the method

newInstance()

This code will work, but only for a subset of Collections. For example, there are many Collection implementations that do not have an accessible default constructor. What if the input collection is:

Collection<String> input = Arrays.asList(new String[]{"hello","world"});

The newInstance call on the class of that List will fail.... because that is a class called java.util.Arrays$ArrayList and it is not public at all...

The 'specification' for this problem is probably contrived, and there is no expectation that it should behave well when the inputs are bad. As a contrived example, I guess contrived code is OK.

Which leads on to the next thing, what is the right thing to do?

Well, I don't think there is a right thing to do. If the input requires the support of bare 'Collection' then you have no hope.

In a real example, I would probably specify the method to allow specific known collections that the program would expect. Then not use the newInstance at all.

Alternatively, I would use the Java-8 style Supplier, and have an input that supplies you with the collection you need, and shift the burden to the user of your method. Something like:

public interface CollectionSupplier<T> {
    Collection<T> supply();
}

and then have your method declared as:

public static <E> ArrayList<Collection<E>> SplitCollection (
        final Collection<E> col, final CollectionSupplier<E> supplier) {
    .....
    Collection<E> colEl = supplier.supply();
    ....
}

That would also remove the ugly exceptions you declare to throw... as it is, I would probably (bad practice) 'try' the whole loop, and 'catch' the ugly exceptions and replace them with a wrapper of an IllegalStateException that explains that an inner Collection could not be instantiated.

General

Overall your method is neat, and well structured. I can't really fault it, given the constraints of the problem.

Update: Actually, the method should have a lower-case 's' to start the name. How did I miss that the first time? Should be splitCollection not SplitCollection

I would prefer that the method declared the input col as final:    public static <E> ArrayList<Collection<E>> SplitCollection (final Collection<E> col) because that is a habit I am in...

Typically I would recommend against returning the data typed as an ArrayList because the implementation should not be reflected, it should just be List, but, again, in this case, the specification requires an ArrayList return value.

Bonus

A Java 8 implementation of this would be a good exercise.

This is what I would try:

public static <T, U extends Collection<T>, V extends Collection<T>> ArrayList<V> splitCollection (U col, Supplier<V> supplier) {

    return col.stream().map(v -> {
           V subcol = supplier.get();
           subcol.add(v);
           return subcol;
        }).collect(Collectors.toCollection(ArrayList::new));
}

and it would be used like:

public static void main(String[] args) {
    System.out.println("Result:"
       + splitCollection(Arrays.asList("hello","world"), ArrayList::new));
}

which gives the output:

Result:[[hello], [world]]

Note, in the Java 8 example, I allow the sub collection to be any supported type that you can add the content to. So, for the above example, the input is an inaccessible list (no public default constructor), but the supplier gives you what you need.


Your code looks solid, however here are a few minor points.

Catching/throwing exceptions

You should only catch exceptions when you are going to handle them. There's no point in catching an exception when you're only going to (re)throw it. However if you were to use logging and still 'bubble up' the exception, you could go with this:

try
{
    //Your webrequest/response code...
}
catch (Exception ex)
{
    //DO YOUR LOGGING HERE

    throw;
}

But as of now I would remove the try/catch from the method and handle exceptions outside of it:

try
{
    string theHtml = NetworkHelper.GetHtml("http://example.com");
}
catch (WebException ex)
{
   //Handle the exception
}

Stored url and data

As of now, your code doesn't allow the same url twice in a row; it'll just return the stored data. This raises 2 questions/issues with me:

What if I want to refresh the result?
I can bypass the check easily but in a hacky way:

Pass url1
Pass url2 to change the _storedUrl variable
Call the method again with url1

I think better would be to change the signature of the method and add a boolean (optional) parameter to indicate if you want to refresh the result:

public static string GetHtml(Uri url, bool refresh = false)
{
    if (url == _storedUrl && !refresh)
        return _storedData;
    else
        _storedUrl = url;

    //Rest of the logic...
 }

Now you will only return the _storedData if you have the same url and don't want to refresh.

Hope this helps!


Reading numbers from console until input isn't a number

Your code does not read numbers from the "console until input isn't a number", but reads 100 inputs strings from the console and returns those that can be converted to integers.

If you want to read numbers from the console "until input isn't a number", you could do something like this:

let numbers1 max = seq {for x in 1..max do yield Int32.TryParse(Console.ReadLine()) }
                  |> Seq.takeWhile (fun (b, x) -> b)
                  |> Seq.map (fun (b, x) -> x)

or

let numbers2 max = seq {for x in 1..max do yield Int32.TryParse(Console.ReadLine()) }
                    |> Seq.takeWhile (fun (b, x) -> b)
                    |> Seq.map (fun (b, x) -> x)
                    |> Seq.toList

if you want to defer the return of each input to after the last valid input has been entered.


Returning consonants of a plane's starting and ending points

Your code is working but repeating all those Replace seems to be unnecessary. Firstly, you repeat them five times for single word and then once again two times because of processing two words. Code becomes long and unclear. Always, when we repeat code, it is good time to think about improvements and reducing those repeats.

So first, I would start to think about reducing repeats in line:

string startConsonants = starting.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");

You can do, for example, use LINQ:

string vowels = "aeiou";
var consonants = starting.Where(c => !vowels.Contains(char.ToLowerInvariant(c))); // (1)

And then simply, instead of operating on arrays startConsonants[0].ToString() and startConsonants[startConsonants.Length-1].ToString(), you can write:

char first = consonants.First();
char last = consonants.Last();

This code is more clear than yours because it has clear intention: select only not vowels and then take first and last of them. No repeating code, no indices calculation etc.

Then, to not repeat line (1) two times, I would create a method for it:

public string GetConsonants(string input)
{
    string vowels = "aeiou";
    var consonats = input.Where(c => !vowels.Contains(char.ToLowerInvariant(c)));
    return new string(consonats.ToArray());
}

and then:

public string Consonants()
{
    string starting = direction.Split('-')[0];
    string destination = direction.Split('-')[1];

    string startConsonants = GetConsonants(starting);
    string destConsonants = GetConsonants(destination);

    return string.Format("{0}{1}-{2}{3}", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());
}

Eventually, to go along with .NET/C# ideology, I would create an extension methods for Char and String to make everything clear:

public static class CharExtensions
{
    private static string Vowels = "aeiou";

    public static bool IsVowel(this Char chr)
    {
        return Vowels.Contains(char.ToLowerInvariant(chr));
    }

    public static bool IsConsonant(this Char chr)
    {
        return !IsVowel(chr);
    }
}

public static class StringExtensions
{
    public static string OnlyConsonants(this String str)
    {
        return new string(str.Where(c => c.IsConsonant()).ToArray());
    }
}

and then:

public string Consonants()
{
    string starting = direction.Split('-')[0];
    string destination = direction.Split('-')[1];

    string startConsonants = starting.OnlyConsonants();
    string destConsonants = destination.OnlyConsonants();

    return string.Format("{0}{1}-{2}{3}", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());
}


Your demonstration could benefit from better semantic markup.  In particular, the numbers on the left should be treated as navigation links, whose target is the item to be animated.  If you remove all JavaScript and CSS, the functionality degrades gracefully.

An additional benefit is that the link directly identifies the item to be manipulated, so that you don't have to locate the element yourself using a var prodName = $(this).data('prod'); if (prodName == className) … check.

You don't need to define a .hide { display: none; } rule in your CSS.  The jQuery $.hide() and $.show() methods can do that job.

Take care to localize $this.

$(document).ready(function () {
    $('nav > ul > li > a').on('click', function () {
        $('li.animated').hide();
        $($(this).attr('href')).each(function () {
            var $this = $(this);
            $this.show()
                 .removeClass('bounceInRight')
                 .addClass('bounceOutRight');
            setTimeout(function () {
                $this.removeClass('bounceOutRight')
                     .addClass('bounceInRight');
            }, 400);
        });
    })
});
nav > ul > li {
    display: inline-block;
    padding: 10px;
}
nav > ul > li > a {
    color: black;
    text-decoration: none;
}
ul {
    position: fixed;
    top: 0;
    right: 0;
    list-stlye: none;
}
nav > ul {
    right: auto;
    left: 0;
}
li.animated {
    background: yellow;
    width: 350px;
    height: 600px;
    /* transition: height 0.3s ease, width 0.2s ease;*/
    overflow: hidden;
    margin-top: -30px;
    padding-top: 30px;
    margin-right: -50px;
}

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.6/animate.min.css">

1

2

3

1

2

3


I created a ring buffer variant for this answer. It was loosely based upon this question and performs considerably better so it may be beneficial to others; note though that it has not been checked for equivalence (and it uses float instead of BigDecimal):

public class MovingAverage {

    private final float[] window;
    private float sum = 0f;
    private int fill;
    private int position;

    public MovingAverage(int size) {
        this.window=new float[size];
    }

    public void add(float number) {

        if(fill==window.length){
            sum-=window[position];
        }else{
            fill++;
        }

        sum+=number;
        window[position++]=number;

        if(position == window.length){
            position=0;
        }

    }

    public float getAverage() {
        return sum / fill;
    }

}


Finding the candidate with the majority of ballots

Before making it faster, it is important to make it better.

Scope of variables

You currently have 3 static variables in your code

static String winner;
static String current;
static int count;

that are only used inside the getWinner method. This is not a good idea:

A variable should have a scope as minimal as possible. This means you only declare that variable when you need it and not a moment before.
They are not private which means that another unrelated class could even access and modify them, thereby completely destroying the algorithm.

You should remove those static variables and have instead:

int count = listOfBallots.size()/2;
// ...
String current = listOfBallots.get(i);
// ...
String winner = null; // before the if/else part

Unused variable

You are storing the size of the input list into the variable totalSize but this variable is unused in the rest of your code. You should either remove it (unused code should be deleted) or make use of it and not call listOfBallots.size() each time it is needed.

Since the current code gets the size of the list multiple times, it would be better to store it like you did and reuse that variable. Example, instead of:

int count = listOfBallots.size()/2;

have

int count = totalSize / 2;

Also, notice the added spaces before the operator / that adds to readability.

Don't compare booleans to true or false

In the case of an empty list, you currently return null with:

if (listOfBallots.isEmpty() == true){
    return null;
}

This explicit check with == true is redundant and even harder to read than a simple

if (listOfBallots.isEmpty()) {
    return null;
}

Early return

In your code, you are returning early in the case of an empty list. But you are not going all the way. You have:

if (listOfBallots.isEmpty()) {
    return null;
} else {
    // ...
}

The else part is not needed and it adds an unnecessary indent to the code. Consider removing it, thereby shifting all the subsequence code one indentation to the left, so making it easier to read for small screens:

if (listOfBallots.isEmpty()) {
    return null;
}
// ...

As noted by Fabian Barney in the comments, you don't even need to return early: when the list is empty, your initial count will be equal to listOfBallots.size()/2 and null will still be returned. Might as well get rid of it and make the code shorter.

Enhanced for loop

Your two loops are written using the traditional index solution:

for (int i = 0; i < totalSize; i++){
    // ...
    String current = listOfBallots.get(i);
    for (int j = 0; j < totalSize; j++){
        if (listOfBallots.get(i) == listOfBallots.get(j)){
            // ...

When you don't need the index, it is better to use the enhanced for loop. It makes the code more compact and easier to read:

for (String current : listOfBallots) {
    // ...
    for (String other : listOfBallots) {
        if (current == other) {

Notice that it also makes another problem appear more clearly:

Do not compare Strings with ==

This won't work like you would expect. To compare Strings, you should really use the equals method and have:

if (current.equals(other))

Returning null

As a last comment, if you explicitely return null when no winner has been found then it would be best to document it clearly. There could be other approaches, like:

Throwing a custom exception.
Returning an Optional<String> (starting with Java 8).

Putting it all together

We all those comments, you could have the following:

public static String getWinner(final List<String> listOfBallots) {
    int totalSize = listOfBallots.size();
    int count = totalSize / 2;
    String winner = null;
    for (String current : listOfBallots) {
        int running = 0;
        for (String other : listOfBallots) {
            if (current.equals(other)) {
                running++;
            }
        }
        if (running > count) {
            count = running;
            winner = current;
        }
    }
    if (count > totalSize / 2) {
        return winner;
    } else {
        return null;
    }
}

Now, let's analyze your current code and spot where the slowness is coming from. The goal of the method is:

  to find the "winner" (defined by the String that appears more than collection.size()/2).

To do that, you are looping over the list, and for each element, you are looping a second time over the list and counting equals element. That is the slow part: for a list of size n, you just made your approach O(n2). You are traversing the list again and again to find the equal elements.

How to improve that? Look at it this way: the goal is to count the number of times the String appears in the list. To do that, we just need to loop over that list only once, but remember the current count.

Take the following list:

A  ---  B  ---  A  ---  D

We first encounter A and we remember that A has been encountered 1 time.
Then we move to B. B was never encountered so we also remember that, now, we encoutered it 1 time.
Then we move to A. But, now, we know that it has already been encoutered 1 time: we remembered it already. So we can just remember that A was encoutered 2 times now.
Finally, we hit D that we never encountered and we remember that we encoutered it 1 time.

In that pattern, the list was only traversed a single time. With the current implementation, it would have been traversed 5 times (the main one and 4 other times to count for how many times each element appeared).

A good data structure to use for that memory is a Map<String, Integer>, that is to say a data structure that maps one String into a count.

There is another optimization that we can make. The winner is the String appearing more than half the time in the initial collection. This means that once we found the winner, there is no need to continue. No other element will be able to appear more than the element that appeared more than half the time. Put another way, if a String A has appeared more than n/2 times, no other element B can appear more times than A: there are less than n/2 elements remaining.

With all this in mind, this is what you could have, that will be a lot more performant:

public static String getWinner(final List<String> listOfBallots) {
    int count = listOfBallots.size() / 2;
    Map<String, Integer> map = new HashMap<>();
    for (String current : listOfBallots) {
        int running = map.containsKey(current) ? map.get(current) + 1 : 1;
        map.put(current, running);
        if (running > count) {
            return current;
        }
    }
    return null;
}

For each element, we determine the number of times it appeared: if it already appeared (so the map contains the key), we add 1; else it is the first time.

Then when we found an element that appeared more than half the time, we return it directly.

With Java 8 constructs

Using Java 8, it is possible to use the merge method on the map and simplify a bit the code. Instead of having

int running = map.containsKey(current) ? map.get(current) + 1 : 1;
map.put(current, running);

we could just have:

int running = map.merge(current, 1, Integer::sum);

And if you're using Java 8, consider returning an Optional<String> instead of null:

public static Optional<String> getWinner(final List<String> listOfBallots) {
    int count = listOfBallots.size() / 2;
    Map<String, Integer> map = new HashMap<>();
    for (String current : listOfBallots) {
        int running = map.merge(current, 1, Integer::sum);
        if (running > count) {
            return Optional.of(current);
        }
    }
    return Optional.empty();
}


You don't need array b.  Try this.

    for (int i = 0; i < 9; i += 3) {
        System.out.println("+---+---+---+");
        for (int j = i; j < i + 3; ++j)
            System.out.printf("| %s ", a[j] == 10 ? "O" : a[j] == 100 ? "X" : " ");
        System.out.println("|");
    }
    System.out.println("+---+---+---+");


object oriented Node.js class RiddleInfo.js

From the outset, I'm not sure how useful/necessary this constructor ("class") is, to be honest. Everything could seemingly be stored in a simple object literal:

var aRiddle = {
  riddle: "What gets wetter and wetter the more it dries?",
  answer: "A towel",
  difficulty: "meh",
  ohFactor: "so-so",
  hints: [
    "Galactic hitchhikers should always bring one",
    "Look in the bathroom",
    "Everyone has several of the things"
  ]
};

Point is, your class doesn't do any input checking, and most of its methods are getters and setters - which don't necessarily make much sense in JavaScript. For instance. I can do this:

var aRiddle = new RiddleInfo();             // no arguments at all: no errors
aRiddle.riddle = "This statement is false"; // bypasses setter completely
aRiddle.foo = 23;                           // arbitrary property assignment
aRiddle.setAnswer(new Date());              // using setter, but passing in nonsense

The only methods left are getHint and isSimilarTo. Both of these could be handled by functions outside the object. Yes, it defies encapsulation, but... 'eh, I'd choose that over a lot of "pointless" code.

But, let's give the code a once-over. Again, I'd suggest a very different approach, but that's not the same as reviewing the code you posted.

First off, your constructor takes an awful lot of arguments. This creates very tight coupling to any other code: All that other code must know the correct order of all those arguments to use the constructor, which makes it harder to change this constructor in the future without breaking everything.
Now, I'm not sure what arguments you consider required and which ones might be optional, but at the very least, I'd say a riddle consists of a question, and an answer. I'd consider the other arguments optional for now. And to avoid having to order the arguments correctly, I'd use an object literal (like the one above) for all the optional arguments:

function RiddleInfo(question, answer, options) {
  // ... see below ...
}

As mentioned, I'd skip getters and setters unless they actually contributing in some way. For instance, they could (should) check their input, to prevent nonsense values being set. And if you're going to have them, you might as well use them yourself.

function RiddleInfo(question, answer, options) {
  this.setQuestion(question);
  // ...
}

RiddleInfo.prototype.setQuestion = function (question) {
  if( typeof question !== "string" ) {
    throw new TypeError("Question must be a string");
  }
  this.question = question;
};

Now the constructor will use the setter, meaning it's guaranteed to throw a TypeError if you're using it wrong. You can do something similar for the other arguments, as well as the optional ones.

Speaking of: Don't return a string that looks like an exception like you do in getHint. It's basically lying: It's not an "InvalidArgumentException" - it's just a string. And hardcoding the line number in there is crazy - you'll have to change it constantly, even if you've only been adding comments or just whitespace. Just throw a real exception. It'll contain a stack trace, and give you the line number.

Anyway, the above neglects one thing: You can still completely bypass the setter by just writing riddle.question = .... Now, as mentioned, getters and setters are probably more trouble than their worth in JavaScript, but if you want a more "secure" way of doing things, you'll have to change things up a bit:

function RiddleInfo(question, answer, options) {
  // define the setter here
  this.setQuestion = function (newQuestion) {
    if( typeof question !== "string" ) {
      throw new TypeError("Question must be a string");
    }
    question = newQuestion;
  };

  // define the getter here too
  this.getQuestion = function () {
    return question;
  };

  this.setQuestion(question);

  // ... similar thing for other arguments ...
}

The point in the above is that question remains a local variable inside the constructor function. Instead of setting it on the instance (this.question = question), we set the getter/setter functions instead. Thanks to closures, they can access the local question variable. What you get is something like

var aRiddle = RiddleInfo("...", "Darkness");

aRiddle.setQuestion("The more there is, the less you see. What could I be?");
aRiddle.getQuestion(); // => "The more there is [...]"
aRiddle.question = "this won't have any effect";
aRiddle.getQuestion(); // => "The more there is [...]"

Lastly, if you've got more than 1 of something, you should probably use an array: i.e. use an array for the hints. You may want more than 3 or fewer, so don't have named variables for exactly 3.

Phew, I think I'll stop here. Hopefully you've got something to chew on.