First thing I would say is that you could reduce the number of variables you use. The iterator of a For loop, if instanced from outside the loop's context (as in your case), can be reused. Doing so you could already reduce the numbers of variables you use.

I do not understand what you mean by "easier to code", but if you mean that you seek a way to more easily re-use this code, you could either make a static method that would display a cross with specific parameters or an object with a display function.

Here is an exemple of a Cross object:

public class Cross {

    private int sectionSize;

    public Cross(int sectionSize) {
        this.sectionSize = sectionSize;
    }

    public void display() {
        final int height = sectionSize * 3;
        final char character = '*';
        //The iterators
        int i, j;

        //This loop controls the line
        for (i = 0; i < height; i++) {
            //Check wether or not to add spaces
            if (i < sectionSize || i > sectionSize * 2) {
                //Add spaces
                for (j = 0; j < sectionSize; j++)
                    System.out.print(" ");
                //Add the characters
                for (j = 0; j < sectionSize; j++)
                    System.out.print(character);
            }
            else
                for (j = 0; j < height; j++)
                    System.out.print(character);
            System.out.println();
        }
    }
}

Or in the format of a static method (which is actually the display method of the last object without the comments):

public static void drawCross(int sectionSize, char character) {
    final int height = sectionSize * 3;
    int i, j;

    for (i = 0; i < height; i++) {
        if (i < sectionSize || i > sectionSize * 2) {
            for (j = 0; j < sectionSize; j++)
                System.out.print(" ");
            for (j = 0; j < sectionSize; j++)
                System.out.print(character);
        }
        else
            for (j = 0; j < height; j++)
                System.out.print(character);
        System.out.println();
    }
}

Here is how you would use either of these solutions:

public static void main(String [] args) {
    final int sectionSize = 5;

    //Use of the Object
    Cross cross = new Cross(sectionSize);
    cross.display();

    //Use of the static method
    Cross.drawCross(sectionSize, '*');
}

Now, if it were not for the necessity of using For loops, I would have replaced the loop that adds the space with a simpler:

System.out.printf(("%," + sectionSize + "s"), "");

and then I would have added the characters of the cross in a loop.
I hope this helps you.


Check if a given string can be a palindrome by altering some character without using a library function

The above looks to be more work than is necessary. Assuming that we are working with all lower case chars, the following should work.

We match the chars at each end, moving inwards on each cycle. Normally, if any do not match, we consider it a fail and break out. If we are allowed a one pair mismatch (i.e. change one character), then we need to keep track of the count of mismatches and if we have 0 or 1 (less than 2) we consider it to be a palindrome.

private static boolean isAlmostPalindrome(String str){
    int diffCount = 0;
    int left = 0;
    int right = str.length() -1;

    while(right>left){
        if (str.charAt(right--)!= str.charAt(left++)){
            diffCount++;
        }
    }
    return diffCount <2;
}


Find primes using Sieve of Eratosthenes with Python

Your code looks correct to me, it does produce prime numbers
in the given range.

PEP8 Online reports some code style violations
with respect to whitespace and line length, but it is not too bad.

But: This is not the Sieve of Eratosthenes.
The Sieve of Eratosthenes keeps a (single) list of all candidate
numbers, and computes multiples
of each found prime to mark subsequent composite numbers in the list.
Your algorithm computes the remainder of all remaining candidates instead, and creates new lists in each step.

As a simple benchmark I ran

print(sum(p for p in get_primes(100000)))

with your code, this takes approximately 5 seconds on my MacBook.

It can be improved slightly by filtering the list only once in
each step and not twice:

def get_primes(max_int):
    numbers = range(2, max_int)
    while len(numbers) > 0:
        yield numbers[0]
        numbers = [num for num in numbers if num % numbers[0] != 0]

This reduces the time to 4.6 seconds.

But any “real” Eratosthenes sieve is much faster. As an example,
with this one
from Rosetta code

def primes_upto(limit):
    is_prime = [False] * 2 + [True] * (limit - 1)
    for n in range(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)``
        if is_prime[n]:
            for i in range(n*n, limit+1, n):
                is_prime[i] = False
    return [i for i, prime in enumerate(is_prime) if prime]

the above benchmark runs in 0.08 seconds.


I see that you have some error handling for int(input(...)).  I would change it, however.  Let's say that the user types a valid number of PC's, but does not type a valid player initiative.  That would trigger a ValueError, and your except block would ask again how many PC's.  Why should it restart the whole process for one little mistake?  You should have different try blocks for each of those. Also, a try block should include only the code that you expect might throw an error.  If some other code throws an error, you want to know about it.

For the first use of int(input(...)), I would just take it out completely.  Why should the user need to specify how many PC's?  Why not just keep going until he runs out and then hit Enter on a blank line?  That can be done quite simply with iter().  Usually, iter() is given an iterable, but if it is given two arguments,  the first argument is a callable (usually a function) that returns a value.  (In our case, we use lambda: input(...)).  The second argument is the stopping point.  iter() will keep calling that function and yielding the result until it returns the second argument. Therefore, we give it '', and we get all of the user's inputs until he types nothing in a line.

The second use of int(input(...)) is when you are retrieving the player initiative.  It should have its own try-except block to make sure the input is an integer.  I would then put that block inside of its own while loop so that the program keeps asking until it gets a valid answer.

Instead of a chain of string concatenations, use string formatting:

player_initiative = input('What is {} initiative? '.format(player_name))

and

print('{}: {}'.format(key, ', '.join(initiative_tracking[key])))

A loop is called that because it loops.  You don't need to tell it to keep looping.  It will keep looping until it is told to stop.  Sometimes it is stops because a condition is not met, but sometimes it stops because it encounters a break.  You should use continue only if you want to skip the code beneath and jump straight to the beginning of the loop.  It really doesn't make sense to put continue at the end of the loop.

The argument that is given to sorted() has only one requirement: that it is iterable.  To test if a type of object is iterable, go into a Python shell and create an instance of it.  Then, do for item in my_object: print(item).  If there is an error, your object is not iterable.  Otherwise, you will see what happens when iterates.  For a dictionary, you get all of the keys.  Therefore, sorted(initiative_tracking.keys(), reverse=True) can be simplified to sorted(initiative_tracking, reverse=True).

Full code:

print('Welcome to Initiative Tracker!')

initiative_tracking = {}
for player_name in iter(lambda: input("What is the player's name? "), ''):
    player_initiative = input('What is {} initiative? '.format(player_name))
    while True:
        try:
            player_initiative = int(player_initiative)
            break
        except ValueError:
            player_initiative = input('Please enter an integer: ')

    if player_initiative in initiative_tracking:
        initiative_tracking[player_initiative].append(player_name)
    else:
        initiative_tracking[player_initiative] = [player_name]

print('\nYour initiative order is: ')
for key in sorted(initiative_tracking, reverse=True):
    print(str(key) + ': ' + ', '.join(initiative_tracking[key]))


Python has a standardized style guide called PEP 8. There is also Google's Python style guide which AFAIK is very similar to PEP 8.

Any code that goes largely against PEP 8 normally doesn't look Pythonic.

Python has a naming scheme to allow developers to know the variables type by it's name only.

Classes are in CamelCase,
Functions, methods and variables are in snake_case, and
Constants are in UPPER_SNAKE_CASE.

There should be a single space after commas.
Lines should be limited to 79 characters.
There should be one space between all methods, and two between top level classes and functions.

Overall your code adheres to these standards pretty well. Good job.
class Agent(object) is a relic from Python 2. In Python 2 classes didn't inherit from object by default. These are now called old style classes. However in Python 3 everything inherits from object by default - making all classes in Python 3 new style classes.
Your code would benefit from another class.

I'm reluctant to suggest this as the code has an over-reliance on global variables. In the future you should try to solve the problem without globals and then see if it can be made cleaner by using a class.

And so we can make a Simulation class. I would include all the global functions you have in it except initialize.
I would use an if __name__ == "__main__": guard to prevent your code from running if it's been imported accidentally.

This gets the following. There's some more changes that can be made, but the base of your code is good.

class Agent:
    def __init__(self, identification, productivity, wealth, preferences, age, health, alive, sex):
        self.identification = identification
        self.productivity = productivity
        self.wealth = wealth
        self.preferences = preferences
        self.age = age
        self.health = health
        self.alive = alive
        self.sex = sex

    def description(self):
        print("My id is", self.identification)
        print("My age is", self.age)

class Simulation:
    def __init__(self):
        self.alive = []
        self.dead = []
        self._id = 0
        self.year = 0

    def create_agent(self):
        self.alive.append(Agent(self._id, 100, 20, "blue", 30, 0, True, True))
        self._id += 1

    def deaths(self):
        for agent in self.alive.copy():
            if agent.age > 30:
                agent.alive = False
                print("Death of", agent.identification)
                self.dead.append(agent)
                self.alive.remove(agent)

    def time_skip(self):
        print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
        self.year += 1
        print("The new year is", self.year)
        for agent in self.alive:
            agent.age += 1
        self.create_agent()
        self.deaths()

if __name__ == '__main__':
    simulation = Simulation()
    for _ in range(3):
        simulation.create_agent()

    # Testing
    for agent in simulation.alive:
        agent.description()

    simulation.time_skip()

    for agent in simulation.alive:
        agent.description()


Update pass-through query from a form (an alternative to stored procedures)

The first thing I would suggest is to avoid as much as possible depending on the DoCmd object. The DoCmd object is essentially replicating the actual user action as if you had clicked on a button via the UI, with all the dialogs, etc. that comes with it.

For the purpose of executing a SQL, I recommend that you use the Database.Execute method, remembering to use dbFailOnError flag and very likely dbSeeChanges if your Oracle tables uses something equivalent to auto-increment for its primary key. So instead of

DoCmd.Close acQuery, "sptROAD_INSP"
DoCmd.OpenQuery strSPTName

You should want to do something like this:

CurrentDb.Execute strSPTName, dbFailOnError Or dbSeeChanges

This does essentially the same thing but without all the extraneous UI baggages that the DoCmd brings to the table. It will NOT prompt you to confirm if you want to make changes, and does NOT require you to use DoCmd.SetWarnings to suppress the unwanted UI messages associated with OpenQuery or RunSQL methods which are member of the DoCmd object.

However, Execute method is only appropriate when it's in fact a statement that is not intended to return results. If you expect results (e.g. the qdf.ReturnRecords is set to true), you would use OpenRecordset method. Therefore, you could revise your function so that it does this (untested aircode):

If qdf.ReturnRecords Then
  Set Results = qdf.OpenRecordset(dbOpenDynaset, dbSeeChanges)
Else
  qdf.Execute dbFailOnError Or dbSeeChanges
End If

assuming that you have a variable named Results that is a `DAO.Recordset type.

Next, you are writing SQL raw. Unfortunately, a passthrough query cannot be properly parameterized. For best protection against SQL injection, you might want to consider using ADO instead of DAO, and if possible use OLEDB provider for Oracle (note that there are multiple providers, some by Oracle themselves, other by Microsoft - I can't say which is better; experimenting is needed). Note that you are not restricted to using ADO exclusively; you can use ADO in VBA code and DAO for Access form binding.

If for some reasons you cannot use ADO and must use DAO, then you should at least consider writing functions to prepare the parameters so that all strings are properly delimited, and that empty values in a textbox will result in a NULL or maybe '', depending on your needs.


Is the solution design optimal? C# 3 - Tier

Data Acess Layer does not create domain objects. It just pass database record wrapped in another simple object (DataEntities.AccountRow). Is it a good/standard approach?

Repository classes should create domain objects. The domain objects may or may not look the same as the DB entities.

If you mean that you write your DAL by yourself (and not using a ORM): Stop with that. It's a waste of time.

  Manager and domain objects are in two different layers. Is it okay?

Use the term WCF service and not manager. Yes. I consider WCF services to be an UI layer since it's the interface to the calling user/client.

  A layer “DTOforServiceCommunication” is created for communicating with WCF service.

The name doesn't matter as long as you understand the difference between a domain object and a DTO.

  Is DTOforServiceCommunication and DataEntities are redundant or a good practice?

Good practice. The DTO's should never change since it would break all clients that use them.

  What are the improvement points for this solution structure?

No need for a userId in the WCF interfaces or the DTOs unless you want to let everyone be able to look at everybody elses accounts. Use the userid provided during authentication.

Update

Repository class using vanilla ADO.NET:

public class AccountRepository
{
    Dictionary<string, Type> _accountClasses = new Dictionary<string, Type>{{"savings", typeof(SavingsAccount)}, {"fixed", typeof(FixedAccount)}};
    List<DataEntities.AccountRow> dbRecords = new List<DataEntities.AccountRow>()
    {
        new DataEntities.AccountRow{AccountNumber=1,AccountType="Savings",Duration=6,DepositedAmount=50000},
        new DataEntities.AccountRow{AccountNumber=2,AccountType="Fixed",Duration=6,DepositedAmount=50000}
    };

    public T Get<T>(int userID, int accountNumber) where T : Account
    {
        var sql = "blabla";
        using (var cmd = _connection.CreateCommand())
        {
            cmd.CommandText = sql;
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                    return null;

                var account = CreateRow(reader);
                if (account.GetType() != typeof(T));
                    throw new InvalidOperationException("The requested account was not of the specified type");

                return account;
            }
        }
    }

    public IEnumerable<Account> FindMyAccounts(int userId)
    {
        var sql = "blabla";
        using (var cmd = _connection.CreateCommand())
        {
            cmd.CommandText = sql;
            using (var reader = cmd.ExecuteReader())
            {
                List<Account> accounts = new List<Account>();
                while (reader.Read())
                {
                    var account = CreateRow(reader);
                    accounts.Add(account);
                }

                return accounts;
            }
        }
    }

    // IDataRecord = a row in a DataReader
    public Account CreateRow(IDataRecord record)
    {
        // might want to check so that the account got a
        Type type;
        if (!_accountClasses.TryGetValue(record["AccountType"], out type))
            throw new InvalidOperationExcpetion("Account type do not exist: " + record["AccountType"]);

        var account = (Account)Activator.CreateInstance(record);

        // fill record here
    }

}

public class Account
{
}

public class SavingsAccount : Account
{
}

public class FixedAccount : Account
{
}

Usage:

account = _repository.Get<SavingsAccount>(1, "kdkdkdkdkd");

Update2

Added a Find method to show that the actual mapping is reused by all methods.

The Find method will also return different types of accounts in the same list.

You could also break out the ExecuteReader parts into two methods (one to fetch one item and one to fetch collections) to reuse the code more.


C++ interview problem: finding an Island in a 2D grid

Don't use using namespace std

It's considered bad practice.

Don't define AND

There is already and as an alternative to &&.

Use std::vector instead of new[]

You have a memory leak at the moment, since you forgot to delete[] the allocated memory. std::vector prevents this kind of error.

Use appropriate data structures

You use an array of unordered_set<int>s where a std::unordered_set< std::pair<int,int> > would be sufficient. Also, clear() isn't necessary. Unless your std::unordered_set implementation is broken, a std::unordered_set starts out empty.

Consider const for variables that shouldn't change

dx, dy, n and m should never change. const makes sure that you don't change them by accident.

Always use braces around blocks

No braces after control structures have led to several bugs that were hard to catch. Always use them. That way you cannot accidentally forget to place them when necessary.


Math calculation refactoring in JavaScript

Strictly in terms of code readability, you want to break down a function like this into it's core parts. Additionally, to reduce repetitive behavior you could make it more of a prototype and use some object oriented style to get to your result without a block of math.

Things to Consider

Law of Demeter -
Passing into your function only what you need and not entire objects.
Breaking your function into segments, why not use methods to
systematically get to your answer? Easily readable/maintainable.
Reduce the amount of variable creation, you dont need to set each
value to a new variable when one is already passed in from the
function arguments. Law of Demeter helps here, too.
Keeping your code expandable.

Here's an example of a function that follows the three above rules, a simple example that leaves you to put in your mathematics.

Example

var measure = function(elementHeight, elementPositionTop, bubbleHeight) {
    var remaining = 0, progress = 0, distance = 0;

    return {
        init: function() {
            measure.buildRemaining();
            measure.buildProgress();
            measure.buildDistance();
        },
        buildRemaining: function() {
            remaining = elementHeight * bubbleHeight;
        },
        buildProgress: function() {
            progress = remaining / 2.5;
        },
        buildDistance: function() {
            distance = (elementPositionTop - progress) + remaining;
        },
        result: function() {
            measure.init();
            return {
                remaining: remaining,
                progress: progress,
                distance: distance
            }
        }
    }
}($element.height(), $element.position().top, $bubble.height());

Accessing the Function

measure.result();

Returns

Object { remaining=5850, progress=2340, distance=3582 }


Determining the region from several sources of information

Since you are not actually using a dictionary I find anonymous tuples would be much more readable here. Consider this where you don't even need a List<T> but just a simple array:

var weights = new (int RegionId, int Importance)[]
{
  (regionIdByIp, 5),
  (regionIdByPhone, 3),
  (regionIdByInput, 4)
};

Where you define such a tuple as (int RegionId, int Importance). With it the next query (also written with line breaks) would be much easier to understand.

int mostImportantRegionId =
    weights
        .Where(x => x.RegionId > 0)
        .GroupBy(kvp => kvp.RegionId)
        .OrderByDescending(x => x.Sum(y => y.Importance))
        .Select(x => x.RegionId)
        .FirstOrDefault();

I also think that x.Key != default(int) is a strage condition. If Key is an id then it probably should be greater than 0 so it's better to write x.RegionId > 0 instead.

What you also can do better is the await part. Currently you wait for each task to finish one-by-one. Let's them work in parallel with WaitAll:

var regionIdByIpTask = GetRegionIdByKeywordAsync(regionByIpStr);
var regionIdByPhoneTask = GetRegionIdByKeywordAsync(regionByPhoneStr);
var regionIdByInputTask = GetRegionIdByKeywordAsync(regionByInputStr);

Task.WaitAll(new []
{
    regionIdByIpTask,
    regionIdByPhoneTask,
    regionIdByInputTask
};

Now you can build your weights:

var weights = new (int RegionId, int Importance)[]
{
  (regionIdByIpTask.Result, 5),
  (regionIdByPhoneTask.Result, 3),
  (regionIdByInputTask.Result, 4)
};


Shouldn't get id twice

I'm concerned with this code:

        persistCounter( user_id, sequence.incrementAndGet());
        return sequence.get();

After you atomically increment and get the counter, you call sequence.get() again.  That seems wrong because what happens if some other thread incremented the counter in the meantime?  I think your code should be:

        int newId = sequence.incrementAndGet();
        persistCounter(user_id, newId);
        return newId;

Repeated code

Also, I noticed that the same block of code (the one above) appears three times in a row:

    public static int getNextValue( String user_id){
        if( sequence.get() == 0){//first time we run it or it has been restarted
            l = ofy().load().type(PersistSequence.class).
                    filter("user_id", user_id).limit(1).list();
            if( l != null){
                int dataStoreSeq = -1;
                if ( l.size() > 0) dataStoreSeq = l.get(0).getLastId();
                if ( dataStoreSeq > sequence.get()) sequence.set( dataStoreSeq);
                persistCounter( user_id, sequence.incrementAndGet());
                return sequence.get();
            }else{
                persistCounter( user_id, sequence.incrementAndGet());
                return sequence.get();
            }
        }else{
            persistCounter( user_id, sequence.incrementAndGet());
            return sequence.get();
        }
    }

Since that code happens for every case, you can simplify your function by extracting that common code and placing it right before the function returns:

    public static int getNextValue( String user_id){
        if( sequence.get() == 0){//first time we run it or it has been restarted
            l = ofy().load().type(PersistSequence.class).
                    filter("user_id", user_id).limit(1).list();
            if( l != null){
                int dataStoreSeq = -1;
                if ( l.size() > 0) dataStoreSeq = l.get(0).getLastId();
                if ( dataStoreSeq > sequence.get()) sequence.set( dataStoreSeq);
            }
        }
        int newId = sequence.incrementAndGet();
        persistCounter(user_id, newId);
        return newId;
    }

Concurrency issues in persistCounter()

It's possible that persistCounter() will get called with out of order lastId arguments.  For example, it's possible that you might get called with lastId of 5 and then later get called with a lastId of 4.  So I think before you save the new counter, you should compare it with the old one to make sure that are actually saving a newer counter.

Also, there may be a concurrency problem with this function.  What happens if one thread tries to save 4 and another tries to save 5 at the same time?  Could it possibly end up saving 4 instead of 5?


Printing doubles using string manipulation

number_to_sci_string looks ok, though you could considerably improve performance by chucking the template, restricting to float, double and long double and using snprintf:

std::string number_to_sci_string(long double number, int precision) {
    std::string s(std::snprintf(0, 0, "%.*Le", precision-1, number), '\0');
    std::snprintf(&s[0], s.size()+1, "%.*Le", precision-1, number);
    return s;
}

Also, I really wonder why you are using a different notion of precision than the standard library...
I suggest you be a bit more flexible in what you accept:

The exponent e00 should be optional.
The fractional part (and decimal point) .00 should be optional.
If there's a fractional part, the integer part should be optional.

Don't use using namespace std;, even in the implementation-file: You don't control what symbols it contains, and there are no guarantees none are added.
The opening brace of main()'s body is, in contrast to all other functions, on a separate line. Why?
Prefer the for-range-loop to std::for_each+lambda. The compiler should compile both to the same result, but the former is simpler and looks better.


Parallelizing an algorithm with OpenMP using a dynamic work queue

Firstly, I know you said you're not so interested in a style review, but:

using namespace std;

Apart from being harmful, this isn't even bringing any benefit.  We can just drop it with no changes to the rest of the code.

And if OpenMP is correctly installed, the header should be on the include path (not in your source code location):

#include <omp.h>

The only thing we use from <omp.h> is omp_get_num_threads(); we can avoid needing that if we change the sense of the numWaiting variable, so we get to compare against zero instead:

    unsigned int num_working = 0;

#pragma omp parallel
{
#pragma omp single
    ++num_working;

    while (true) {
        std::unique_lock<std::mutex> lock(m);

        if (workStack.empty()) {
            --num_working;

            if (num_working == 0) {
                cv.notify_all();
                break;
            }

            while (true) {
                cv.wait(lock);
                if (num_working == 0 || !workStack.empty()) break;
            }

            if (num_working == 0) break;

            ++num_working;
        }

Instead of the #pragma omp single, we could make num_working be a std::atomic<unsigned> instead.

When we add two items to the work queue, we only wake up one worker thread.  We need to wake up a thread for each child, potentially:

        workStack.push(childA);
        cv.notify_one();
        workStack.push(childB);
        cv.notify_one();

Possibly a style issue, but the while (true) loop looks better as a do ... while:

            do {
                cv.wait(lock);
            } while (num_working > 0 && workStack.empty());


There's an unmatched ( in the declaration of the contents of story.  I recommend that you actually test the DTD using a validating parser such as OpenSP before posting code for review.

6.1 is not satisfied: you have declared content for story but no attributes.

6.2-6.4 are not satisfied: the url, title and preview elements must each appear exactly once.

6.6.1 is not satisfied: you only allow content before video and not video before content.

7.1 is not satisfied, because title has been declared as an empty element.


Implementing a linked list as practice for a coding interview

Names

package LinkedList

By Java's naming convention, package names are in lowercase and follows a 'reversed Internet domain name' prefix. Therefore, LinkedList is not a good package name, but something like com.antarkar.amough may be more suitable.

public class LinkedList

It is usually not recommended to use class names that conflict with those from the standard API, as it may cause confusion at best and compilation errors at worst. Since you are indeed doing a linked list implementation, I don't suppose there's a simpler way around this, just bear this in mind in the future for 'production level code'...

Separation of concerns

The biggest issue about this class, going by 'production level code' and 'coding interview' standards, is that you are mixing I/O operations (i.e. user input and display) with the data structure implementation. These two should stay separate for two simple reasons, if I may classify them under the standards you requested:

Production level code

When codes get into 'production' (depending on your definition), you'll want it to do one thing, do it well, and do it in as minimal as possible. If it's a data structure, it shouldn't know how to interact with System.in and System.out. If logging is required, it will use a (preferably widely-adopted and well-tested) logging framework to do so. Lesser lines of code tend to result in less programming bugs introduced. Lesser instructions (at the JVM level) also translate to more efficient memory usage, too.
Coding interview

Intertwining two unrelated features into a single class may indicate a lack of understanding of OOP concepts. What happens if a GUI-based demonstration is required? Also, how will you unit test your code when the class is interfacing directing with System.in and System.out, when it should be done through proper method arguments and (possibly) String outputs?

I'll recommending browsing through the number of linked list implementations in Java we have here on CR, to compare-and-contrast your implementations with the rest.

Modern code

Without even going into Java 8 features, features like try-with-resources should already be adopted around your Scanner so that you do not need an explicit call to close() at the end. Java 7 already has generic type inference aka the 'diamond operator', so you can remove the unnecessary types. Hashtable is a legacy class that is retrofitted to become part of the Collections framework, so you really ought to be using HashMap.

All these pointers matter if this is for a coding interview, as you'll want to show that you are reasonably kept up to date with the newer developments in your programming language of choice.


How to make my code shorter. This Code formats Credit card number. Vanilla JS

I've mainly got three points:

The whole thing should be wrapped in a function with the reference to the input element passed in. Currently it is hard coded to (only) apply to the first input on the page, which doesn't seem like a practical scenerio.

Instead of using the deprecated/non-standard keyCode and which, you should be using key. And if you do use keyCode you should define all code numbers as constants.

Unless I'm missing some side-effect, the use of parseInt on inpVal.length is pointless.


Evaluate joint probability density function of a Markov random field

A first go at the problem:

Generating the states

Since you are generating all possible bit patterns with a given number of bits, it's wasteful to first create a binary representation as a string, and then convert it back to integers digit by digit. As often itertools can help you here. Especially itertools.product. Your use case is basically one of the examples given in its documentation.

from itertools import product

def generate_all_possible_states(size):
    states = np.empty((2**size, size))
    for i, value in enumerate(product((0, 1), repeat=size)):
        states[i, :] = value
    return states

The reimplementation also avoids the dynamically growing list and allocates a numpy array of appropriate size beforehand.

Moving repeated computations

You are calculating exp for every single scalar that you put in density_func. That is wasteful since it does not allow numpy to play its strengths, namely applying the same operation to a lot of values aka vectorization. Fortunately, there is an easy way out (ot the loop ;-)) and you can just compute np.exp on the whole density_func vector.

The first part of the sum can also be easily moved out of the loop.

density_func = np.empty(2**size)
for i in range(2**size):
    density_func[i] = np.dot(np.dot(states[i], J), states[i])

density_func += np.dot(states, b)
density_func = np.exp(density_func)
# maybe a teeny-tiny bit faster:
# density_func = np.exp(density_func + np.dot(states, b))

The order of operation matters here. Intializing density_func to np.dot(states, b) and then adding the results in the loop like density_func[i]  += np.dot(np.dot(states[i], J), states[i]) is consistently slower.

Preliminary timing

As an example, for size = 18, your original implementation takes about \$5.5s\$ here on my machine. With just the two modifications above, you can get down to \$1.9s\$ (both with the same fixed seed for the random numbers).

size = 20: \$23.4s\$ vs. \$8.0s\$
size = 21: \$47.9s\$ vs. \$16.4s\$

Maybe I will have time to revisit this later on this week to update the answer with a proper analysis on how both of them scale for larger sizes. My strong intuition at this point would be that they both have a complexity of \$\mathcal{O}(2^n)\$ and the difference between them will actually remain a constant factor (\$\approx 3\times\$ faster).

Things that didn't work (so far)

Things that I tried, that didn't work for me:

Eliminating the magic of np.dot and explicitely using np.inner or np.matmul / @ (in Python 3). np.dot seems to have some tricks up its sleeves and is still faster. Maybe I will have to read the doc more carefully.
Trying to compute the second part of the sum in a vectorized manner. I'm a little bit too tired at the moment to come up with a clever solution to this.


File Output given repeated small operations

Measuring is good, but it will only tell you what those data will result in, so you will need to reason on the code too and then measure that it isn't totally wrong.

The reason to change the code is the suspicion that the repeated calls to file output would be a large overhead.

// ToDo: add sanity checks.

string Duplicate(string org, size_t maxSize) {
  string dup;
  dup.reserve(org.length() * maxSize);
  for (auto i = 0; i < maxSize; ++i)
    dup.append(org);

  return dup; // hope for NVRO
}

string Ones = "1\n";
size_t numLens = Ones.length();
string Ones = Duplicate(Ones, MaxNumberOfRepeats);
string Zeroes = Duplicate("0\n", MaxNumberOfRepeats);

Usage, dups is the number of duplicates

inline void Writer(string text, size_t dups) {
  file << text.substr(0, dups*numLens); // potentially makes a copy
}

There is a method using char[] which doesn't make any copy. (not shown)

 double value = (0.5 + (-0.5 * (deltaY / cellToY)));

Saving on the math operations as '/' is expensive and '-0.5 *' also is a constant that might as well be calculated outside the loop.
WARNING this may result in some subtle differences in final values due to float pointiness.

Outside the loop or if cellToY is a global const make it a constexpr

constexpr double invCellToY = -0.5 / cellToY;

This leaves

double value = (0.5 + ( (deltaY * invCellToY)));

Saving a divide.

The ifs are a problem

            if (deltaY < -cellToY) {
                file << "1\n";
            }
            else if (deltaY > cellToY) {
                file << "0\n";

If they are true at a near random occurrence you have a serious performance problem. If they come in streaks you can do something like this

double deltaY = yProfileHeight[x] - yPos;
if (deltaY < -cellToY) {
    int count = 1;
    while (++x < xcells) {
        deltaY = yProfileHeight[x] - yPos;
        if (!(deltaY < -cellToY))
            break;

        ++count;
    }
    Writer(Ones, count);
} else
    ...

This guarantees one mispredict for the while so this might be a loss if they don't come in streaks. (branch prediction is somewhat dependend on global branch history so some of the lost might be redeemed again as the next x itereation should have an increased probability of predict the first if not taken after the loop exit).

This would also mean that the original code would get lots of mispredicts, you could try this

// these bool calculations should be branchless
bool LT = (deltaY < -cellToY);
bool GT = (deltaY > cellToY);
// ??? LT and GT are mutual exclusive
bool LTGT = LT | GT;

if (LTGT)
    res = LT?Ones:Zeroes;
else
    // very costly operation of turning double to string ...
    // should the result be 0 or 1 also?
    res = string(0.5 + ( (deltaY * invCellToY)))+"\n";

fill << res;

as in some cases (trinaries) some compilers (gcc+?) can find out to generate conditional moves.

But my guess would be the while implementation would be faster as the domain suggest some form of streaks. Merge your final decision with this code.

string res;
for (int y = 0; y < ycells; y++) {
    double yPos = yMin + (cellToY * (y + 0.5));
    if (yPos < yHeightMin)  {
        Writer(Zeroes, xcells);
    }
    else if (yPos > yHeightMax) {
        Writer(Ones, xcells);
    } else {
        for (int x=0; x<xcells; x++) {
            double deltaY = yProfileHeight[x] - yPos;

            // exchange this with the wanted code
            if (deltaY < -cellToY) {
                file << "1\n";
            }
            else if (deltaY > cellToY) {
                file << "0\n";
            } else {
                double value = (0.5 + ( (deltaY * invCellToY)));
                file << value << "\n";
            }
        }
    }
}


Just a note about the tests: I'd create a test method for every assert call. For example,

  def test_StackWithTwoElements
    stack = [2, 1]
    sorted_stack = [1, 2]
    assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with two elements: 1, 2 failed")
    stack = [2, "a"]
    assert_raise (ArgumentError) { @sorter.sort(stack) }
  end

would be

  def test_StackWithTwoElements
    stack = [2, 1]
    sorted_stack = [1, 2]
    assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with two elements: 1, 2 failed")
  end

  def test_StackWithInvalidElement
    stack = [2, "a"]
    assert_raise (ArgumentError) { @sorter.sort(stack) }
  end

Too many asserts in one test is a bad smell. It's Assertion Roulette and you lost Defect Localization. If the first  assert_equal throws an exception you don't know anything about the results of the other assert calls which could be important because they could help debugging and defect localization.


Deleting ranges of rows from a spreadsheet

Instead of looping through every single line and then deleting it if it matches your criteria, you could build a string that contains the exact ranges you want to delete.  Then once the loop is complete you could call a single Range().Delete call.  You also can make the macro take in a string that you wish to delete.

Sub MacroDelete(S As String)

Dim i As Long
Dim LR As Long

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

LR = Cells(Rows.Count, 1).End(xlUp).Row

Dim RangeToDelete As String
Dim Count As Integer
Dim numRowsToDelete As Integer

RangeToDelete = ""
Count = 0

' cheap way to get the total amount we want to delete
numRowsToDelete = Application.WorksheetFunction.CountIf(Range("E:E"), S) - Application.WorksheetFunction.CountIf(Range("E1:E2"), S)

For i = LR To 2 Step -1

' build the range string
If Range("E" & i) = S Then
    Count = Count + 1
    RangeToDelete = RangeToDelete & i & ":" & i
    If Count < numRowsToDelete Then
        RangeToDelete = RangeToDelete & ","
    End If
End If

Next i

' delete all the rows found matching S
Range(RangeToDelete).Delete Shift:=xlUp

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

You can see @D_Zab's answer for an understanding on how to call subs or functions from other subs


Redundant check

If xiExistingRangeStart is greater than xiExistingRangeEnd, then you only have to verify that xiExistingRangeStart is not greater than zero to know that xiExistingRangeEnd can't be.

Parameters + Error messages

I would prefer your exception messages to be more explicit.   Rather than:

  "The SMALLER value MUST be provided first. Note that since values are negative, this first value will have the larger ABSOLUTE value!"); }

I think it would be better to refer to 'Start' rather than 'first' value.  This may seem pedantic but consistency between the error name and the parameter name make it easier to resolve issues.

Similarly, when I think of negative numbers, I tend to think of numbers < 0, not <= zero which seems to be what your code suggests.  So again, I'd tend to be more explicit.


Your implementation seems fine at a glance, but Python actually provides two really easy ways to do this:

string.format
bin

Your function would then become:
def integer_to_binary_string(int_value):
    '''Converts integer to a string of base-2 bits,

    example: 20 becomes '10100'

    '''
    return f"{int_value:b}"
    # or
    # return bin(int_value)[2:]

The advantages of this are numerous:

Obvious what is happening & idiomatic Python
Doesn't require someone to understand the math behind it
Way faster (timeit with 1,000,000 iterations clocks at 0.23s for my method, 1.82s for yours)

Now to actually review your code (the reinventing-the-wheel tag was added after I started writing this):

Generally, I prefer list comprehensions over an explicit loop; they're often faster
Creating a function called reverse_string is unnecessary - the idiomatic/Pythonic way to do this is using the slice notation you mentioned - hiding it behind a method is just going to confuse experienced Python users.
Repeatedly appending to strings/lists/things is generally not the best from a performance perspective (this has to do with how memory is allocated). Instead, use str.join, as it will do better from a memory allocation perspective

What I would end up with looks like this:
def integer_to_binary_string2(int_value):
    """Converts integer to a string of base-2 bits,

    example: 20 becomes '10100'

    """
    if int_value == 0:
        return "0"
    bin_digits = floor(log2(int_value)) + 1
    return "".join([
        str(int_value // 2 ** i % 2)
        for i in range(bin_digits)
    ])[::-1]

You can use a generator comprehension instead of a list comprehension, but as pointed out by @Graipher in the comments, in CPython str.join turns arbitrary iterables into lists as the very first step, negating any potential benefits. Generally speaking I prefer generator comprehensions to list comprehensions because they can be more memory efficient & are lazily evaluated, but they add no benefit here.


Matrix struct with random values allocation and deallocation

Improve your error reporting:

Your detectError function is not very useful. The name is also not good. It doesn't "detect errors", but rather it detects an out-of-memory condition if called after malloc.

int detectError(void *ptr) {
     if (ptr == NULL)
    {
            printf("operation failed\n");
            printf("%s\n", strerror(errno));
            return ERROR;
    }
    return SUCCESS;
}

If malloc fails, there is only one possible reason, it can't allocate any more memory. On a POSIX implementation if that happens malloc will set errno to ENOMEM. So by calling strerror you are just inventing a very complicated way of printing "out-of-memory" to stdout. Your code would be simpler and more idiomatic if instead of calling detectError you would just check the return of malloc for NULL:

matrix->values = malloc(n * sizeof(int*));
if (matrix->values == NULL) {
    fprintf(stderr, "Out-of-memory");
    return ERROR;
}

Also note that on some implementations malloc might not set errno at all or set it to EAGAIN, which would print an unclear or wrong message if using errno with strerror.

Still looking at the error reporting, it is more conventional to print error messages to stderr, so that users can filter normal program output from errors more easily.

Use booleans whenever possible instead of error codes:

#define ERROR -1
#define SUCCESS 0

I would not define those constants and instead use bool. If there are only two possible outcomes, success or failure, then just returning true or false is simpler and avoids confusion. It is very common for libraries to mix the use of integers as booleans and as error codes, which complicates things and leads to error if you misinterpret a return value. Keep it simple.

Awkward pointer manipulation:

From getMatrixProps, which already takes matrix by pointer:

return allocateMatrix(&(*matrix), n, m);

That dereference followed by taking the address is nonsensical. Pass it directly as is.

Allocate a flat array:

Lastly, you could simplify a lot if you'd allocate the whole matrix as a sequential memory block. Instead of having to call a malloc per column, you can allocate a flat array of columns.

Since we are dealing with a 2D matrix, in the following example I'll call
the columns width and rows height, using x and y as the respective indexes.

typedef struct {
    int width;
    int height;
    int * values;
} Matrix;

bool allocMatrix(Matrix * mat, int width, int height)
{
    // The total number of elements in the matrix is
    // the number of columns times the number of rows
    //
    mat->values = malloc(width * height * sizeof(int));
    if (mat->values == NULL) {
        fprintf(stderr, "Out-of-memory");
        return false;
    }

    mat->width  = width;
    mat->height = height;
    return true;
}

//
// To access a given 2D index, now that the matrix is flat, you'll need to
// calculate the proper offsets with the formula: 'x + y * width'
//
// To simplify element access, I suggest defining a couple helper functions:
//

int getMatrixElement(const Matrix * mat, int x, int y)
{
    return mat->values[x + (y * mat->width)];
}

void setMatrixElement(Matrix * mat, int x, int y, int value)
{
    mat->values[x + (y * mat->width)] = value;
}


Kth to last element of a singly linked list

Your code is neat, and, within the confines of the "Solution", you have solved things well.

The algorithm you use is the right one, it's implemented well, and it's all clear. I like it.

There's only one thing that concerns me. The interface of the Node class:

The value of the node should be final (not just private).
The Node class itself should be private, and should not be passed in to the findKthToLast method (it should be accessed as the private field it is)
the return value of the findKthToLast should be the node's value, not the node itself.

There are all concerns that are about the implementation environment, not just the implementation itself. The Solution concept may be the issue.

So, taking that all in to consideration, your solution, given the constraints, is a good one, but the Solution environment and requirements themselves may be the worst of the problems.


Did I make it unnecessarily complicated?

You can replace
find:
  scasb
  jz    found
  loop  find
  jmp   next

by the simpler
  repne scasb
  jne   next

The use of the SCASB instruction here depends on the direction flag DF being in the clear state (CLD). It is a safe assumption that this will be the case. Nonethesless prudent programmers will at least at program start include one CLD instruction.
If ever you find that you need to reverse the direction for the string primitives by the use of STD, you should always issue a restoring CLD as soon as possible (once the string operation has finished). Why is this? Well, just as you can expect the direction flag to be clear, any library functions that your program invokes expect the same thing. During normal program execution DF=0 is almost true 100% of the time. See.

No need to use the extra register EDI in:
mov   edi, ebx
inc   ebx
mov   [d + edi], al

Just write:
mov   [d + ebx], al
inc   ebx

The digits have well-known ASCII codes. Finding a digit is just a matter of comparing AL with the range 48 to 57. I find scanning that digits string a bit overkill, although at times that could be a good way. When the character codes aren't contiguous.
  mov   ecx, len
  jecxz end_prog
  xor   esi, esi
  xor   ebx, ebx
repeat_this:
  mov   al, [s + esi]
  cmp   al, '0'
  jb    next
  cmp   al, '9'
  ja    next
  mov   [d + ebx], al
  inc   ebx
next:
  inc   esi
  loop  repeat_this

Clearing a register is best done using XOR <reg>,<reg>.

This shorter version uses the string primitives and avoids using the slow LOOP instruction:
    mov   ecx, len
    mov   esi, s
    mov   edi, d
    jmp   next
  repeat_this:
    lodsb
    cmp   al, '0'
    jb    next
    cmp   al, '9'
    ja    next
    stosb
  next:
    sub   ecx, 1
    jnb   repeat_this


Accessing environment variables in jq

This doesn't really work as it is...:

RESOURCE_NAME="example.com"
# ...

cat resource-changes.json | \
jq '.Changes[].ResourceRecordSet.Name=env.RESOURCE_NAME' | \
# ...

jq cannot access RESOURCE_NAME if it's not exported.
The fix is simple:

export RESOURCE_NAME="example.com"

Iterating over a list of values

This is a very hacky way to iterate over a list of hosts:

RESOURCE_HOSTS="1.1.1.1,2.2.2.2,"

# ...

for host in $(echo "$RESOURCE_HOSTS" | tr "," "\n"); do

If the host names will never contain space,
you could use a simple space-separated string:

RESOURCE_HOSTS="1.1.1.1 2.2.2.2"

# ...

for host in $RESOURCE_HOSTS; do

Or for maximum flexibility you could use a proper Bash array:

RESOURCE_HOSTS=(1.1.1.1 2.2.2.2)

# ...

for host in "${RESOURCE_HOSTS[@]}"; do

Streamlining by eliminating the loop

The current script creates many temporary files in the process,
which is very ugly.
The biggest obstacle to streamlining this into a single nice pipeline is the looping logic.
You could prepare the host values into a JSON list and let jq take care of the rest.

Here's one way to create a JSON list from an array of hosts:

hosts=(1.1.1.1 2.2.2.2)

values="\"${hosts[0]}\""
for host in "${hosts[@]:1}"; do
    values="$values,\"$host\""
done

This assumes that there is at least one host.
It initializes values with the first one,
and then appends the others with a comma,
adding double-quotes to make it valid JSON.

With this new variable,
you can chain the jq calls like this:

cat resource-changes.json | \
jq '.Changes[].ResourceRecordSet.Name=env.RESOURCE_NAME' | \
jq 'del(.Changes[].ResourceRecordSet.ResourceRecords[])' | \
jq ".Changes[].ResourceRecordSet.ResourceRecords = ([$values] | map({\"Value\":.}))"

The cat command at the front is a bit ugly, because the filename could be a parameter of the first jq call, or replaced with an input redirection.
But that would break the current nice aesthetic flow of the jq calls.
This minor issue could be fixed by grouping and input redirection:

{
jq '.Changes[].ResourceRecordSet.Name=env.RESOURCE_NAME' | \
jq 'del(.Changes[].ResourceRecordSet.ResourceRecords[])' | \
jq ".Changes[].ResourceRecordSet.ResourceRecords = ([$values] | map({\"Value\":.}))"
} < resource-changes.json


Find the minimum number of characters to add to make password strong

Code length is one factor in readability, but it isn't the only factor. "Is this code easy to read and modify" is a more important question to ask.

It looks like you've gotten a method skeleton here, which kind of leads you down the path of stuffing everything in one function, which is a bit of a shame. Let's look at what we actually need here.

Length of at least 6
One lowercase English character
One uppercase English character
One digit
One special character

What if we split this up into a bunch of separate functions, which each do one thing. We'll just write the function names down for now, and leave the implementation blank.

def lower_required(text):
    pass

def upper_required(text):
    pass

def digits_required(text):
    pass

def length_required(text):
    pass

def special_required(text):
    pass

Now, Python has a string module that is (semi)deprecated (much of what was in it is now on string objects themselves), but that has some still useful things, namely, string.ascii_lowercase, string.ascii_uppercase, and string.digit. We can use these in the implementations for some of our functions. Let's just write them as simply as possible for now.

import string

def lower_required(text):
    for char in text:
        if char in string.ascii_lowercase:
            return 0
    return 1

def upper_required(text):
    for char in text:
        if char in string.ascii_uppercase:
            return 0
    return 1

def digit_required(text):
    for char in text:
        if char in string.digits:
            return 0
    return 1

There's quite a bit of repetition here that we can factor out.

def num_required(text, characters):
    if any((x in characters for x in text)):
        return 0
    return 1

Then our previous functions can just call this:

def lower_required(text):
    return num_required(text, string.ascii_lowercase)

And similarly for the upper_required and digit_required.

In fact, we can do this with our special characters as well:

SPECIAL_CHARS = '!@#$%^&*()-+'

def special_required(text):
    return num_required(text, SPECIAL_CHARS)

The last function we need to implement is length_required:

MINIMUM_LENGTH = 6

def length_required(text):
    if len(text) >= MINIMUM_LENGTH:
        return 0
    return MINIMUM_LENGTH - len(text)

Now we can stitch these all together within minimumNumber (note that Python functions should be named using snake_case, so it should be minimum_number here - but I assume this function name was given to you, so I won't harp on about it too much).

def minimumNumber(text):
    test_functions = [lower_required, upper_required,
                      digits_required, special_required]
    min_chars_required = sum([test_fn(text) for test_fn in test_functions])
    missing_length = length_required(text)
    if missing_length > min_chars_required:
        return missing_length
    return min_chars_required

The benefit of doing this is the fact that we can easily add extra checks. What if a new requirement comes along? We can just create a new function an add it to test_functions; the amount of existing code we have to touch is minimal.

Just to drive home the point about size vs readability, here is a (slightly) code golfed version:

import string

def minimumRequired(password):
    if len(password) < 6:
        return 6 - len(password)
    unique_pw = frozenset(password)
    char_sets = (frozenset(string.ascii_lowercase), frozenset(string.ascii_uppercase),
                 frozenset(string.digits), frozenset('!@#$%^&*()-+'))
    required_extra = 0
    for char_set in char_sets:
        if not char_set & unique_pw:
            required_extra += 1
    return required_extra

This (probably - I haven't really tested it) satisfies the requirements, but how do I make changes to it? Is it obvious how it does what it does (I'd argue not really).


To clean up the code a bit and increase performance, try this one line that does everything your code does :-)

from statistics import median

As far as your algorithm goes, I think that the speed would likely be improved if you just sorted the list in the first place, then selected the middle one (or ones and took the average). You don't correctly handle the case where the size of the list is even.


How can I ensure some structure for classes for a plug-in system written in Python?

You did not mention which Python version you are targeting. If the ABCMeta metaclass does not seem to be working you are probably on Python 3 where you must apply a metaclass in this manner:

class Feature(metaclass=abc.ABCMeta):

To answer your main question, one possible approach is this: let the base class check the arguments, and call a different, abstract method to do the work. Subclasses will then override the abstract method only.

class Feature(object):
    __metaclass__ = abc.ABCMeta

    def __call__(self, handwritten_data):
        assert isinstance(handwritten_data, HandwrittenData.HandwrittenData), \
            "handwritten data is not of type HandwrittenData, but of %r" % \
            type(handwritten_data)
        return self._call(handwritten_data)

    @abc.abstractmethod
    def _call(self, handwritten_data):
        pass


import Safe (findJust)
import Data.Foldable (null, all)

personalRating = sortBy . comparing . defaultRateFunction

proposal m f = all (on (>) (defaultRateFunction f) m) $ partner f

remarry p x = (x {partner = p} :) . delete x

marrige :: [Person] -> [Person] -> [Person]
marrige ms fs = case find (null . partner) ms of
  Nothing -> fs
  Just m -> marrige
    (remarry (Just f} m $ maybe id (remarry Nothing) (partner f) ms)
    (remarry (Just m) f fs)
    where f = findJust (proposal m) $ personalRating m fs

You never actually use ms that have a partner. Why keep track of them? I'll assume that all start out without partners, otherwise filter once at the start. In particular, I'll assume the invariant that partnership is symmetric.

marrige :: [Person] -> [Person] -> [Person]
marrige [] fs = fs
marriage (m:ms) fs = marrige
  (maybe id (\ex -> (ex {partner = Nothing} :)) (partner f) ms)
  (f {partner = Just m} : delete f fs)
    where f = findJust (proposal m) $ personalRating m fs

For performance, you could use Data.Map instead of []'s delete.

Edit: Here's one where the explicit recursion is less global. Unsetting ex's partner may be superfluous.

import Control.Monad.State

marrige = execState . traverse_ go where go m = do
  f <- gets $ findJust (proposal m) . personalRating m
  modify $ (f {partner = Just m} :) . delete f
  for_ (partner f) $ \ex -> go $ ex {partner = Nothing}


Already pointed out by other users

There is no need to make lists from the strings as any sequence will do
minimums - you make bad names where the existing names were better

The if clause
if args.extended :
    subset = alphaL + alphaU + numeric + special2
    for i in range(0, minimums[3]) :
        password += secrets.choice(special2)
elif minimums[3] :
    subset = alphaL + alphaU + numeric + special
    for i in range(0, minimums[3]) :
        password += secrets.choice(special)

is erroneous. The check for elif minimums[3] shall be replaced by an else:
Also - just because you already switch on args.extended you are not required to pack all variation on that argument in there.
You prepare subset for the logically next function (choice from compound set) before even performing the current one (choice from special).
That results in less readability. There is nothing wrong in switching two times if required. However in this case you should simply switch
if args.extended:
    special = """~`!@#$%^&*()+=_-{}[]\|:;"'?/<>,."""
else:
    special = "!@#$%^&*"

Then the choice from special/special2 collapses to the standard pattern.
Names
It was already mentioned that the minimum list is a name worse than the args attributes (which could be even more descriptive).
Also the names for your imports are bad and camel-cased. why not simply follow the existing naming scheme?
ascii_lowercase = string.ascii_lowercase

or even more straight
from string import ascii_lowercase
from string import ascii_uppercase
from string import digits

An extra bad name is subset
subset = alphaL + alphaU + numeric + special

which is clearly a union or superset
The standard pattern
You do
for i in range(0, minimums[0]) :
    password += secrets.choice(alphaL)

the recommended way to character wise join a string is
password += "".join(secrets.choice(ascii_lowercase) for _ in range (0, args.lower)

Cargo cult
You do
for i in range(0, 100) :
    random.shuffle(subset)

which is pointless. It is pointless to shuffle a 100 times. there is no extra quality in randomness compared to a single shuffle.
It is even more pointless to do that before apply secrets.choice(subset). You could safely sort subset before choice().
Final shuffle
You do
for i in range(0, 100):
    print("Password: ", password)
    password = ''.join(random.sample(password, len(password)))

which I interpret as final shuffle to eliminate the order of the subsets ascii_lowercase, ascii_uppercase, ...
Again you shuffle a 100 times which will not add any value compared to a single shuffle. To be cryptographically safe you should implement a shuffle based on secrets.choice.


Improving a robot's ability to navigate the plane with Karel J. Robot

Commands is a poor name for this class.  It's a robot of some kind.  Better names would be EnhancedRobot or GridAwareRobot or CartesianRobot.
What is the point of the currentDirection member variable?  It's a write-only variable, and is therefore useless.
Reusing code via inheritance is always tricky business, especially here, where the Robot class that you are extending is a bit of a poorly documented black box.
The way you use super calls is confusing.  For example, a call to Commands.move(2) chains to Robot.move().  However, to ensure that the zero-parameter .move() method on a Commands object works consistently, you also override Commands.move() to chain to move(1).  If you were to add another level of inheritance on top of this, it could get very difficult to trace what calls what, especially with overriding and overloading involved.
In addition, you also have to be concerned that the superclass methods to move, turn, and pick/drop beepers don't always succeed the way you would expect.  Indeed, a robot can enter a "crashed" state if it tries to drop a beeper when the bag is empty, or if it runs out of bounds, or if it runs into a wall (see the World class).  Since the Robot offers no way to detect and recover from such errors after the fact, you must proceed with extreme caution with every action.  This is especially important since your Commands and the underlying Robot are keeping track of the state independently, and your information could get out of sync if you assume that everything has gone smoothly.
The Robot's capabilities are actually deliberately limited to one primitive action at a time to force you to build reliable state machines in these exercises.  By writing a move(int steps) method, you are, in a sense, missing the point of these algorithm-design exercises.  What should happen if, say, Karel runs into a wall after 2 steps of a move(5)?  Karel has no remote-sensing capabilities, so your options are:

Let it crash, and fail the exercise. ☹

Move 2 steps, detect that the front is not clear, avoid telling the Robot superclass to move the third step, and somehow give your caller a way to query the position of the robot and deduce that the move(5) only got partially executed.  This is better than crashing, but puts your user in the nasty position of figuring out what to do with a partially-executed command.
And how would the user figure out what state Karel is in after a partially-executed command?  You'll notice that the language you are allowed to use in these exercises is a restricted subset of Java: you aren't supposed to assign or compare variables (except in a counting for-loop).1  In a sense, you have already cheated in writing this code, by assigning variables.  But with this strategy, you would also be forcing your user to cheat too.

Move 2 steps, detect that the front is not clear, turn around 180°, move 2 steps, and turn around 180° again.  This is known as atomically failing.  This kind of behaviour would restore sanity to your user's algorithms: at least you would be assured that after a move(5), the robot is in one of two states (either five steps ahead, or not moved at all).

Endow your Commands class with a canMove(int steps) method to emulate remote-sensing capability, which you implement by carefully walking out and walking back.  Then, if the user calls move(5) and crashes, it's not your fault.

You'll probably realize that none of these strategies is palatable, and do your exercises using a dumb Robot after all.

1 Based on the reference in Karel the Robot Learns Java, Appendix A


Old technique

The version you're using relies on overload resolution. The current form of detection idiom relies on SFINAE. IIRC SFINAE didn't exist pre-C++11.(Thanks to @JDlugosz)

Code Review

Inherit from std::true_type and std::false_type

That will spare a lot of boilerplate, and incorporates with tag dispatch quite well. It might not be directly usable in your case without some indirection and hiding into namespace detail.
Don't use enum as a member where static constexpr bool will do

Even though with freestanding values it is a different story due to linkage. bool will just bring less surprises.
Provide xxx_v value aliases

Somewhat modern approach

Lets take somewhat more interesting example.

  Identify if value of type Element can be push_backed into container of type Container.

Today, it is suggested to first "carve out" the operation itself into an alias:

template <typename Container, typename Element>
using pushback_t = decltype(std::declval<Container>().push_back(std::declval<Element>()));

Then, std::void_t is used:

template <typename Container, typename Element, typename = std::void_t<>>
struct has_pushback : std::false_type{};

template <typename Container, typename Element>
struct has_pushback<Container, Element, std::void_t<pushback_t<Container, Element>>>:
                        std::true_type{};

And then _v value alias is provided:

template <typename Container, typename Element>
inline constexpr bool has_pushback_v = has_pushback<Container, Element>::value;

Demo.

Shameless self PR: if you're a bit confused about how SFINAE works in the new version, I recommend reading this question which I've asked in the past.

Better upgrade path

When std::is_detected will arrive, one can easily put something like this (provided a copy the operation alias from above):

template <typename Container, typename Element>
struct has_pushback : std::is_detected<pushback_t, Container, Element>
{};

That will spare even more boilerplate. See comments for already existing implementations.


Rather than breaking the string into substrings, then converting each individually from a hex string to an integer, I'd probably convert the entire string at once, then use bit shifting to get the pieces you care about.

SDL_Color hex2sdl(std::string input) {

    if (input[0] == '#')
        input.erase(0, 1);

    unsigned long value = stoul(input, nullptr, 16);

    SDL_Color color;

    color.a = (value >> 24) & 0xff;
    color.r = (value >> 16) & 0xff;
    color.g = (value >> 8) & 0xff;
    color.b = (value >> 0) & 0xff;
    return color;
}

This simplifies the code quite a bit, and at least in my mind makes it rather easier to read.

Another point to consider (when/if your compiler supports it) would be to use an std::string_view instead of a std::string for the input. A string_view is something like a pointer/length, so (when needed) it can trim the # from the beginning without copying all the data like an actual string normally will. Even if your compiler supports string_view itself, however, it may easily not support passing a string_view to std::stoul, which kind of ruins the idea (for now).


GLSL function used to differentiate between pixels above/below a line

I would try using the dot product for your test. If you take the vector from p1 to p2 and form the dot product with the vector from p1 to aspect, it will return the cosine of the angle between them. The cosine of an angle is positive when the angle is between -90° and 90° and it's negative when the angle is in the other 180° of the circle. What this means is that when aspect falls on one side of the line it will be positive and on the other it will be negative. So your function could be rewritten as something like this:

float slice(vec4 aspect, vec2 p1, vec2 p2, bool top) {
    aspect /= aspect.w;    // <- may be unnecessary if w is guaranteed to be 1.0
    vec2 v1 = aspect.xy - p1;
    vec2 v2 = p2 - p1;
    float cosTheta = dot(v1, v2);
    float result step(0.0, cosTheta);
    return top ? result : 1.0 - result;
}

I haven't tested this, but it removes all conditionals and logical operators. If you don't need the divide by w then there are no divisions, either. I think this could be faster, but you'll need to profile to be sure.

Note that this assumes that "on the line" can be taken as being on one side or the other. If you need to differentiate that case, I think you'll need either a conditional or some clever non-conditional code to extract that case.


Boost.Signals2 is a thread-safe library. It uses mutex locking internally. There are some caveats, as explained in this article:

  Almost all classes provided by Boost.Signals2 are thread safe and can
  be used in multithreaded applications. For example, objects of type
  boost::signals2::signal and boost::signals2::connection can be
  accessed from different threads.

  On the other hand, boost::signals2::shared_connection_block is not
  thread safe. This limitation is not important because multiple objects
  of type boost::signals2::shared_connection_block can be created in
  different threads and can use the same connection object.

but in its simplest and default forms, Boost.Signals2 is multi-threading safe.

Your given example is, indeed, thread-safe.

  What happens if an Observer is destructed during notifyObservers?

The slot is disconnected preemptively.


Separation of concerns. Ideally, one method should do one thing. I would expect the rotate method to actually rotate the array. That's it. Your method also prints something to the standard output. There are two reasons why it's bad. Firstly, it's confusing. Secondly, it introduces more reasons for the method to change. For instance, if you need to change the format of the output or write it to the file, you have to change the rotate method. It's not convenient, is it?
The interface is quite strange. The n parameter of the rotate method is redundant (it's expected to be equal to the length of the array, isn't it?). It also makes the interface less clear (what if I pass a different value of n?).
The algorithm itself is not efficient. Shifting the array be one d times requires O(n * d) time. There are at least two ways to make it linear. The first one is pretty simple. You can copy the entire array to a buffer and that assign res[i] = buffer[(i + d) % buffer.length] in a loop. However, it requires additional memory. The second one uses a constant amount of space and O(n) operations. It goes like this: to cyclically shift an array by k positions to the left, one can reverse the [0, k - 1] range, then reverse the [k, n - 1] range and finally reverse the entire array.
Documenting your code is a good practice. It's not clear what the valid range of values for d is from your code itself. It's also not clear whether it performs a left or a right shift.
Your code formatting violates the Java coding conventions. The indentation is kind of messed up. The binary operators are not surrounded with whitespaces. The names of the variables are not meaningful (for example, what does d stand for?). That's why it's hard to read.


Naming

Some variable names should be more descriptive:

What does set contain?
What does num count?
What is cent or arrayThree?

Simplifications

if String(char) == "." can be shorted to if char == ".", the conversion to
a string is not needed because "." can be both a string literal and a
character literal.

In

var num = board[i].reduce(0 , {(result : Int, char : Character)
    in
    var cent = 0
    if String(char) == "."{
        cent = 1
    }
    return result + cent
})

the closure can be shortened to

var num = board[i].reduce(0 , {(result, char) in
    char == "." ? result + 1 : result
})

without the need for a temporary variable.

In

set = Set(board.reduce([Character]() , { resultArray, chars in
    return resultArray + [chars[i]]
}))

an array is created with the elements in column #i, and put into a set. That can be simplified to

let column = board.map { $0[i]} // Column #i
set = Set(column)

and column can then also be used in the following count of empty fields.

The creation of an array of all entries of a block can be simplified using
array slices:

let firstRow = 3 * (i / 3)
let firstCol = 3 * (i % 3)
let block = board[firstRow..<firstRow+3].flatMap { $0[firstCol..<firstCol+3]}

Generally, the check for duplicate digits in a row/column/block can
be simplified if you filter out empty fields before creating the set,
that makes counting the empty fields obsolete.

Comments

The comments

// firstly
// secondly
// thirdly

are not really helpful.

Putting it together

Summarizing the above suggestions so far, the code could look like this:

class Solution {
    func isValidSudoku(_ board: [[Character]]) -> Bool {

        for i in 0..<9 {
            // Check digits in row #i:
            let rowDigits = board[i].filter { $0 != "." }
            if rowDigits.count != Set(rowDigits).count {
                return false
            }

            // Check digits in column #i:
            let colDigits = board.map { $0[i] }.filter { $0 != "." }
            if colDigits.count != Set(colDigits).count {
                return false
            }

            // Check digits in block #i:
            let firstRow = 3 * (i / 3)
            let firstCol = 3 * (i % 3)
            let blockDigits = board[firstRow..<firstRow+3].flatMap { $0[firstCol..<firstCol+3]}
                .filter { $0 != "." }
            if blockDigits.count != Set(blockDigits).count {
                return false
            }
        }

        return true
    }
}

An alternative approach

The Python solution can not be translated directly to Swift, one reason is
that tuples are not Hashable and therefore cannot be put into a set.
Also inhomogeneous collections are better avoided in Swift.

But we can enumerate the board in a similar fashion, and put each element
into a set corresponding to its row, column, and block. The return value
from the insert statement already indicates if an identical element was
already present.

That leads to the following implementation:

class Solution {
    func isValidSudoku(_ board: [[Character]]) -> Bool {
        var rowSets = Array(repeating: Set<Character>(), count: 9)
        var colSets = Array(repeating: Set<Character>(), count: 9)
        var blockSets = Array(repeating: Set<Character>(), count: 9)

        for (i, row) in board.enumerated() {
            for (j, char) in row.enumerated() where char != "." {
                if !rowSets[i].insert(char).inserted {
                    return false
                }
                if !colSets[j].insert(char).inserted {
                    return false
                }
                let block = (i / 3) + 3 * (j / 3)
                if !blockSets[block].insert(char).inserted {
                    return false
                }
            }
        }

        return true
    }
}

I haven't checked which one is more efficient, I leave that task to you :)


Your class Shape knows about what kind of shape it is (circle/square). This makes it tied to the two child classes. It should not know any thing about the composition. Rather just provide methods with empty implementations that can be overridden by child classes.

The only thing I can see that is common across all classes is the concept of a center point and a color. So

import abc

class Shape(metaclass=abc.ABCMeta):
    def __init__(self, centrePoint, colour):
        self.centrePoint = centrePoint
        self.colour = colour

Since move depends only on center point, it is ok to define it in base class.

    def move(self,x,y):
        self.centrePoint.move(x,y)

This is certainly one that should be implemented by the child classes because it requires knowledge about what kind of a shape it is.

    @abc.abstractmethod
    def getArea(self):
        return

or if you dont want to use it

    def getArea(self):
        raise NotImplementedError('Shape.getArea is not overridden')

see
abc in
so

And the to string method is another that should be done in child because it holds details of what shape it is.

    @abc.abstractmethod
    def __str__(self):
        return

However, if you are going to use the same format for all shapes, then you can provide the default implementation (as below.)

    def __str__(self):
        return "Center Point: " + str(self.centrePoint) + "\nColour: "+ self.Colour + "\nType: " + self.type() + "\nArea: " + self.getArea()

I would also recommend scale as part of the base class because all shapes can be scaled.

    def scale(self, factor):
        return

Basically all operations that make sense on any shapes should have an abstract method on the base class.

Now for child classes

class Rectangle (Shape):
    def __init__(self, cp, color, width, height):
        super(Rectangle, self).__init__(cp, color)
        self.width = width
        self.height = height

    def scale(self, factor):
        self.scaleVertically(factor)
        self.scaleHorizontally(factor)

    def scaleVertically(self, factor):
        self.height *= factor

    def scaleHorizontally(self, factor):
        self.width *= factor

    def getArea(self):
        return self.width * self.height

    def type(self):
        return "Rectangle"

class Circle (Shape):
    def __init__(self, cp, color, radius):
        super(Rectangle, self).__init__(cp, color)
        self.radius = radius

    def scale(self, factor):
        self.radius * factor

    def getArea(self):
        return math.pi*(self.radius**2)

    def type(self):
        return "Circle"


MembershipProvider with Entity Framework and IoC

The preferred method of doing this is to use a factory dependency that creates the DbContext for you. So instead of the DbContext as the dependency you have a ContextFactory as the dependency and its consumers can get and manage a local DbContext by calling contextFactory.CreateContext();

If you insist on having your context injected directly, I believe it would be much better to have your MembershipProvider be registered per web request (even though you don't have control over creating it, you still have to register it right?). It shouldn't be a bottleneck. From a design and testing perspective this is much preferred to having a hard dependency on a service locator. How will you test the class by itself? Would you be incorporating your service locator into your tests?


Variadic template with function argument

using lambdas might be expensive

Why do you think that?

Lambdas are simply syntactic hand waving for class functors (that have been around for over 3 decades). Functors are considered (in general) to be much more efficient than standard functions (especially when used by templates) as the compiler can do a lot of optimizations on them.

auto x = [&capture](X const& parm){ /* BODY */ }

You can consider as syntactic sugar for:

class CompilerNamedType
{
    TypeOfCapure&     capture;
    public:
        CompilerNamedType(TypeOfCapure& capture)
            : capture(capture)
        {}

        CompilerCalculatedReturnType operator()(X const& param) const
        {
            /* BODY */
        }
};

CompilerNamedType  x(capture);


RAII

Whenever you need to acquire a resource, hold it for a while, and then release it deterministically - think resource acquisition is initialization. RAII! When I look at your equality comparison:

bool operator== (const EventHandler& other)
{
    while (m_flag.test_and_set(std::memory_order_acquire));
    bool equal = (m_ptr == other.m_ptr);
    m_flag.clear(std::memory_order_release);
    return equal;
}

We're really doing two things. We're acquiring and releasing a lock on m_flag, and then we're doing the equality comparison. So let's make that a lot more explicit.

std::lock_guard is an RAII lock, templated on a BasicLockable - which is just a class that supports a lock() and unlock(). So instead of holding a std::atomic_flag member, we can hold a member of type:

struct FlagMutex {
    void lock() {
        while (m_flag.test_and_set(std::memory_order_acquire));
    }

    void unlock() {
        m_flag.clear(std::memory_order_release);
    }

    /*
     * note that you were not initializing your flag correctly!
     */
    std::atomic_flag m_flag = ATOMIC_INIT_FLAG;
};

And then our equality operator becomes:

bool operator== (const EventHandler& other) {
    std::lock_guard<FlagMutex> lk(m_mutex);
    return m_ptr == other.m_ptr;
}

Keep that in mind throughout. Furthermore, if you do it this way, then FlagMutex can become a template argument for EventHandler so you can actually test the assertion that a std::atomic_flag is faster than a std::mutex.

Generalize Your Class

Right now, your event handler is constructible with:

template <typename _Type>
EventHandler(void (_Type::*memFn)(_EventArg), _Type *obj)

But why limit to just member functions? Your class has a std::function member. That can support free functions. Just generalize it.

Additionally, prefer make_shared to just new:

using FuncType = std::function<void(_EventArg)>;

template <typename F,
          typename = std::enable_if_t<
              std::is_constructible<FuncType(F&&)>::value
          >>
EventHandler(F&& func)
{
    m_ptr = std::make_shared<FuncType>(std::forward<F>(func));
}

The user can pass in a bind expression if they want, or a lambda, or any number of other things. Just lets you do more things.

Also _EventArg is a reserved name.


My current task is to find a score from an array where the
  highest/lowest scores have been taken away, and if the highest/lowest
  occur more than once (ONLY if they occur more than once), one of them
  can be added

So the programflow can be written as:

Find the highest item of the array
Find the lowest item of the array
Find the number of occurance of the highest item of the array
Find the number of occurance of the lowest item of the array
Remove the first highest item found
Remove the first lowest item found
Sum together the remaining items
Export/Print the results

So you will have 8 methods without the ExitProgram() method.

Review

Naming

Based on the naming conventions for C#, all methodnames should be written using the PascalCasing style. So findOccurrence should be FindOccurrence and findScore should be FindScore

So based on the list of tasks above the methods should be named

FindHighestItem() or GetHighestItem()
FindLowestItem() or GetLowestItem();
FindNumberOfHighestOccurance() or GetCountOfOccurance()
FindNumberOfLowestOccurance() or GetCountOfOccurance()
RemoveHighestItems() or SetArrayitemsByValueToZero()
RemoveLowestItems() or SetArrayitemsByValueToZero()
GetHighestItemIndex()
GetLowestItemIndex()
GetNormalizedArray() which returns a new array or
SetArrayitemsByValueToZero() which manipulates the items in the array
SumItems()
Print()

Style

Opening brackets should be placed on the line below the statement so

for (int i = 0; i < scores.Length; i++) {

should be

for (int i = 0; i < scores.Length; i++)
{

Programflow

By combining some of these tasks you are violating the single responsible principle.
The findScore() method

is searching for the highest and lowest item in the array
removes the highest and lowest item from the array (basically add only the items which aren't highest or lowest to the new array)
is summing the items of this new array stated above
is printing/exporting the sum

Refactoring

For getting the highest/lowest item in the array we can use the Math.Max() and Math.Min() methods. For finding the highest item we will initialize the var highestValue with Int32.MinValue and for finding the lowest item we will initialize the var lowestValue with Int32.MaxValue.
Based of the comment as it is not allowed for this assignment to use Math.Min() or Math.Max() I have changed the methods

    private int GetLowestItem(int[] items)
    {
        int lowestItem = Int32.MaxValue;
        foreach (int item in items)
        {
            // lowestItem = Math.Min(item, lowestItem);
            if (item < lowestItem)
            {
                lowestItem = item;
            }
        }
        return lowestItem;
    }

    private int GetHighestItem(int[] items)
    {
        int highestItem = Int32.MinValue;
        foreach (int item in items)
        {
            // highestItem = Math.Max(item, highestItem);
            if (item > highestItem)
            {
                highestItem = item;
            }
        }
        return highestItem;
    }

    private int GetCountOfOccurance(int[] items, int comparingValue)
    {
        int count = 0;
        foreach (int item in items)
        {
            if (item == comparingValue)
            {
                count++;
            }
        }
        return count;
    }

private int GetHighestItemIndex(int[] items, int highestItem)
{
    for(int i = 0 ; i<items.Length ; i++)
    {
        if(items[i] == highestItem)
        {
            return i;
        }
    }
    return -1;
}

private int GetLowestItemIndex(int[] items, int lowestItem)
{
    // to be filled by you
}

Next we should create a new calssed named BoundaryItem which holds the min and max values of the array.

class BoundaryItem
{
    internal int Max { get; set; }
    internal int Min { get; set; }
}

now we add a method to set each item of the array to zero if the value is either the max or the min of the array.

private void SetArrayitemsByValueToZero(int[] items, BoundaryItem boundaryItem)
{
    for (int i = 0; i < items.Length; i++)
    {
        if (items[i] == boundaryItem.Min || items[i] == boundaryItem.Max)
        {
            items[i] = 0;
        }
    }
}

Next we will add a 2 overloaded SumItems() methods

public int SumItems(int[] items)
{
    BoundaryItem boundaryItem = PreProcessArray(items);

    return SumItems(items, boundaryItem);
}

private int SumItems(int[] items, BoundaryItem boundaryItem)
{

    int sum = boundaryItem.Min + boundaryItem.Max;
    foreach (int item in items)
    {
        sum += item;
    }
    return sum;
}

and last we add the missing PreProcessArray() method

private BoundaryItem PreProcessArray(int[] items)
{
    BoundaryItem boundaryItem = new BoundaryItem();

    boundaryItem.Min = GetLowestItem(items);
    boundaryItem.Max = GetHighestItem(items);

    int minOccurance = GetCountOfOccurance(items, boundaryItem.Min);
    int maxOccurance = GetCountOfOccurance(items, boundaryItem.Max);

    SetArrayitemsByValueToZero(items, boundaryItem);

    if (minOccurance < 2) { boundaryItem.Min = 0; }
    if (maxOccurance < 2) { boundaryItem.Max = 0; }

    return boundaryItem;
}

But wait, we can still do better, if the amount of methods needed would not matter. Instead of GetLowestItem() and GetHighestItem() we create a method GetBoundaryItem()

private BoundaryItem GetBoundaryItem(int[] items)
{
    BoundaryItem boundaryItem = new BoundaryItem();
    boundaryItem.Min = Int32.MaxValue;
    boundaryItem.Max = Int32.MinValue;

    foreach (int item in items)
    {
        if (item < boundaryItem.Min)
        {
            boundaryItem.Min = item;
        }
        else if (item > boundaryItem.Max)
        {
            boundaryItem.Max = item;
        }
    }
    return boundaryItem;
}

and change the PreProcessArray() method

private BoundaryItem PreProcessArray(int[] items)
{
    BoundaryItem boundaryItem = GetBoundaryItem(items);

    int minOccurance = GetCountOfOccurance(items, boundaryItem.Min);
    int maxOccurance = GetCountOfOccurance(items, boundaryItem.Max);

    SetArrayitemsByValueToZero(items, boundaryItem);

    if (minOccurance < 2) { boundaryItem.Min = 0; }
    if (maxOccurance < 2) { boundaryItem.Max = 0; }

    return boundaryItem;
}

The printing I will leave to you. As you see I have made instance methods out of the static methods. So it would be a good idea to create a class named Scoring where you place these methods.Then you would call this like

static void Main(string[] args) {

    Scoring scoring = new Scoring();

    int[] scores = { 4, 8, 6, 4, 8, 5 };
    int sum = scoring.SumItems(scores);
    // now print the result
    ExitProgram();
}

See: When to Use Static Classes in C#

As I have written the refactorings I came to the conclusion that we just need to get the index of the highest/lowest items so we can skip those items at composing the new array.
After the coment from Malachi I realized that using the index of the highest/lowest item will be an invalid aproach if these values are contained more than 2 times in the array.
This implementation assumes that for the given array [1 ,1 ,1 ,2 ,3 ,3 ,3]  it's sum should be 1 + 2 + 3 .


The only thing I can see is that you don't need to have the return on a separate line.  return next((c for c in text if c.isalpha()), "") works fine.  It works on both python 2 and python 3 from what I can see.

Also, you could use filter in this situation: return next(iter(filter(unicode.isalpha, text)), ""), although I am not sure that is any real improvement.  On python 3 this approach is a bit simpler: return next(filter(str.isalpha, text), "")


A simple implementation of the Unix find command written in Rust

Your code can be simplified a little bit:

use std::collections::VecDeque;
use std::ffi::{OsStr, OsString};
use std::io;
use std::path::PathBuf;

fn find(query: &str, start: &OsStr) -> io::Result<Vec<PathBuf>> {
    let start = PathBuf::from(start);
    let mut dirs = VecDeque::from(vec![start]);
    let mut result = Vec::new();

    while let Some(dir) = dirs.pop_front() {
        for entry in dir.read_dir()? {
            let path = entry?.path();
            if path.is_dir() {
                dirs.push_back(path.clone());
            }
            if let Some(name) = path.file_name() {
                if query.is_empty() || query == name {
                    result.push(path.clone());
                }
            }
        }
    }
    Ok(result)
}

fn main() -> io::Result<()> {
    let mut args = std::env::args().skip(1);
    let query = args.next().unwrap_or(String::new());
    let start = args.next().map(OsString::from).unwrap_or(OsString::from("."));

    for path in find(&query, &start)? {
        if let Some(p) = path.to_str() {
            println!("{}", p);
        }
    }
    Ok(())
}

In your function find, you should use the borrowed version of String and OsString as parameters; or you can just move the value if you think that query or start will not be needed anymore in the main.

In you main, you can take advantage of the Iterator's and Option's methods to make a more concise and cleaner code:

You create an iterator that will iterate over all args but the first using skip;
The query is the next item: if there is no item, you give a default value with unwrap_or;
For the next item, first you apply a function to the inner with map, and then you provide a default value;
Your main can return a Result, so you do not need to make the error handling by hand.

Just a little thing: the idiomatic way to do such an algorithm in Rust is to implement an Iterator. In you code you do an unnecessary allocation for all your found files.


I recommend a signature of:

def distributer(f, data, num_workers=8):
...
    for _ in range(num_workers):

Perhaps f is the appropriate identifier. But it leaves me scratching my head a bit. I wouldn't mind a docstring explaining the function's responsibility.

    p = Process(target=worker, args=(child_conn,))

Ordinarily this would be perfect. But given that you're also manipulating pipes, it wouldn't hurt to assign to proc instead.

Your prose suggests that you're filtering, in this case picking out one value in a thousand. Perhaps the appropriate function name would have been filter_worker().

Phrasing it as "reduce" may have been clearer than "filter". For example, every thousandth row return sum of previous rows, that sort of thing, if the code is strictly for illustrative purposes.

In summary, as a reader I'm looking for a comment / docstring that explains what is interesting about the top level code doing busy work forever (I see no benchmark timings), and I'm interested in a docstring on worker() explaining the protocol it implements.


Actively writing an HTTPS webserver in Python 3

When importing names from a location (module, package, dynamic library, ...), don't mix multiple locations on a single line. That is, this:

import os, ssl

... should be:

import os
import ssl

This is purely a stylistic concern, and it's one of the rules listed in PEP-8, the official Python style guide.
Global variables should be a last resort. They clutter the global namespace, are hard to track when reading the code, and are very prone to race conditions when using threads. Here, you could pass the context as an argument, or perhaps set up another class with the context attached as an attribute.

Let's say you have to share foo between func_a() and func_b(). Three different approaches:

Make foo global (analogous to what you did with the context, not great):

foo = Foo()

def func_a():
    foo.method_1()

def func_b():
    foo.method_2()

func_a()
func_b()

Pass foo as an argument:

def func_a(foo):
    foo.method_1()

def func_b(foo):
    foo.method_2()

def main():
    foo = Foo()
    func_a(foo=foo)
    func_b(foo=foo)

Make foo a class attribute:

class MyClass:
    def __init__(self, foo):
        self.foo = foo

    def func_a(self):
        self.foo.method_1()

    def func_b(self):
        self.foo.method_2()

my_class = MyClass(Foo())
my_class.func_a()
my_class.func_b()

Even if you stick to using global variables, setting global sslcontext is unnecessary because you're not reassigning it. If you're not assigning to a variable, Python will:

i. Try to find the name locally;

ii. If that fails, look for the name in global scope;

iii. Finally, raise a NameError to indicate the variable doesn't exist in any scope.

Therefore, if you reference sslcontext locally, the interpreter will find the global name (ii.). But it can't read your mind. If you instead assign sslcontext = 42, Python will assume you want to create a fresh, local variable with the name 'sslcontext' and the value of 42, rather than reassigning the global sslcontext. That's it. That's where global comes in, and that's all it's good for.
In HSTSHandler.end_headers(), this idiom:

SimpleHTTPRequestHandler.end_headers(self)

... could be more clearly expressed by calling super(), then super().end_headers(). This is good practice, and also assures multi-inheritance is handled correctly.
Source code encoding does not need to be set explicitly here, as ASCII will suffice.

That's as much as I can give you without more context to the question.


Switch statement in PHP - cleaner way to determine priority?

That's certainly a bastardization of the switch statement.

What you should use is an if...else if... group:

$response = null; //initialize
if ( $controller->using_router)
{
  $response = $controller->router();
}
else
{
  $response = Annotation\Runner::run(Annotation\Extractor::extract( $controller, $method ) );
  if ( is_null( $response )
  {
    $response = call_user_func_array( array( $controller, $method ), $parameters );
  }
}

Note: this code flows in a readable manner. The response is set, if the controller is using the router, the response is set to the output of $controller->router(), otherwise the response is set to the extracted controller method.

If that is null, the response is finally set to whatever $controller->$method(...) produces.

Code should always flow in a readable manner (unless it's minified, obfuscated, or encoded).


My remarks are similar to last time.  morse_alphabet should be MORSE_ALPHABET.  Repeated string concatenation (decoded += …) is bad for performance.  The main task could be accomplished using a one-liner substitution.

MORSE_ALPHABET = {
    ' '     : ' ',        # Note: Changed the key from '' to ' '
    '.-'    : 'A',
    '-...'  : 'B',
    '-.-.'  : 'C',
    …
}

def decode(morse):
    return re.sub(' ?( |[.-]*)', lambda m: MORSE_ALPHABET.get(m.group(1)), morse)

The main code would be simpler if you used fileinput.  Despite the current Pokémon craze, you should not Catch 'Em All, but only catch the exceptions that you intend to handle.

def main():
    try:
        for line in fileinput.input():
            print(decode(line), end='')
    except IOError as e:
        sys.exit(e)

if __name__ == "__main__":
    main()


Portability

The code would fail if the sender and receiver platforms disagree on the size of integer.

The code would fail if the sender and receiver platforms disagree on the endianness of integer.
Partial reads

There is a chance that the very first read returns just a couple of bytes. The code still interprets it as a valid integer.
Overall

There is no need to use the same buffer for both size and payload.

m,n,k are patently bad variable names.
Recommendations

Implement a separate send_size() and read_size() routines.


Project Euler #5 (Smallest multiple) in Swift

In general, I like it; nice solution. Functions are well separated and I understood what it was doing right away, just from the function names.

You can get rid of one of your leastCommonMultiple functions (and make it more Swifty I think) by passing it a Range instead of an Array and by using reduce():

func greatestCommonDenominator(a: Int, b: Int) -> Int {
    return b == 0 ? a : greatestCommonDenominator(b, a % b)
}

func leastCommonMultiple(range: Range<Int>) -> Int {
    return reduce(range, 1) { (a, b) in a * (b / greatestCommonDenominator(a, b)) }
}

func solution5() {
    let answer = leastCommonMultiple(1...20)
    println(answer)
}

That change also seems to speed it up significantly. On my machine it changed the average run time from 0.0001 seconds to 0.00002 seconds; I believe that's simply from not having to create the Array though.