Does this ugly code fit into a design pattern?

The strategy pattern is a good candidate for this, one way you could implement it would be something like as follows (the discounts are the strategies).

Define an interface for classes which can apply discounts:

public interface IApplyDiscount
{
    void Apply(buyerUserId, buyerTransaction, sellerUserId, sellerTransaction);
}

Create an implementation of the interface for the SingleFreeCommisionPerUser discount.

public class SingleFreeCommisionPerUserDiscount : IApplyDiscount
{
    public void Apply(buyerUserId, buyerTransaction, sellerUserId, sellerTransaction)
    {
        var userDiscounts = _discountRepository.GetUserDiscountsForUsersWithDiscounts(new List<int> { buyerUserId, sellerUserId }).ToList();

        var buyerHasFreeCommission = userDiscounts.Any(ud => ud.UserId == buyerUserId && ud.Discount.Type == DiscountTypes.SingleFreeCommisionPerUser);

        if(buyerHasFreeCommission)
        {
            buyerTransaction.Amount = 0;
        }

        var sellerHasFreeCommission = userDiscounts.Any(ud => ud.UserId == buyerUserId && ud.Discount.Type == DiscountTypes.SingleFreeCommisionPerUser);

        if(sellerHasFreeCommission)
        {
            sellerTransaction.Amount = 0;
        }
    }
}

The main code then creates the initial commission transactions:

var sellerCommisionChargeTransaction = new Transaction
{
    AccountId = sellerAccountId,
    Type = TransactionTypes.Fee,
    Amount = -2
};

var buyerCommisionChargeTransaction  = new Transaction
{
    AccountId = buyerAccountId,
    Type = TransactionTypes.Fee,
    Amount = -2
};

Applies all the available discounts:

List<IApplyDiscount> discounts = GetAllDiscounts();
discounts.ForEach(d => d.Apply(buyerUserId, buyerCommisionChargeTransaction, sellerUserId, sellerCommisionChargeTransaction));

Then, only add the corresponding charge if a transaction amount is due.

if (sellerCommisionChargeTransaction.Amount < 0)
{
    var sellerTransferFeeTransaction = new Transaction
    {
        AccountId = 5020,
        Type = TransactionTypes.Fee,
        Amount = -sellerCommisionChargeTransaction.Amount
    };

    _accountRepository.AddTransaction(sellerCommisionChargeTransaction);
    _accountRepository.AddTransaction(sellerTransferFeeTransaction);
}

if (buyerCommisionChargeTransaction.Amount < 0)
{
    var buyerTransferFeeTransaction = new Transaction
    {
        AccountId = 5020,
        Type = TransactionTypes.Fee,
        Amount = -buyerCommisionChargeTransaction.Amount
    };

    _accountRepository.AddTransaction(buyerCommisionChargeTransaction);
    _accountRepository.AddTransaction(buyerTransferFeeTransaction);
}

Then if you want to add other discount types and rates, you can just create additional IApplyDiscount implementations and include them in the results of the GetAllDiscounts() call.

This implementation is more flexible, you don't need to change any of the current implementation to add additional discounts.

The discounts could be percentages and the corresponding TransferFeeTransaction will cater for that by charging the positive value of whatever amount remains on the CommissionChargeTransaction.


It is better to use CouncurrentDictionary to reduce lock contention:

class Map<X, Y>
{
    public X this[Y y]
    {
        get { return YX[XY[YX[y]]]; } // Ensure Set completion
        set { Set(value, y); }
    }

    public Y this[X x]
    {
        get { return XY[x]; }
        set { Set(x, value); }
    }

    void Set(X x, Y y)
    {
        if (!YX.GetOrAdd(y, x).Equals(x))
            throw new InvalidOperationException();

        if (!XY.GetOrAdd(x, y).Equals(y))
            throw new InvalidOperationException();
    }

    ConcurrentDictionary<X, Y> XY { get; } = new ConcurrentDictionary<X, Y>();
    ConcurrentDictionary<Y, X> YX { get; } = new ConcurrentDictionary<Y, X>();
}


In case you do not know it yet, I suggest you to use pylint to parse your code and have automatic feedbacks. In fact some of my notes come from pylint.

Styling notes:

Constant names like var "directory" require uppercase style PEP8
Function and variable names require snake_case style PEP8
Functions require docstring, as well as the module itself PEP8

Inline notes

#NOTE: 'from datetime import datetime' allows a shorter line below
import datetime
import time
import os
import sys

# get user's current directory

# NOTE: use os.path.join for concat filesystem paths for cross compatibility (also below)
directory = os.path.dirname(os.path.realpath(__file__)) + '/logs'

def createNewLog():

    # ensure log folder exists

    if not os.path.exists(directory):
        # NOTE: what if user has no permission to create files/directory in current directory? (also below)
        # HINT: give a way to choose where to store logs
        os.mkdir(directory)

    # get timestamp for naming the log

    timeInSeconds = time.time()
    # NOTE: fromtimestamp may raise an exception which is not not managed here
    timestamp = \
        datetime.datetime.fromtimestamp(timeInSeconds).strftime('%Y-%m-%d %H:%M:%S'
            )

    logFile = directory + '/' + timestamp + '.txt'
    mostRecentLog = directory + '/mostRecentLog.txt'

    # create log file and file with the log file's name

    # NOTE: redefining name 'log' (it's also a function name)
    # NOTE: this 'log' is not used. What it's that for?
    with open(logFile, 'w') as log:
        with open(mostRecentLog, 'w') as recentLog:
            recentLog.write(timestamp)

def findMostRecentLog():

    # ensure logger has been intiated

    try:
        with open(directory + '/mostRecentLog.txt', 'r') as logFile:
            logName = logFile.read()
    except FileNotFoundError:
        print("Must initiate logger first!")
        # NOTE: kind of rugh, I suggest returning an error and managing at caller level
        sys.exit(1)

    return directory + '/' + logName + '.txt'

def log(comment):
    # NOTE: why forcing the type?
    comment = str(comment)

    # write to log file retriving most recent log from corresponding file

    # NOTE: this dependency will make hard testing this function alone.
    with open(findMostRecentLog(), 'a') as log:
        log.write(comment + '\n')


Find the square root of the number without using any built-in function?

It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.
The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.
As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.
You may want to check the input for correctness: both x and precision must be positive.


I can't really comment on your structure in Razor, as I am unfamiliar with that framework, however, your replacing structure could be improved.

By using a function, alongside a dictionary, you can simplify this greatly.

function massReplace(str, dict){
    for (var i in dict){
        str = str.replace(i, dict[i]);
    }
    return str;
}

Whilst also converting the "__id3__", id3 structure into:

var dict = {
    "__id2__": id2,
    "__id3__": id3,
    "__id4__": id4
};

And then simply:

$('#element').html('' + data[1] + '');


I have absolutely no idea what the purpose of this code is. Something to do with locking and unlocking files, but why? Your code doesn't say, and neither does your post. It's hard to review code when I have no idea what it is supposed to do.
There are no docstrings. What do these functions do? What arguments should I pass?
Running shell commands and parsing their output is complex and slow. Instead, get the flags for a file by calling os.stat and set the flags for a file by calling os.chflags. Use the constants in the stat module, for example stat.UF_IMMUTABLE for the uchg flag.

To read the flags for a file:

import os, stat
flags = os.stat(filename).st_flags

To determine if a file is immutable, evaluate:

bool(flags & stat.UF_IMMUTABLE)

To set the immutable flag, call:

os.chflags(filename, flags | stat.UF_IMMUTABLE)

To clear the immutable flag, call:

os.chflags(filename, flags & ~stat.UF_IMMUTABLE)

Since you don't say what the purpose of this code is, I can't tell if it is a good implementation or not. If you are planning to use this mechanism for mutual exclusion (e.g. to prevent two instances of a program running at the same time) then it won't work, because it has race conditions (the flags might change between getting them and setting them).


Checking if input is a string or an integer

This is now a conflict:

using namespace std;

//Workaround for compiler issue.
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 )

There is an stoi in the standard namespace. Because you used using this will be considered with your function. They both have the same parameter types so this should generate a compiler error.

The only reason it may not be doing so is that you are using an archaic version of the language.

You have to reset errno to a zero state before using a function that sets it (std::strtol does not change the value if there is no error it just sets the value if there is an error).

    if( errno == ERANGE || value > std::numeric_limits<int>::max() )
        throw std::out_of_range( "stoi: out ofrange" ) ;

This will fail if a previous library call set errno to ERANGE.

Don't like the extra indention of you r function:

int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 )
    {
^^^^!

Prefer to use {} around block statements.

if( errno == ERANGE || value > std::numeric_limits<int>::max() )
            throw std::out_of_range( "stoi: out ofrange" ) ;

// Best to be safe
// So consistent use of '{}' is usually best.
if( errno == ERANGE || value > std::numeric_limits<int>::max() ) {
            throw std::out_of_range( "stoi: out ofrange" ) ;
}

Readability enhanced by using another line:

if(pos) *pos = end - begin ;

// Easier to read for your next maintainer.
if(pos) {
    *pos = end - begin ;
}


jQuery cycle content of static HTML page

I would try to avoid using separate arrays for values that are interrelated.
Instead create an object with the elements of each content like:

{
    images: [
        "http://www.example.com/img100.jpg",
        "http://www.example.com/img101.jpg"],
    description: "some text 1",
    link: "http://www.somewhere.com/"
}

And create an array of these objects. So you only have to handle one array and one index.

var content = [ // Array of objects
{
    images: [
        "http://www.example.com/img100.jpg",
        "http://www.example.com/img101.jpg"],
    description: "some text 1",
    link: "http://www.somewhere.com/a"
}, {
    images: ["http://www.example.com/img200.jpg",
        "http://www.example.com/img201.jpg"],
    description: "some text 2",
    link: "http://www.somewhere.com/b"
}, {
    images: ["http://www.example.com/img555.jpg",
        "http://www.example.com/img556.jpg"],
    description: "some text 3",
    link: "http://www.somewhere.com/c"
}, {
    images: ["http://www.example.com/imgA.jpg",
        "http://www.example.com/imgX.jpg"],
    description: "some text 4",
    link: "http://www.somewhere.com/d"
} ];

I would also add a "show" function to avoid repeating the same code in each case. Thus, the code that handles the content can be simplified as:

var currentIndex = 0;

$(document).ready(function () {
    /* Content initialization */
    show(content[currentIndex]);

    /* Register click handlers */
    $("#gallery_button_left").click(function () {
        if (currentIndex > 0) {
            show(content[--currentIndex]);
        }
    });

    $("#gallery_button_right").click(function () {
        if (currentIndex < content.length - 1) {
            show(content[++currentIndex]);
        }
    });

});

/* Update content function */
function show(data) {
    animateTo(80);
    $(".view-before").css("background-image", 'url(' + data.images[0] + ')');
    $(".view-after").css("background-image", 'url(' + data.images[1] + ')');
    $(".gallery-title-h1").html(data.description);
    $("#link").attr("href", data.link);
}

Demo:

var content = [ // Array of objects
{
    images: [
        "http://www.example.com/img100.jpg",
        "http://www.example.com/img101.jpg"],
    description: "some text 1",
    link: "http://www.somewhere.com/a"
}, {
    images: ["http://www.example.com/img200.jpg",
        "http://www.example.com/img201.jpg"],
    description: "some text 2",
    link: "http://www.somewhere.com/b"
}, {
    images: ["http://www.example.com/img555.jpg",
        "http://www.example.com/img556.jpg"],
    description: "some text 3",
    link: "http://www.somewhere.com/c"
}, {
    images: ["http://www.example.com/imgA.jpg",
        "http://www.example.com/imgX.jpg"],
    description: "some text 4",
    link: "http://www.somewhere.com/d"
}, ];

var currentIndex = 0;

$(document).ready(function () {
    /* Content initialization */
    show(content[currentIndex]);

    /* Register click handlers */
    $("#gallery_button_left").click(function () {
        if (currentIndex > 0) {
            show(content[--currentIndex]);
        }
    });

    $("#gallery_button_right").click(function () {
        if (currentIndex < content.length - 1) {
            show(content[++currentIndex]);
        }
    });

});

/* Update content function */
function show(data) {
 //animateTo(80);
    $(".view-before").css("background-image", 'url(' + data.images[0] + ')');
    $(".view-after").css("background-image", 'url(' + data.images[1] + ')');
    $(".gallery-title-h1").html(data.description);
    $("#link").attr("href", data.link);
}

LEFT

RIGHT

    link


Why not add some JSDoc to your code:

/**
*@constructor
*@param {Array} txtbox - An array of whatever
*@returns {Validator}
*/
function Validator(txtbox) {
    /**
    *@private
    */
    this.txtbox = txtbox;
}

var validator = new Validator([ "username", "password"]);

/**
*@public
*@memberOf Validator.prototype
*@param {Form} form - The form holding the login information
*/
Validator.prototype.validate = function(form) {
    for(var i = 0, l=this.txtbox.length; i < l; i++) {
        var status = document.getElementById("status-msg");
        if (form[this.txtbox[i]].value == 0) {
            status.innerHTML="The " + form[this.txtbox[i]].name + " is empty";
            status.style.display = "inline-block"
            status.className = "error";
            return false;
        }
        else {
             status.innerHTML="Login successful";
            status.style.display = "inline-block"
             status.className = "success";
        }
    }
}

function runValidate(form) {
    validator.validate(form);
}


Linked List Interview Code methods, runtime, and edge cases

The namespace std is not designed for wholesale importation, see "Why is “using namespace std” considered bad practice?" for more detail.
You could instead do a using std::cout; or better qualify the three use-sites.

You don't in any way encapsulate the list and abstract over the list. It's just a bunch of Nodes. Consider putting it all into a List owning and managing the whole lot.

Trying to remove() the root-Node uncovers a bug. Try to trace it through.

pointer != nullptr is just a long-winded way to write pointer in a boolean context. Respectively for pointer == nullptr and !pointer. Yes, Java needs that, but this is C++.

When you return from the if-branch, putting the alternative in an else-branch is superfluous.

A function for printing an object should allow the caller to specify the stream, and be called operator<<.

There is no reason to rely on the compiler transforming recursion to iteration, especially as it might not always be able.

this should rarely be used explicitly.


You should pass your AccountListFilterModel to the view, either via model (which is the best solution as it's less error-prone) or using ViewBag \ ViewData (which is an anti-pattern actually, but fits the quick-fix niche).
Using the latter approach:

In your controller:

public ViewResult Index(AccountListFilterModel accountListFilter)
{
    ViewBag.Filter = accountListFilter;
}

In your view (you can delete the code at the top of the view, that uses Request to get parameters.

<a style="@(ViewBag.Filter.currentSortOrder == "UserName desc" ? "" : "display:none;")" ... />

It's a general rule of thumb that your view should not contain any logic at all, your controller should supply all the data that the view needs.


Remove duplicates from csv based on conditions

Using pandas.DataFrame.groupby is pretty much the same as what you are doing using the first line in your for loop. So you can change:

for email in df['Email Address'].unique():
    subdf = df.loc[df['Email Address'] == email]
    ...

by

for email, subdf in df.groupby('Email Address'):
    ...

Now, to improve this loop:

subdf['Registration Date Copy'].min() is not what you want since it gives you the value and you are interested by its index (as you are filtering and getting values[0] on the next line). Use argmin() instead to get the index so you can directly get the desired value with subdf['Registration Date'][<variable_name_you_stored_argmin_into>]
You can modify a specific cell of a DataFrame using df.set_value(index, column, value), no need to use an intermediate dataframe here. Since you will drop everything but the firsts elements of each group, you can change only the ones at subdf.index[0].

This yield:

df = pd.read_csv('pra.csv')

# Sort the data by Login Date since we always need the latest
# Login date first. We're making a copy so as to keep the
# original data intact, while still being able to sort by datetime
df['Login Date Copy'] = pd.to_datetime(df['Login Date'])
df['Registration Date Copy'] = pd.to_datetime(df['Registration Date'])
df.sort_values(by='Login Date Copy', ascending=False, inplace=True)

# Change the registration date of the first duplicate to the oldest one
for email, group in df.groupby('Email Address'):
    oldest_index = group['Registration Date Copy'].argmin()
    oldest_registration = group['Registration Date'][oldest_index]
    df.set_value(group.index[0], 'Registration Date', oldest_registration)

# Drop working columns
df.drop(['Login Date Copy', 'Registration Date Copy'], axis=1, inplace=True)

# Finally, get only the first of the duplicates and output the result
df.drop_duplicates(subset='Email Address', keep='first', inplace=True)
df.to_csv('~/output.csv', index=False)

I also changed a bit the formating of the comments and used inplace=True instead of df = df.whatever().

Finally, you may consider wrapping that in a function so you can easily change the values of the input/output parameters:

import pandas as pd

def main(input_csv, output_csv):
    df = pd.read_csv(input_csv)

    # Sort the data by Login Date since we always need the latest
    # Login date first. We're making a copy so as to keep the
    # original data intact, while still being able to sort by datetime
    df['Login Date Copy'] = pd.to_datetime(df['Login Date'])
    df['Registration Date Copy'] = pd.to_datetime(df['Registration Date'])
    df.sort_values(by='Login Date Copy', ascending=False, inplace=True)

    # Change the registration date of the first duplicate to the oldest one
    for email, group in df.groupby('Email Address'):
        oldest_index = group['Registration Date Copy'].argmin()
        oldest_registration = group['Registration Date'][oldest_index]
        df.set_value(group.index[0], 'Registration Date', oldest_registration)

    # Drop working columns
    df.drop(['Login Date Copy', 'Registration Date Copy'], axis=1, inplace=True)

    # Finally, get only the first of the duplicates and output the result
    df.drop_duplicates(subset='Email Address', keep='first', inplace=True)
    df.to_csv(output_csv, index=False)

if __name__ == '__main__':
    main('pra.csv', '~/output.csv')


Compare multiple values of an array in the same time in Javascript

let courseFilter = this.newFilterArr.find(k => k.key === 'courseId'),
    rateTypeFilter = this.newFilterArr.find(k => k.key === 'rateTypeId');

I would consider making your filter an object instead of an array. The keys are probably unique and known ahead of time, thus could be a type.

    if (courseFilter && rateTypeFilter) {
        return x['courseId'] === courseFilter.filtered.id && x['rateTypeId'] === rateTypeFilter.filtered.id;
    } else if (courseFilter && !rateTypeFilter) {
        return x['courseId'] === courseFilter.filtered.id
    } else if (!courseFilter && rateTypeFilter) {
        return x['rateTypeId'] === rateTypeFilter.filtered.id;
    }

This code is a good example of a function doing too many things. You can just progressively filter, filtering by courseId first, and whatever results from that, you filter with rateTypeId.  The condition with the && is not necessary.

This could be rewritten as:

class Filter {
  courseId:string
  rateTypeId:string
}

function Optimiz() {
  const filter:Filter = this.newFilterObj

  // Match only if filter is a truthy value. Otherwise, just add it.
  this.rateSetupDataUi = this.originalRateSetupDataUI
    .filter(x => filter.courseId ? x.courseId === filter.courseId : true)
    .filter(x => filter.rateTypeId ? x.rateTypeId === filter.rateTypeId : true)
}

Nitpicks

I advise against a single let/var/const and recommend a let/var/const per variable. Prepending/appending requires needlessly modifying the first and last lines, respectively. And if you move variables around, you will still have to add let/var/const.
x['courseId'] and x['rateTypeId'] don't need to be in bracket notation, as the property names don't have invalid characters.


find_path is very inefficient. Consider the following example, where we try to find a short path (just one edge) in a graph with just eleven nodes:

>>> G = {i: list(range(10)) for i in range(10)}
>>> G[0].append(10)
>>> find_path(G, 0, 10)
[0, 10]

How long does this take?

>>> from timeit import timeit
>>> timeit(lambda:find_path(G, 0, 10), number=1)
1.3475657280068845

It really shouldn't take more than a second to find a path with a single edge in such a small graph. So why does it take so long?

The way that find_path works is that it generates all simple paths (paths with no repeated nodes) in depth-first order. However, in general there can be exponentially many simple paths in a graph. I constructed the graph G so that it looks like this:

The depth-first search starts by finding the path 0–1–2–3–4–5–6–7–8–9 but then it reaches a dead end:

So the search backtracks a couple of steps and then finds the path 0–1–2–3–4–5–6–7–9–8, but again it reaches a dead end:

You can see that the search will have to visit every path starting with 0 and visiting all of 1 to 9, before it will consider the path 0–10. But there are \$9! = 362,880\$ such paths.

To avoid this exponential runtime, you'll have to use a different approach, for example Dijkstra's algorithm.


Here's concise method to get the coordinates of the zero-crossings that seems to work according to my tests :

def zcr(x, y):
    return x[numpy.diff(numpy.sign(y)) != 0]

Some simple test case :

>>> zcr(numpy.array([0, 1, 2, 3, 4, 5, 6, 7]), [1, 2, 3, -1, -2, 3, 4, -4])
array([2, 4, 6])

This is 2d only, but I believe it is easy to adapt to more dimensions.


Summing the size/count of associations for multiple records

Equivalent, but functional and idiomatic:

def total_leg_count
  active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
end

This pure SQL query should be equivalent and more performant:

def total_leg_count
  active_flights_within_timeframe.includes(:legs).count(:legs)
end


A javascript equivalent for toDictionary (c#)

When providing an object, I don't think it makes sense to pass the index into the callbacks. Rather, pass in the current key.

Also, I think reduce reads much clearer here:

_.dictionary = function (source, keyGenerator, valueGenerator) {
    if (Array.isArray(source)) {
        return source.reduce(function (output, value, index) {
            output[keyGenerator(value, index)] = valueGenerator(value, index);
            return output;
        }, {});
    }

    return Object.keys(source).reduce(function (output, key) {
        output[keyGenerator(source[key], key)] = valueGenerator(source[key], key);
        return output;
    }, {});
};

See it here in action: https://jsfiddle.net/e4g4p7wy/


Get rid of unnecessary code:

    <% @photos.each_with_index do |photo, index| %>
      <% if index.zero? %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

TITLE

      <% else %>

        <img src="<%= photo.image_url(:large) %>" alt="<%= photo.title %>">

      <% end %>
    <% end %>

Move stuff to helpers:

module PhotoHelpers
  def slider_image(photo)
    image_tag photo.image_url(:large), alt: photo.title
  end
end

    <% @photos.each_with_index do |photo, index| %>
      <% if index.zero? %>

          <%= slider_image photo %>

TITLE

      <% else %>

          <%= slider_image photo %>

      <% end %>
    <% end %>


Configuring DI when using four-layer architecture

Actually, in this case you are not configuring ninject in presentation layer, as the presentation layer in case of MVC is cshtml files.

DI engines (like ninject) should be generally configured in the start-up part of application, not in any specific layer. DI has nothing to do with logical decomposition of your application into layers. DI engines only role is to automatically 'distribute' dependencies to objects, usually by interfaces.
In case your application is modular and modules shouldn't see each other, than yes - in this case you probably need per-module DI set-up.

Coming back to ASP.NET MVC, in this case the initial object that are created are controllers and you need to provide implementations for it's dependencies (like you did in the code piece). Now if these dependencies - for exampl HomeService, have their own dependencies, these would need to be registered in the same ninject DI contaier right? So as you see, DI spawns across whole MVC application layers.


The CRUD interface I created for my new app. Creates, updates, deletes, reads and lists

Ad 1) it Is ok to pass id in the Array data of you want to change the id. If you were asking if you can omit the id argument. Then yes but you Will never be able to change id And honestly it becomes more verbose to use. And honestly it Is quite premature to expect this on this generic level.

Ad 2) if "wrong" means empty id or database unreachable and similar, then yes, throw (or pass up) exceptions. But if it means object with given id not found then return null, it is not exceptional to ask for non-existent id, it just leads to a different result. But when database is unreachable, you are unable to say wheteher it exists or not and if it does what are its data and so here exception is appropriate.

Although many will argue here that exceptions are better. I think that exceptions are there to halt program (and do cleanup and notify someone) when something went really bad, not to be used to control flow of your program.

Ad 3) You have (at least) 2 options here:

Dont make it part of the interface. Let implementations take care of this. Could be abstrakt but in generál i advise against abstract classes as they sooner or later start cousing troubles when an implementation wants something done slightly differently And nobody thought about it when the abstract class was designed.

Or,

if it is / has to be part of the interface than it might better return error messages/codes instead of just bool. And the caller should be responsible for calling it first, if He does not call IT than the interface Is being used incorrectly And anything can happen, but that would be a dev's Mistake.

To provide an analogy, it would be like calling Iterator::current() before making sure Iterator::valid() returned true -> undefined behaviour, anything can happen, exception thrown, or nothing, or random element returned, or anything else - simply whatever was the most convenient for that implementation, anyway it is not important because at that point the interface is being misused and the code calling it is wrong and need to be fixed.

Calling it from inside the other method (valid from current, or validateData from create/update) just to make sure that the first method returns true and throw exception otherwise is also wrong because it will get called twice (redundantly) for whoever used the interface correctly.

Although many (especialy PHP) devs may argue that it is better to always throw exception to make sure the dev notices this as soon as possible. I personaly think that you should just write it into the interface's doc comments to state very explicitly that calling create/update without validating the data first is undefined behaviour. How many consumer classes will there be for CrudInterface anyway? One? Two? You make sure that these are correct and then everyone is going to use them, right? So...


Transfer the format of an old string to a new string

First off, I'd rename those two String methods. You obviously had a plan in mind when you added them (i.e. that the strings you'd be checking would be 1 character long), but from a more general perspective, it's fraught with ambiguity.

For instance, is the string "Hello, world" uppercase? Or is it lowercase? Is it sentence-case? Titlecase? So your methods, simple as they are, are perhaps too simple to make sense when applied outside the (narrow) usage you've tailored them for. As such, they probably shouldn't be global String methods. Certainly, you don't need to extend a core class like String just for a simple == comparison.

Also, Ruby convention is to not use an is_ prefix on interrogatory methods like those. The nil? method, for instance, isn't called is_nil?. Same for one?, any?, empty?, include? and so on.

As for your maintain_format method, here's what came to mind:

There's a String#chars method, which'll give you an array of chars - no need for split
Instead of zipping, use a loop and use an index - characters in a string can be accessed just like elements in an array.
And if you're going to loop, no need to loop further than the shortest of the two strings. Or, if you zip the arrays like you do right now, make sure you break the loop when one string or the other "runs out"
You only need to check for uppercase. Everything else gets downcased by default. A character can only be upper or lowercase, so if it's not uppercase, you already know that it's lowercase; no need for extra ifs (but see the update below)

I'd suggest something like

def maintain_format(template, string)
  string = string.downcase              # do this right away
  template = template[0..string.length] # shorten the template, if necessary
  template.chars.each_with_index do |char, index|
    next unless char == char.upcase     # skip lowercase chars
    string[index] = string[index].upcase
  end
  string
end

Perhaps there's a smarter way to detect upper-/lowercase chars, but I couldn't quite think of one that'd be as simple and handle unicode etc.

Lastly: Naming (again). maintain_format is a bit off to me; you're applying a format, copying a format, or something along those lines. (The title of your question also calls it "transfer" rather than "maintain". But transfer would suggest that one string loses its format, when it's applied to the other, so it's not quite right either.)

Ironically, it might make more sense to add this method to String, since it's somewhat more generally applicable. Besides, a call like template.assimilate(other_string) (besides sounding ominous, would make it much clearer which string is the template, and which string will be changed. Right now, it can quickly become confusing which argument is which. But again, better naming might alleviate that.

Update: As 200_success rightly points out in the comments, it's surprising that a string that's longer than the template string gets downcased rather than simply keep whatever case it had. And code shouldn't surprise.

Hence it might be better to do this:

def maintain_format(template, string)
  string = string.dup  # still want a duplicate to work on
  template = template[0..string.length]
  template.chars.each_with_index do |char, i|
    string[i] = char == char.upcase ? string[i].upcase : string[i].downcase
  end
  string
end

You can still achieve the original behavior by simply downcasing the string yourself before passing it to the method.


2D lattice with fixed boundary condition

Testing script from a few days ago:

import numpy as  np

original:

def CML2d(x):
    eps = 0.3
    r = 3.9
    xn = np.zeros(N+1, float)
    for i in range(1, N+1):
        if i>L and i<=(L-1)*L:
            if i%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
            elif i%L==0:
                xl, xr = x[i-1], 0.
                xu, xd = x[i-L], x[i+L]
            else:
                xl, xr = x[i-1], x[i+1]
                xu, xd = x[i-L], x[i+L]
        elif i>1 and i<L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = 0., x[i+L]
        elif i>(L-1)*L+1 and i<L*L:
            xl, xr = x[i-1], x[i+1]
            xu, xd = x[i-L], 0.
        elif i==1:
            xl, xr = 0., x[i+1]
            xu, xd = 0., x[i+L]
        elif i==L:
            xl, xr = x[i-1], 0.
            xu, xd = 0., x[i+L]
        elif i==(L-1)*L+1:
            xl, xr = 0., x[i+1]
            xu, xd = x[i-L], 0.
        elif i==L*L:
            xl, xr = x[i-1], 0.
            xu, xd = x[i-L], 0.
        value = (1-eps)*r*x[i]*(1-x[i]) + 0.25*eps*( r*xl*(1-xl) + r*xr*(1-xr) + r*xu*(1-xu) + r*xd*(1-xd) )
        xn[i] = value
    return xn

partial attempt to work with 2d x; the intention was to replace all the uses of L with 2d array indexing tests.

def CML2d_1(x):
    eps = 0.3
    r = 3.9
    L,_ = x.shape
    N = L*L
    # xn = np.zeros((L,L), float)
    xn = (1-eps)*r*x*(1-x)
    x = x.flat
    #for i in range(N):
    for j in range(L):
      for k in range(L):
        i = k+L*j
        i1 = i+1
        if i1>L and i1<=(L-1)*L:
            if i1%L==1:
                xl, xr = 0., x[i+1]
                xu, xd = x[i-L], x[i+L]
        ....
        #value = (1-eps)*r*x[i]*(1-x[i])
        value = 0.25*eps*( r*xl*(1-xl) +
                            r*xr*(1-xr) +
                            r*xu*(1-xu) +
                            r*xd*(1-xd) )
        #xn.flat[i] = value
        xn[j,k] += value
    return xn

But I then realized that I don't need to iterate over all points.  Instead I could just sum subarrays  (similar to the array of taking a 1d diff, x[1:]-x[:-1]:

# x[i+1] = (1-eps)*   r*x[i]*(1-x[i]) +
#          0.25*eps*( r*x[i-1]*(1-x[i-1]) +
#                     r*x[i+1]*(1-x[i+1]) +
#                     r*x[i-L]*(1-x[i-L]) +
#                     r*x[i+L]*(1-x[i+L]) )

def CML2d_2(x):
    eps = 0.3
    r = 3.9
    x2 = r * x * (1-x)
    xn = (1-eps) * x2
    xn[1:,:]  += 0.25 * eps * x2[:-1,:]
    xn[:-1,:] += 0.25 * eps * x2[1:,:]
    xn[:,1:]  += 0.25 * eps * x2[:,:-1]
    xn[:,:-1] += 0.25 * eps * x2[:,1:]
    return xn

then making use of a covolve2d function in scipy.signal:

from scipy import signal
def CML2d_3(x):
    eps = 0.3
    r = 3.9
    in2 = np.zeros((3,3))
    in2[1,:] = 0.25 * eps
    in2[:,1] = 0.25 * eps
    in2[1,1] = (1-eps)
    print(in2)
    x2 = r * x * (1-x)
    res = signal.convolve2d(x2, in2, mode='same', boundary='fill', fillvalue=0)
    return res

testing:

L = 10 #side of 2d lattice
#L = 4
N = L*L #number of sites in 2d lattice
x0 = np.random.uniform(0.1, 0.9, N+1) #initial values for x
x0[0]=np.nan  # test if this is used
res=CML2d(x0.tolist())
print(res)

x2d = x0[1:].reshape(L,L)
res1=CML2d_1(x2d)
print(x0.shape)
print(res1.shape)
print(np.allclose(res1.flatten(), res[1:]))

print(np.allclose(res1, CML2d_2(x2d)))
print(np.allclose(res1, CML2d_3(x2d)))


Indexing columns to make a MySQL query faster

Currently your code scans the spooner_pec table 6 times, once each for the year-based columns, and again for the final result.

You can reduce this to just 2 times by caching the list of years in a temp table:

CREATE TEMPORARY TABLE GotYears (year varchar(10));

INSERT INTO GotYears
SELECT DISTINCT year
FROM spooner_pec

Now you have a small table with just a few years in it, instead of 3,000,000 records. You have scanned the table just once to do that too.

Now use that table to build your SQL select clauses....

SELECT GROUP_CONCAT(CONCAT(
     'max(case when year = ', year, ' then experience_rate end) AS `', year, '-Pen`' )
ORDER BY year ) INTO @sql1 FROM GotYears;

Having made that recommendation, though, I also recommend having an index on the year column which will make the scan a whole lot faster too.

The query is still really ugly ™ but that's a problem in your application and data storage.

Additionally, your final query is horrible, horrible, and horrible. A group-by query with many columns, but only grouping by the policy_id is very messy, and is MySQL specific. The values returned in the other columns are unspecified in terms of behaviour. I hope all your values in all the columns are the same or otherwise your output values are unspecified. It is a problem with your database structure too, that the data is not normalized. Why do you record the same values for the same policies in multiple records? Your database may be a data warehouse, but even then it is a bit of a mess.

You should audit your tables, and reconsider the design and normalization of your tables.

Still, if you apply the changes I suggest (add the year index, and have a single temp table for the year values), then I imagine your query will execute in about 5 seconds instead of 30.


A simple stop watch which I want to extend

Don't use member variables for temporary storage

Your class Timer has a member variable mvSession, which is unnecessary. It is only used in SessionTime(), where it is filled in and returned. No other functions use it. Instead, just declare std::vector<int64_t> mvSession(3) inside SessionTime().

By making it a member variable, you introduced two problems: first, your class now uses more memory than necessary. Second, the function SessionTime() is now no longer reentrant; if two threads would call SessionTime() simultaneously, they would both write to the same mvSession variable, potentially corrupting it.

Use std::chrono::steady_clock for timers

The problem with std::chrono::high_resolution_clock() is that it is not guaranteed what kind of clock it is. It can represent wall clock time, which can jump ahead or forwards because of summer and winter time, leap seconds, the computer suspending and resuming. This is not something you want for a timer where you are interested in a simple duration. For this, you want to use std::chrono::steady_clock, which is guaranteed to be a monotonically increasing clock. Also, your function SessionTime() returns the time in a resolution of seconds, so you don't need a high resolution clock anyway.

Don't use Hungarian notation

There might be some merits to Hungarian notation, but it really isn't necessary to use it for C++, since the compiler will do type checking for you. Moreover, it's easy to use the wrong prefix, and it's hard to come up with a reasonable prefix when you can have complex types.

You are already making mistakes in your code. For example, mtpNow and mtPause are both of type cppTimer::time_point. So the prefix should have been the same. And mtRestart has a different type than mtPause, so their prefixes should have been different. I recommend that you just avoid using Hungarian notation altoghether.

Be consistent with using

You are declaring using seconds = std::chrono::seconds, and use seconds in a few places, but you also use std::chrono::seconds in a lot of places. Furthermore, you also use std::chrono::minutes and std::chrono::hours, but have not declared an alias for them. In this case, I suggest you don't declare using seconds at all.

I would keep using cppTimer though, since it basically selects which clock to use. That makes it easier to change the clock later by just changing one line of code. I would write using clock = ... though, to be consistent with the C++ library itself.

Don't cast to seconds too early

Instead of seconds mtRestart, use cppTimer::duration mtRestart. This will keep the accuracy of the duration to the same as the clock itself. Only cast durations to seconds or other time intervals until the last moment possible. The same goes for the calculation of delay in SessionTime(), just write:

auto delay = now - mtpNow;

Use nouns for variable names, verbs for function names

A variable holds (the value of) a thing, so its name should naturally be a noun. Functions do stuff, so there names should generally be verbs. The function Now() should actually be named Start(). Your function Start() should probably be named Continue(). The function SessionTime() calculates how long the timer has been running for, so probably should be named GetDuration().

Conversely, the variables mtPause and mtRestart should be renamed to nouns as well. They are a bit confusing. Sure, you set mtPause in the Pause() function, but it doesn't describe what the value actually means. The same goes for mtRestart. I would instead write:

clock::time_point StartTime;
clock::time_point PauseTime;
clock::duration PausedDuration;
bool IsPaused;

Now you can rewrite the function Now() to:

void Start() {
    StartTime = clock::now();
    IsPaused = false;
    PausedDuration = {};
}

Remove mtRestart

You are using two variables to handle the timer being paused, mtPause and mtRestart. However, you only need one. In the Pause() function, you indeed just record when this function is called. However, when restarting the timer, instead of adding the duration of being paused to mtRestart, just add that duration to mtpNow instead:

void Start() {
    if(mbIsPause) {
         mtpNow += cppTimer::now() - mtPause;
         mbIsPause = false;
    }
}

This also simplifies SessionTime():

std::vector<int64_t> SessionTime() {
    auto end = mbIsPause ? mtPause : cppTimer::now();
    auto tp = std::chrono::duration_cast<std::chrono::seconds>(end - mtpNow);
    ...
}

Also, since mtPause is only ever 0 when you didn't pause, you can use that to signal whether the timer is paused instead of having bool mbIsPause.

Another option is @user673679's suggestion of storing only the start time and the accumulated elapsed time so far. You would then use the start time being equal to {} as a signal that the timer has not been started.

Just return a std::chrono::duration

When you want the elapsed time, I would avoid having the Timer class be responsible for converting the duration to a vector of integers representing hours, minutes and seconds. It reduces the accuracy of your timer. Instead, I would just return a std::chrono::duration, and have the caller decide whether it wants to convert that to something. It also is much more efficient than having to construct a std::vector<int64_t>.

Try to make it behave reasonable in all situations

One issue with your code is that it only gives reasonable results for SessionTime() if you have called Now() at least once. You didn't initialize mtpNow, and even if it was value-initialized to zero, then SessionTime() will return the time that has passed since the epoch.

If you want the Timer to behave like it was started at construction time, then initialize mtpNow to cppTimer::now(). If you want it to behave like it was paused, then ensure both mtpNow and mtPause are initialized to the same value (I suggest just using {}), and that mbIsPause is true.

Make it work like a real stopwatch

As already suggested by others, it helps to think of a timer as a stopwatch. A real stopwatch starts in a stopped state, showing an elapsed time of zero. Then, you can start and stop the timer mechanism with buttons. Usually, there is a separate button to reset the stopwatch to its initial state. By making the class act like something a lot of people are already familiar with, the code is easier to understand for others.

Reworked code

Here is an example of what the code would look like with my suggestions applied, as well as @user673679's way of storing the elapsed time between previous start and stops of the clock:

#include <chrono>

class Timer {
  using clock = std::chrono::steady_clock;
  clock::time_point StartTime = {};
  clock::duration ElapsedTime = {};

public:
  bool IsRunning() const {
     return StartTime != clock::time_point{};
  }

  void Start() {
    if(!IsRunning()) {
      StartTime = clock::now();
    }
  }

  void Stop() {
    if(IsRunning()) {
      ElapsedTime += clock::now() - StartTime;
      StartTime = {};
    }
  }

  void Reset() {
    StartTime = {};
    ElapsedTime = {};
  }

  clock::duration GetElapsed() {
    auto result = ElapsedTime;
    if(IsRunning()) {
      result += clock::now() - StartTime;
    }
    return result;
  }
};
```


Implementing `concat` using `foldTree` on Rose Tree

edit: indeed, (++) will cause perfomance degradation on degenerate left-leaning trees. This is overcome with

-- toList = treeFold (\x y -> x ++ (foldr (++) [] y)) (\x -> [x])

toList t = treeFold (\x y -> x . foldr (.) id y) (\x ->([x]++)) t []

but that's equivalent to using the DL monoid mentioned in Petr Pudlák's answer.

Because foldr (++) [] y is just concat y, you can write it down as \x y -> concat (x:y), or, pointfree,

-- treeFold :: (t -> [b] -> b) -> (a -> t) -> Tree a -> b

toList = treeFold ((concat .) . (:)) (: [])

but that's minor. Do take note that treeFold's inferred type is more general than what you specified.

Similarly, to sum the tree of numbers,

sumRoseTree = treeFold ((sum .) . (:)) id

(or replace id with some other number-producing function, in cased the tree carries some other type).


import curses
import pygame

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
player = pygame.mixer.music

When giving modules a shorter name, the usual method is from pygame.mixer import music as player It makes it a little clearer what you are doing.

song = "testshort.mp3"
player.load(song)
player.play()

For anything but a quick script, its recommended that you put your code inside a main function.

screen = curses.initscr()

I recommend that you take a look at the curses.wrapper function. It'll take care of closing curses correctly in the case of an error.

curses.noecho()
curses.mousemask(curses.ALL_MOUSE_EVENTS)
screen.keypad(1)
curses.curs_set(0)
screen.resize(6, 30)
screen.border(0)
screen.addstr(4, 19, "*"*5+"-"*5)
player.set_volume(0.5)
screen.addstr(4, 2, "|")

Your code jumps between curses settings, outputing to the screen, and setting up the player. I recommend dividing it cleanly between these three different tasks.

paused = 0
curses.halfdelay(1)

while True:
            busycheck = player.get_busy()
            if busycheck == 0:

use if not player.get_busy(). Using == to check in the case of bools is considered bad practice. And there is no reason to split across two lines here

                screen.addstr(4, 2, ">")
            char = screen.getch()
            if char == curses.KEY_MOUSE:
                cords = list(curses.getmouse())

There is no reason to call list here.

                mouse_x = cords[1]
                mouse_y = cords[2]

I suggest mouse_x, mouse_y = coords[:2]

                vol_on = mouse_x - 18
                vol_off = 10 - vol_on
                screen.border(0)

Why are you calling screen.border here?

                if mouse_y == 4:
                    if 29 > mouse_x > 18:
                        vol_bar = screen.addstr(4, 19, "*"*vol_on+"-"*vol_off)

You are basically repeating what you had previously. I suggest refactoring so as to share code.

                        volchange = (mouse_x-19)/9.0
                        player.set_volume(volchange)

See how you are effectively changing the same piece of information three times? This suggests you should put all of that in a function.

                    elif mouse_x == 2:
                        if paused == 0:
                            if busycheck == 1:
                                screen.addstr(4, 2, ">")
                                player.pause()
                                paused = 1
                            else:
                                player.play()
                                paused = 0
                                screen.addstr(4, 2, "|")
                        else:
                            player.unpause()
                            screen.addstr(4, 2, "|")
                            paused = 0

Again, your code tangles together in a seeming haphazard manner the different things it does.

This is how I'd do it:

import curses
import pygame
from pygame.mixer.music import music

SONG = "testshort.mp3"

class MusicPlayer(object):
    def __init__(self):
        pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
        music.load(SONG)
        music.play()
        self.paused = False
        self.change_volume(5)

    def change_volume(self, volume):
        self.volume = volume
        music.set_volume( volume / 9.0 )

    def toggle_pause(self):
        self.paused = not self.paused:
        if self.paused:
            music.pause()
        else:
            music.unpause()

def update_screen(screen, player):
    screen.addstr(4, 19, "*" * player.volume + "-"* (10 -player.volume))

    if music.get_busy() or player.paused:
        screen.addstr(4, 2, "|")
    else:
        screen.addstr(4, 2, ">")

def main(screen):
    curses.mousemask(curses.ALL_MOUSE_EVENTS)
    screen.keypad(1)
    curses.curs_set(0)
    screen.resize(6, 30)
    screen.border(0)
    curses.halfdelay(1)

    player = MusicPlayer()

    while True:
        update_screen(screen, player)

        char = screen.getch()
        if char == curses.KEY_MOUSE:
            mouse_x, mouse_y = curses.getmouse()[:2]
            if mouse_y == 4:
                if 29 > mouse_x > 18:
                    player.change_volume(mouse_x - 18)
            elif mouse_x == 2:
                player.toggle_pause()

if __name__ == '__main__':
    curses.wrapper(main)

See how each piece of the code worries about one small thing? We don't mix controlling the music with updating the display.


How many flags do you need? If you can settle with only 32 or 64 different flags instead of a generic-length array of flags, then it would probably be better to allocate the flags in a simple unsigned long, to save your program from all the runtime calculations.

The main efficiency problem in your code is that the compiler can't know the value of the "flag" parameter, so it must calculate division and modulo in runtime to know where to set the flag.

Your code is also limited to one flag set at a time. A common way to write code like this from the caller's side is setFlag (&the_struct, FLAG_THIS | FLAG_THAT);. The whole Windows API uses flags like that, with bitwise OR. If you stored the flags in an unsigned long that wouldn't be a problem, as you wouldn't need to index the flag array. Then the caller wouldn't need to call your function over and over to set several flags at the same time.

Surely it must be ok to group flags into 32/64 bit variables, related to a specific code module?


Vue.js v-if for a checkbox selection of data from a csv

If you want to allow a user to be able to input an optional field after checking that check box it will go like this

You bind the field you want to make optional in your v-model. Upon the click event that optional field should dropdown

HTML

  <input type="checkbox" name="show_organization_fields" v-model="showOrganizationFields">

Organization Fields

    {{field}}
    <select :id="field" :name="field" v-model="mapping[field]" required>
      <option value="">Please Select</option>
      <option v-for="columnName in columnNames" :name="columnName" :value="columnName"  value="">{{columnName}}</option>
    </select>

Javascript

data: null,
      columnNames: [],

      showOrganizationFields: false,

      file: null,
      requiredContactFields: [
        'contact_account_name',
        'contact_first_name',
        'contact_last_name'
          ],
      optionalContactFields: [
        'contact_email',
        'contact_phone',
        'contact_address',
        'contact_city',
        'contact_region',
        'contact_postal_code'
          ],
      requiredOrganizationFields: [
          'organization_account_name',
          'organization_name'
          ],
      optionalOrganizationFields: [
          'organization_email',
          'organization_phone',
          'organization_address',
          'organization_city',
          'organization_region',
          'organization_postal_code'

          ]


Validate IP address and create a registration attempt

Creating a new promise when you already have a promise is considered a Promise anti-pattern.  Instead, you can just use the promise that is already available to you.  This then saves you all the reject handlers because if anywhere in the promise chain, there is a rejection that will propagate back.  So, I think you can just do this:

Authenticator.prototype.register = function(opts) {
  var self = this;
  return  self.__validateIpAddress(opts.ip).then(function() {
      self.__createRegisterAttempt(opts).then(function(attempt) {
         // ...
      });
  });
};


Storing and iterating over multiple NSError pointers

I want to propose a differently structured code, that especially will be easier to adapt for more objects.

NSArray *objects = @[object1, object2, object3];
NSMutableArray *errors = [NSMutableArray array];

[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSError *error;
    [obj methodWithError: &error];
    if(error){
        [errors addObject: @{@"error":error,@"object":obj}];
    }
}];

Now you can iterate over all errors and examine them along with the object the error occurred on.

[errors enumerateObjectsUsingBlock:^(NSDictionary *errorDict, NSUInteger idx, BOOL *stop) {
    NSError *error = errorDict[@"error"];
    id object = errorDict[@"object"];
    if(…){
        //add an appropriate test
    }
}];

you can't add the errors into an array upfront, as

NSError *error1;

will result into a nil-object for the variable error1. NS(Mutable)Arrays can't handle nil objects. Same for dictionaries.
On the other hand my solution allows adding the errors, as it only add them once an existing objects is assigned to the variable error.


Alright, there's a number of issues with the code you posted here. I'll go through it all, and point out issues, step by step:

func (c *Consumer) scanShards(col Collector, streamName string, ids []string) error {

Alright, so we have a *Consumer (exported type), with a non-exported scanShards function. That's fine. The thing I'm slightly baffled by is why the Collector is passed as an argument here. In AWS Kinesis terms, a Collector is what you use to send stuff to Kinesis in a single request. To me, it's sort of like a buffered writer. This collector, however, seems to provide the consumer with data about the shards that you're about to consume. The collector is actually a core dependency of your consumer, it seems. It'd make sense for the consumer to have the underlying collector assigned to a field:

type Consumer struct {
    collector   Collector // Rename needed, though
    cancelFuncs []context.CancelFunc // more on this later!
}

Because you're dealing with streams, I'd strongly recommend you use the context package, too (I know you are, but you're not getting the most out of it - see below). Convention dictates that the context argument comes first, so the function would now look like this:

func (c *Consumer) scanShards(ctx context.Context, streamName string, ids []string) error {

The arguments could probably do with some renaming, but I'm probably the worst person to suggest a good variable name. Anyway, onwards:

    checkpoints, err := col.GetSequenceNumberForShards(streamName, ids)
    if err != nil {
        return fmt.Errorf("error retrieving stored checkpoints for shards: %v", err)
    }

Right, so the "collector" has an exported function getting sequence, and you're expecting the collector to be passed in as an argument. This is kind of weird. It'd make much more sense for someone to use a Consumer object and call something like consumer.GetShards(), because that actually tells me something: I know that I'm working with a consumer that is taking its data from a shards X, Y, and Z.
I've looked at what comes next, but I'll be returning to the checkpoints variable later on. First let me just recommend you look at this package for errors. You're essentially returning a specific error (which is OK), but it's a hard one to detect on the caller-side. The string value of the error still contains all of the raw/initial error value. With the package I linked to, you'd be able to write the same like so:

return errors.Wrap(err, "error retrieving stored checkpoints for shards")

Replace the string constant with an exported constant like so

const ErrRetrievingCheckpoints = "error retrievign stroed checkpoints for shards")
// and use:
return errors.Wrap(err, ErrRetrievingCheckpoints)

And you'll have a much easier time actually detecting what error was returned, without losing the underlying error details.

OK, let's move on to the channel stuff now:

    errc := make(chan error, 1)
    done := make(chan error, 1)
    wg := sync.WaitGroup{}
    wg.Add(len(ids))

Right, So you're creating a waitgroup, and add the length of ids to it, so there's going to be 1 routine per ID. Fine. Then you create an error and done channel, both with a buffer of 1. I'll explain how in a bit, but you can (and should) get rid of the done channel entirely. Having said that, channels like done are generally defined as done := make(chan struct{}): no buffer needed, and an empty struct is defined in the golang specs as a 0-byte type.

The error channel, however, has a bit of a problem: Suppose I'm going to start 10 routines, and I've got 3 errors. The first routine to err will write its error value onto the channel, and be done with it. The second and third routines to fail will be blocked, waiting for you to read the error from the channel. You have the code to do this, so you'll get that error, and the second routine will now write a new error value to the channel. The third routine is still blocked!

What your code does next, is cancel all routines (sort of), and wait for the wg.Wait() call to return. Because the third routine is blocked, this will never happen. You've got a deadlock on your hands. The done channel won't get closed, and thus this function won't return, all because your error channel is blocking routines from completing. That's not what we want. There's a quick (and not always ideal) solution to this problem: increase the channel buffer:

errCh := make(chan error, len(ids) -1) // we'll always read 1, hence -1 is big enough

Of course, we're assuming ids is not empty. Just in case, it's always a good idea to add some basic checks like if len(ids) == 0 and return early.

Still, I'll explain later how we fix this without having to increase the channel buffers too much. For now, let's carry on with the line-by-line review:

    for _, id := range ids {
        seqNum := checkpoints[id]

Yes, I have an issue with this already. checkpoints clearly is a var of type map[string]string. I know this because ids is []string, and the seqNum variable is passed to a goroutine with the type string. Why, then, iterate over a slice, and then perform a lookup in a map to get the corresponding value? Why not simply write:

for id, seqNum := range checkpoints {

That's a lot cleaner, and reduces the risk of someone else looking at your code and adding something like this:

seqNum, ok := checkpoints[id]
if !ok {
    return errors.New("checkpoint missing")
}

Nevermind the risk of someone changing the GetSequenceNumberForShards function to not return an error if not all id's were found! Suppose your ids var holds {"foo", "bar", "zar", "car"}, but the checkpoints  map only was returned without the zar key...

For the same reason, you really should replace wg.Add(len(ids)) with wg.Add(len(checkpoints))

Right, onwards, let's get stuck in with the context:

        ctx, cancel := context.WithCancel(context.Background())
        c.cancelFuncs = append(c.cancelFuncs, cancel)

Why? Why on earth? You're creating a cancel context for each routine, and append the cancel func to a slice without a way to retrieve a specific cancel function. The slice is also stored on the Consumer type. The function uses a pointer receiver, so there's a genuine risk of race conditions here! Suppose I do this:

go consumer.scanShards(col1, "foo", []string{"a", "b", "c"})
go consumer.scanShards(col2, "bar", []string{"foo", "bar", "car", "zar"})

Both routines are appending to the same slice of cancel functions. They're both calling all of them blindly, too. These routines are messing things up for eachother. And that's just one example, imagine someone coming along and writing this:

func (c *Consumer) Reset() {
    // restoring some fields
    c.cancelFuncs = []context.CancelFunc{}
    // more fields here
}

These kind of things can be really hard to debug, and your code is very vulnerable to these issues. You may think that the Reset func I've written here is an unlikely scenario, but given that there's nothing in your code that actually removes the cancel values from the slice, your slice will grow, and grow, and grow, and things will get slowed down.

OK, I had to rant about these things somewhat, but remember how I said that you ought to have your first argument be a context? Right, do it, it allows the caller to pass in a context.WithCancel, or context.WithTimeout, for example, so the caller can determine whether they want to/need to wait on your function to return. Secondly: why not have all your routines share the same context?. You're just re-wrapping the Background context anyway. Instead of doing that, I'd simply wrap the context from the argument once (outside the loop):

rctx, cfunc := context.WithCancel(ctx)

If the context passed as an argument gets cancelled, the cancellation will propagate, if you want to cancel the context, call cfunc, and all your routines will receive the cancellation signal (<-ctx.Done()). The caller is unaffected.

So with this in mind, let's rewrite the loop a bit (more improvements to follow below, but what we have thusfar):

func (c *Consumer) scanShards(ctx context.Context, stream string, ids []string) error {
    if len(ids) == 0 {
        return ErrNoIdsProvided
    }
    checkpoints, err := c.collector.GetSequenceNumberForShards(stream, ids)
    if err != nil {
        return errors.Wrap(err, ErrRetrievingCheckpoints)
    }
    if len(checkpoints) == 0 {
        return ErrNothingToCheck // something like this, should be handled properly
    }
    // note ids is irrelevant, checkpoints is the source of truth now
    errCh := make(chan error, len(checkpoints) - 1)
    // we'll get rid of this, but I've not explained how, so it's here still:
    done := make(chan struct{})
    wg := sync.WaitGroup{}
    wg.Add(len(checkpoints))
    // wrap around ctx argument once!
    rctx, cfunc := context.WithCancel(ctx)

    for id, seqNum := range checkpoints {
        go func(ctx context.Context, shardID, startSeqNum string) {
            defer wg.Done()
            if err := c.scanShard(ctx, shardID, startSeqNum); err != nil {
                errc <- fmt.Errorf("error in shard %q: %v", shardID, err)
            }
        }(rctx, id, seqNum)
    }

OK, that's where we are now. Because the rctx is not in the for scope, and is shared by all routines, you can simply write the routine like so:

go func(id, seqNum string) {
    defer wg.Done()
    // note: rctx, not ctx!
    if err := c.scanShard(rctx, id, seqNum); err != nil {
        errCh <- err
    }
}(id, seqNum)

The routine centers around c.scanShard, a function you've not posted, and thus I have no idea what it does (how it uses the context etc...). What is clear to me, though, is that it's an unexported function, and you have control over it. You could just as easily make it into a function that behaves exactly like the routine you wrapped the call in, so you can replace the go func() bit simply with this:

go c.scanShard(rctx, &wg, id, seqNum, errCh)
// given scanShard looks like this:
func (c *Consumer) scanShard(ctx context.Context, wg *sync.WaitGroup, id, seqNum string, errCh chan<- error)

Anyway, the rest of your code is about tying things together:

    go func() {
        wg.Wait()
        close(errc)
        close(done)
    }()

So waiting for the routines to return before closing the channels, which is fair enough, seeing as writing to a closed channel is bad. Closing the done channel here, though is what actually allows your function to return. But does it add any value?

    err = <-errc
    if err != nil {
        for _, cancel := range c.cancelFuncs {
            cancel()
        }
    }
    <-done // Wait for all goroutines to exit.
    return err
}

And this is where things get realy messy: you're first checking the error channel (fair enough), but because you're not sure whether or not you've passed the blocking read (err = <-errCh) because the channel was closed or not, you have to check whether or not you actually have an error. If not, you're still checking the  done channel, completely pointlessly. Even with your code as it stands, the done channel is completely redundant, the error channel already does the same thing.

Get rid of done, even with your current code, it serves no purpose whatsoever.

Alternative approach

I've been ranting plenty for now, and I think this is a decent starting point. When I started looking at your code, my mind did jump to select statements, and using the ctx.Done() to stop calling the scanShard function. I'm not sure if it's actually the better way for this particular case, but it might be worth considering. I'll just include a quick write-up of how I'd write this function using ctx.Done and select to control the flow. It's a bit more verbose, and actually looks more complex than it needs to be IMHO, but it's just to show an alternative approach, that in some cases might be worth considering. I have to say, all code in the answer is untested, and just written as I went along, so typo's and bugs are possible:

package main

import (
    "context"
    "fmt"
    "sync"
)

func (c *Consumer) scanShards(ctx context.Context, streamName string, ids []string) error {
    checkpoints, err := c.collector.GetSequenceNumberForShards(streamName, ids)
    if err != nil {
        // zerolog
        c.logger.Error().Err(err).Msg("Error retrieving stored checkpoints for shards")
        return err
    }

    errc := make(chan error, 1)
    defer close(errc)
    wg := sync.WaitGroup{}
    wg.Add(len(checkpoints))
    rctx, cfunc := context.WithCancel(ctx)
    for id, seqNum := range checkpoints {
        go func(shardID, startSeqNum string) {
            defer wg.Done()
            select {
            case <-rctx.Done():
                // context cancelled, no need to do anything
                return
            default:
                if err := c.scanShard(rctx, shardID, startSeqNum); err != nil {
                    c.logger.Error().Err(err).Msg("Error in shard %q", shardID)
                    errc <- fmt.Errorf("error in shard %q: %v", shardID, err)
                }
            }
        }(id, seqNum)
    }
    go func() {
        // wg cleared -> cancel context
        wg.Wait()
        cfunc()
    }()
    select {
    case <-ctx.Done():
        // ctx was closed after waitgroup, so nothing to do here
        return nil
    case err := <-errc:
        // error -> cancel routines
        cfunc()
        return err // return, this will close channel
    }
}


As Jesse C. Slicer mentioned, because your class seems to encapsulate an IDisposable object (assuming serialPort would be a private field - this would be clearer if you named it _serialPort), it's asking to implement the IDisposable interface.

Thus, instead of a destructor, you would simply have a Dispose method:

public void Dispose()
{
    serialPort.Dispose();
}

Another thing is this LibraryTrace whose Start and End static methods are a testability hinderance. If it's at all possible, I would wrap that with an interface like ILibraryTrace and implement it in a LibraryTraceWrapper : ILibraryTrace class that exposes the static LibraryTrace methods as instance methods - and inject it into the constructor as a dependency - same goes for the SerialPort:

private readonly ILibraryTrace _trace;
private readonly ISerialPort _serialPort;

public ComPortInput(ILibraryTrace tracer, ISerialPort sp, int delay) : base(delay)
{
    // ...
}

This way you could unit test your class and inject mocks as needed.

As for your non-null assertion, that's called a guard clause and it's good because you're failing fast; by throwing in the constructor you thwart the instantiation of your class without a serial port.

I don't know if it's a typo or if it could be an actual issue, but LibraryTrace.Start and LibraryTrace.End are not working off the same string parameter value (you have "ComPortInput" and "ComportInput" - those are not the same string in C#). Given you're passing in the type's name, I would seriously consider passing in typeof(this).Name instead of a magic string. This shields both calls from an eventual rename refactoring.


Counting multiples of 3 up to a given number

Use your brain, not brute force. How would you solve the problem if it were presented in a math test, and you couldn't use a computer?

Your solution requires \$O(x)\$ time; it should be possible in \$O(1)\$.


Generalization of any() function with switchable default parameter for empty iterables

I really think this is a bad idea. A function called any returning True if there not only isn't anything true but even not anything at all... that's just wrong. It sure isn't a "generalization". Shadowing the built-in is not a good idea, either. Maybe just call yours any_or_empty (without a default)?
For the emptiness check, the counting seems like overkill and I think a Boolean is clearer (and probably faster, due to not going through enumerate):
    empty = True

    for item in iterable:
        if item:
            return True
        empty = False

    return empty

Or with a sentinel, to get rid of the assignment in the loop:
    item = sentinel = object()

    for item in iterable:
        if item:
            return True

    return item is sentinel

For best speed, you could just handle the first item yourself and then let the built-in handle the rest:
def any(iterable, *, default=False):
    """Modification of the built-in any() function."""

    it = iter(iterable)
    sentinel = object()
    first = next(it, sentinel)
    if first is sentinel:
        return default
    return bool(first) or _any(it)

Your test code uses the words "truey" and "falsey". That's not Python terminology. See the Python docs, you'll never find those words. It's true and false, as you can for example see at if, Boolean operations and Truth Value Testing.
The name falsey_iterables is ambiguous if not misleading, as it doesn't yield any false iterables. They're all true. They just don't contain anything true. I'd suggest iterables_without_trues. And iterables_with_true instead of truey_iterables for consistency.
Did you have this idea because next, min and max offer a default parameter? In their cases it makes sense, as they rather need non-empty inputs. And meaningful defaults are possible there, for example min with default=float('inf') could be a useful default for the code using the result.


Check if a game of Tic-Tac-Toe has a winner

I would suggest this instead :

public boolean checkWin(){
    boolean diagLTRHasWinner = true;
    boolean diagRTLHasWinner = true;
    for(int j = 1; j < this.size; j++){
        boolean columHasWinner = true;
        boolean rowHasWinner = true;
        for(int i =0; i < this.size; i++){
            columHasWinner = columHasWinner && (board[i][j] == board[i][j-1]);
            rowHasWinner = rowHasWinner && (board[j][i] == board[j-1][i]);
        }
        if ((rowHasWinner && board[j][0] != -1) || (columHasWinner && board[0][j] != -1)){
            return true;
        }
        diagLTRHasWinner = diagLTRHasWinner  && (board[j][j] == board[j-1][j-1]);
        diagRTLHasWinner = diagLTRHasWinner  && (board[this.size - j][j] == board[this.size - j+1][j-1]);
    }
    return (diagRTLHasWinner && board[0][0] != -1) || (diagLTRHasWinner && board[this.size-1][0] != -1);
}

In order to reduce the number of loops, and objects allocated.
Besides the new code does not even count the element in the board, it just checks if we have a valid sequence of X or O, no matter which one, neither how many! It simply detects the end of the game !


Enforce exclusive order of four processes using semaphores

Programs exit instead of wait

Right now, your programs check their semaphore, but if they don't find the value they are expecting, they exit instead of wait.  I think that you should modify your programs to wait until the previous program signals them.  You would need to make the following modifications:

In program #0, initialize each semaphore to the value 1.
In each other program, use semop() to wait for its semaphore to reach value 0.  For example, program #1 waits for semaphore #0's value to become 0, using semop().
Modify each program to actually take a non-zero amount of time to do its work.  I suggest a for loop like this:

for (int i=0;i<10;i++) {
    printf("Executing process #1, iteration #%d.\n", i);
    sleep(1);
}

After each program's work loop, it releases its semaphore using semop().  This causes the semaphore value to transition from 1 to 0, which allows the next program to run.  For example, program #1 releases semaphore #1, causing program #2 to be able to run.
Program #3 cleans up instead of releasing a semaphore.


The trouble with your question is that the code resembles more config than coding and there is nothing wrong with it except that it is not DRY between those 2 files.

It seems that Ext JS supports require as of version 4, so you simply need to extract the common logic/config into a file that you will require into both places.


I'm afraid that I don't know anything about TCP, but I did notice this.

  if (!client.Connected)
  { /*ignore*/ }
  else
  {
     Console.WriteLine("Listener error: " + ex.Message);
  }

Instead of checking for the negative condition, check for the positive. It removes several lines of code and a comment.

if(client.Connected)
{
    Console.WriteLine("Listener error: " + ex.Message);
}


Maze path finder using Depth-First Search algorithm

Set makes for a slow stack
Your use of a Set rather than a stack (array) is slowing everything down. The hashing function needed for Set to add delete and check items is expensive compared to pushing and popping from a stack.
JS does not like managing memory, allocations are expensive. If you use a stack you don't need to shrink it, rather just keep a pointer to the current stack position. That way if it shrinks below half its size it does not need relocation. You only get reallocation of the array each time it grows over double its size and never repeated.
Creating complex object, like arrays is far slower than creating primitive types. The for loop you use needs to create a new array for each position moved to. Every time you add to the toVisit set you create a new array. This all adds up.
Even creating the array chart populating it with characters from from the maze string is overly complex and can be avoided.
Example
The example avoids creating anything by basic types in the while loop. Avoids repeated calculations. Uses stackPos to track the size of the stack rather than push and pop from the stack. For quicker indexing the map is a flat array and coordinates are handled as triplets {x, y, idx}
I would guess its about 10 times faster (depending on the maze complexity) I did not have a maze to test it on so I hope it works :)
function pathFinder(maze) {
    const stack = [], rows = maze.split("\n");
    const size = rows.length, size2 = size * 2, exit = size - 1;
    const map = new Array(size * size);
    const checkMove = (x, y, idx) => {
        if (x === exit && y === exit) { return foundExit = true }
        if (x < 0 || x > exit || y < 0 || y > exit || rows[y][x] === "W") { return false }
        if (map[idx] === undefined) {
            map[idx] = 1;
            stack[stackPos++] = x;
            stack[stackPos++] = y;
        }
        return false;
    }
    var x, y, idx, stackPos = 0, foundExit = false;

    checkMove(0, 0, 0)
    while (stackPos) {
        y = stack[--stackPos];
        x = stack[--stackPos] + 1;  // add one to check next position
        idx = x + y * size;
        if (checkMove(x, y, idx)) { break }
        x -= 2;
        idx -= 2;
        if (checkMove(x++, y, idx++)) { break }
        y += 1;
        idx += size;
        if (checkMove(x, y, idx)) { break }
        if (checkMove(x, y - 2, idx - size2)) { break }
    }
    return foundExit;
}


Optimizing jQuery addclass / removeclass on scroll

You shouldn't be doing so much manipulation of the classes. Instead, you could just add or remove a scrolled-down class to the <body> element. Then specify the rest of the changes using pure CSS.  (For example, you would have a body.scrolled-down nav { … } rule.)


Remove particular element from an array and return indices of other elements

First of all your code doesn't compile.

Second, your code doesn't do what you state - "Remove particular element from an array".

Third, what exactly do you mean by "Remove"? You want to set these elements to null or compact your array? In second case what do you need indexes of other elements for (their indexes will change when you compact your array)?

Ok, now lets start with a declaration of a contract:

You want to get a multivalue result: filtered array and indexes of remaining elements.

public struct Result
{
    public readonly string[] FilteredArray;
    public readonly List<int> IndexesOfRemainingElements;

    public Result(string[] filteredArray, List<int> indexesOfRemainingElements)
    {
        FilteredArray = filteredArray;
        IndexesOfRemainingElements = indexesOfRemainingElements;
    }
}

Now, I'd rewrite your method in this way:

static Result FilterArray(string[] array, string[] input)
{
    var remainingElements = array.Where(i => !input.Contains(i)).ToArray();

    return new Result(remainingElements,
                      remainingElements.Select(i => Array.IndexOf(array, i)).ToList());
}

And finally you can call it:

string input = "Net Sales,COGS";
string[] values = { "Net Sales", "COGS", "COGS%", "Gross Profit", "GP%", "Quantity" };

// Split has an override that accepts params char[]
var result = FilterArray(values, input.Split(','));

Complete example here: https://dotnetfiddle.net/4wbfpC


Return Value

I don't think it's a good idea to return PerfMeasureUtil in start. What would it even be used for? The code would look like this, which doesn't make much sense:

PerfMeasureUtil meassure = new PerfMeasureUtil();
meassure = meassure.start();
int time = meassure.stop("someName");

I could imagine using it as sort of a factory method:

public static PerfMeasureUtil start() {
    PerfMeasureUtil meassure = new PerfMeasureUtil();
    if (env.isDev()) {// || env.isTest()) {
        LOG.log(Level.INFO, "====================================== measurement starts");
        meassure.setStartTime(System.currentTimeMillis());
    }
    return meassure;
}

And then use it like this:

PerfMeasureUtil meassure = PerfMeasureUtil.start();
int time = meassure.stop("someName");

But I would probably prefer to just not return anything.

Dev check

If you want to reduce the amount of environment checks, you could actually use the factory approach from above, and check on object creation if you are in development mode. If not, return a dummy object whose methods do nothing.

Misc

be consistent with your use of this. Currently, you use it sometimes, but not always.
duration doesn't really need to be a field.
I would add a comment on stop to mention what methodName does (that it's only used for logging).


I know you asked for a non-recursive version, but recursion is a natural way to approach this problem.  Here's a compact, though not high-performance, approach:

function nPr(xs, r) {
    if (!r) return [];
    return xs.reduce(function(memo, cur, i) {
        var others  = xs.slice(0,i).concat(xs.slice(i+1)),
            perms   = nPr(others, r-1),
            newElms = !perms.length ? [[cur]] :
                      perms.map(function(perm) { return [cur].concat(perm) });
        return memo.concat(newElms);
    }, []);
}

All we're doing is taking each element, and then appending it to the (r-1) permutations of all the other elements.

It is possible to do this using while and without recursion, though it will be hard to make that approach as terse.  I'll try to take a shot at it later.


OK, so let's see. arr x = [x] is usually called wrap, or just the operator section (:[]) is used. But map can also be written with list comprehension, giving us

sort :: (Ord a) => [a] -> [a]
sort xs = reduce True [[x] | x <- xs]

I find it much more visually apparent that way. We usually use short variable names in Haskell, with the same goal. When I see a variable fw and then not fw I get it that it is a toggle, a flag of some sorts, I don't need to see the long name like forwardorbackwardsflag explaining it to me in words while at the same time obscuring this visually. So we get

  where
    reduce _ []    = []
    reduce fw [xs] = if fw then xs else reverse xs
    reduce fw s    = reduce (not fw) (combine fw [] s)

we make it an internal function to sort, because this is what it is. It has no otherwise uses on its own. It's too tailored for the specific use here. -- (x:[]) is written also [x], which is a lot simpler. -- We don't have to annotate types of everything. Here reduce is defined right under its use site, so we see that the initial value of fw is True. For me, it is self-documenting enough, but YMMV. Next, combine. There's no need to name all those interim entities. The name of the function itself isn't right, it's too generic. What it does, specifically, is process the elements of its input list in pairs:

    rpairs fw acc []       = acc
    rpairs fw acc [x]      = reverse x : acc
    rpairs fw acc (x:y:zs) = rpairs fw (merge fw x y : acc) zs

It also builds its result in reversed order. We can make it an internal function to reduce, so that its argument fw could be referred to in rpairs body. At the same time there is no need in the separate accumulator really, we can just build the result naturally, in lazy fashion:

  where
    reduce _ []    = []
    reduce fw [xs] = if fw then xs else reverse xs
    reduce fw s    = reduce (not fw) (reverse $ pairs s)
      where
        pairs []       = []
        pairs [x]      = [reverse x]
        pairs (x:y:zs) = merge fw x y : pairs zs

For merge to be able to refer to fw it too should be put here as an internal function to reduce. It is usual to split such functions into two like you did, the interface function ("the wrapper") and the internal "worker" function, except that normally the worker is made internal to the wrapper. But here the wrapper itself is too specialized, it reverses its result so is unlikely to be useable in general, so no need for the split. Thus we arrive at:

sort    :: (Ord a) => [a] -> [a]
sort xs = reduce True [[x] | x <- xs]
  where
    reduce _  []   = []
    reduce fw [xs] = if fw then xs else reverse xs
    reduce fw s    = reduce (not fw) . reverse . pairs $ s
      where
        pairs (x:y:t)     = rmerge [] x y : pairs t
        pairs [x]         = [reverse x]
        pairs []          = []

        rmerge acc [] []  = acc
        rmerge acc xs []  = reverse xs ++ acc
        rmerge acc [] ys  = reverse ys ++ acc
        rmerge acc (x:xs) (y:ys)
          | fw && x <= y || not fw && x > y
                          = rmerge (x:acc) xs (y:ys)
          | otherwise     = rmerge (y:acc) (x:xs) ys

There's no shame in calling rmerge with the initial value as we do here, it's just an internal function here, called from another internal function.

But actually the reversals that rmerge performs are unnecessary, because of Haskell's lazy evaluation. merge now becomes a general function, usable in general. pairs too. reduce performs the same processing step on its input iteratively until a condition is met - there's a higher order function until that already captures this pattern. This leads to some more simplification of the code:

sort    :: (Ord a) => [a] -> [a]
sort [] = []
sort xs = head $ until (null . tail) (pairwise merge) [[x] | x <- xs]
                                  -- (reverse . pairwise merge)
pairwise f (x:y:t) = f x y : pairwise f t
pairwise _ t       = t

merge xs []        = xs
merge [] ys        = ys
merge (x:xs) (y:ys)
       | x <= y    = x : merge  xs (y:ys)
       | otherwise = y : merge (x:xs) ys

I think we would need to toggle between <= and < in merge to ensure the sort's stability, if we were to proceed by (reverse . pairwise merge) steps. But, perhaps we can just throw that reverse away.


I don't know whether you wanted to optimize the code for length or speed or "elegance", but here it is as a one-liner:

def Second_Conversion(x):
    return sum(map(lambda i,j: int(i)*j, x.replace('.', ':').split(':'), [3600, 60, 1, 1e-6]))


Reading a data file for performing a FFT

You can use HLint tool to get rid of few extra parentheses, and use <$> instead of liftM:

contents <- B.lines <$> B.readFile filename

Other than that I don't see anything to be improved in your code at low level. To help with high level design there's not enough info in your question. Can you explain what do you want to achieve with your code?


Add classes onclick and then remove them with onfocus event

Here's a step-by-step conversion from your code to the JS-only code of youmightnotneedjquery.com.

function changeClass() {
    document.getElementById("message").className += " dropzone-wrap";
    document.getElementById("dragNdrop").className += " dropzone-content";
}

Your method here can only ever be used to add "dropzone-wrap" and "dropzone-content". Consider a different approach, where you provide the DOM Element and CSS Classes as parameters.

Consider two such methods - one to add the class (from $.addClass()), and one to remove it ($.removeClass()).

// http://youmightnotneedjquery.com/#add_class
function addClass(el, className) {
    if (el.classList)
      el.classList.add(className);
    else
      el.className += ' ' + className;
}

// http://youmightnotneedjquery.com/#remove_class
function removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className);
    else
      el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}

Note that I'd remove the class before adding it, as that code does not protect against long repeated classname strings.

Anyway, let's continue with your code:

window.onload = function() {
    document.getElementById("ToggleTxTDrop").addEventListener( 'click' , changeClass );
}

Using onload works, but it isn't the right way to do it. With jQuery this should be $(window).on('load', function() { ... });... with native Javascript, it isn't much different (.addEventListener).

For the function code itself, create a handler method that uses the addClass() abstraction method to replace your old changeClass() functionality:

function txtDropClicked(evt) {
    addClass(document.getElementById('message'), 'dropzone-wrap');
    addClass(document.getElementById('dragNdrop'), 'dropzone-content');
}

window.addEventListener('load', function() {
    document.getElementById("ToggleTxTDrop").addEventListener( 'click' , txtDropClicked );
});

Now we have your classes being added on click; let's update the onfocus handler in the same fashion:

/* lets remove the previous classes when on focus */
function removeClassesOnFocus(evt) {
    // evt.target is the element that triggered the event. We bound to #message.
    removeClass(evt.target, 'dropzone-wrap');
    removeClass(evt.target.parentNode, 'dropzone-content');
}

// this bit really should wait for `window.load` too.
document.getElementById('message').addEventListener('focus', removeClassesOnFocus);

  If the classes are there nothing should happen

To address that, the removeClassesOnFocus function could be reworked to look up the element if it isn't provided.

function txtDropClicked(evt) {
    removeClassesOnFocus(false);
    addClass(document.getElementById('message'), 'dropzone-wrap');
    addClass(document.getElementById('dragNdrop'), 'dropzone-content');
}

function removeClassesOnFocus(evt) {
    // evt.target is the element that triggered the event. We bound to #message.
    var message = (evt === false) ? document.getElementById('message') : evt.target;
    removeClass(message, 'dropzone-wrap');
    removeClass(message.parentNode, 'dropzone-content');
}

The full converted code:

// http://youmightnotneedjquery.com/#add_class
function addClass(el, className) {
    if (el.classList) { el.classList.add(className); }
    else { el.className += ' ' + className; }
}

// http://youmightnotneedjquery.com/#remove_class
function removeClass(el, className) {
    if (el.classList) { el.classList.remove(className); }
    else { el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); }
}

// When the txtDrop toggle is clicked, add these classes to the message and drag/drop thing.
function txtDropClicked(evt) {
    removeClassesOnFocus(false);
    addClass(document.getElementById('message'), 'dropzone-wrap');
    addClass(document.getElementById('dragNdrop'), 'dropzone-content');
}

// Removes the classes after the message receives focus.
function removeClassesOnFocus(evt) {
    // evt.target is the element that triggered the event. We bound to #message.
    var message = (evt === false) ? document.getElementById('message') : evt.target;
    removeClass(message, 'dropzone-wrap');
    removeClass(message.parentNode, 'dropzone-content');
}

// Attach the click handler to txtDrop toggle when the page loads.
window.addEventListener('load', function() {
    document.getElementById("ToggleTxTDrop").addEventListener( 'click' , txtDropClicked );
    document.getElementById('message').addEventListener('focus', removeClassesOnFocus);
});

It is worth noting that you can use inline functions as handlers, too - and not define txtDropClicked or removeClassesOnFocus. Either way, the point of each method is to perform a single task, and to do that in the most reusable manner possible.


Java creating augmented array of size 400,000,000

The biggest problem I can see with this approach, is that a user can't add or get any index higher than Integer.MAXVALUE.  You might need to parse Strings or use a BigInteger type instead of int for those methods.


Severe code readability issues

Honestly, your code is extremely difficult to follow and I gave up. The most important part about code is readability. Readable code is easier to reason about, easier to maintain, easier to debug, and, especially relevant here, easier to get other people's opinions on. I would very much like to give you advice on how to improve your functions - but I can't. I have no idea what they're doing now. They're simply inscrutable.

It also isn't enough that you understand what this code does right now. What if you need to go back to this code in a week? In 3 months? In a year? Will you remember what it does then? Even well-commented code with good names sometimes becomes hard to understand once you forget the context of when it was written. Poorly named, uncommented code is just setting yourself up for lots of confusion and frustration. At best.

I cannot stress this enough. Read up on the python style guide, especially for its conventions for naming and comments.

As far as examples of the above. We have:

def CreateBoard(r, c, b, n):

What are r, c, b, and n? I can't even tell from the body of the function. Avoid single-letter variable names unless used in a context where they are truly trivial (e.g. iterating over a range with i or _ is fine).

Function names should be snake_case, not CamelCase, and should describe what the function actually does. Certainly Diag1 and Diag2 are not helpful at all. Which one checks which kind of diagonal? What arguments do they take? What do they return?

docstrings belong inside the function:

def print_board(b):
    """This function takes the parameter board(b), prints
    the board and then returns the board."""

When you need a comment to describe what your variable name names, that's a good indicator that you should just change your variable name. Once you do that, that doc string becomes pointless:

def print_board(board):
    ...

It's pretty clear that a function called print_board that takes a board will print it. And if it doesn't do that, then it should be renamed. somewhere.

The meaning of this docstring:

"""The following Check function takes the parameter board. Within this  """
def check(board, n):

eludes me completely. Also check suggests that we're checking something, but check is doing all sorts of things, involving taking user input. It also takes an argument n which it immediately shadows internally, and it's unclear if that's intentional or not.

WinningCon either explicitly returns True or implicitly returns None - it gives no indication as to who won. It has a variable (loop1) that isn't used.

I would strongly, strongly suggest rewriting your code with PEP-8 in mind, providing better variable names and comments, and using 4-space indentation throughout. Once you do that, you can repost and I will hopefully be able to provide more specific comments as to the actual functionality.


A quick look at bruteForce.

The built-in max computes the maximum value of a collection.
Nested loops can often be combined into a single loop using product, combinations, or combinations_with_replacement, depending on how you need to handle repetitions.
The loops go downwards from 999, but no use is made of this (no early exit) so you might as well let the loops go upwards, which is simpler.

Revised code:

from itertools import combinations_with_replacement

def palindrome(n):
    """Return True if n is a palindrome in base 10."""
    s = str(n)
    return s == s[::-1]

def problem4():
    """Return the largest palindrome made from the product of two 3-digit
    numbers.

    """
    return max(i * j
               for i, j in combinations_with_replacement(range(1000), 2)
               if palindrome(i * j))


Pass values as parameters for modularity
You can make your code a lot more modular if you pass values to functions as parameters instead of hardcoding values in the function itself.
Let's change the bot_login() function to this.
def bot_login(client):
    print("Login...")
    reddit = praw.Reddit(client_id=client["id"],
                client_secret=client["secret"],
                password=client["password"],
                user_agent=client["useragent"],
                username=client["username"])
    print("Login succesfull!")
    return reddit

This way you can call the function like this
client={ "id":"1",
    "secret":"supersecret",
    "password":"password123",
    "useragent":"Chrome 1.0",
    "username":"beepbot"}
bot_login(client)

Your Github_text() function should look something like this.
def github_text(github_url):

Also, notice the lowercase function definitions. You are better off following standards.
Similarly, you should never go with generic variable names such as data text even though they are better than x,y,t1 etc. You can use them if the context is very clear but even so using specific names such as website_response is better.
You can change the function definition of run_bot(reddit) to
run_bot(reddit,subreddit,limit)
This way you can maybe run your bot in other subreddits.
Code is better understood vertically
if any(sentence in submission.selftext for sentence in check_sentences) \
        and submission.author not in users_messaged and not submission.stickied and submission.is_self:

That is very hard to read.
Maybe write it like this
conditions=[any(sentence in submission.selftext for sentence in check_sentences),
            submission.author not in users_messaged,
            not submission.stickied,
            submission.is_self]
if all(conditions):

Please handle edge cases
What happens to the github_text() function if re.search() does not return anything? private_message_text is not defined! Probably won't happen but nothing is guaranteed.
Also if you are using Python3 why not use urllib2 instead of urllib. urlopen() seems to be deprecated use urllib2.urlopen() instead.
Use if __name__=='__main__'
It is better to use this format to run code.
if __name__=='__main__':
    main()

It is a good programming habit even if you are not going to import this anywhere.
  if len(users_messaged) > 50:
      del users_messaged[0]
      users_messaged.append(submission.author)
  else:
      users_messaged.append(submission.author)

I don't know what you are trying to do with this piece of code. But it probably does not do what you want. Since you don't want to message the same person again.
Perfomance
The major performance bottleneck you will face is probably in the network and not in your code. (I could be wrong). I am not familiar with the Reddit API. But if it allows you to message a bunch of users at the same time then you should probably generate the user list and message them all at once.
As a side note, you should handle exceptions if there are any. Especially, if you are going to run this code for a long time. You don't want your program to suddenly stop because of a read timeout.


Excel VBA Retrieving a Specific Pattern from String

You can remove a goto - unconditional branches are strongly discouraged and in this case the code fall-through renders it unnecessary.

    If x = 0 Then
        GoTo NextIteration
    Else
        cell.Offset(0, 1).Value = Mid(cell.Value, x, 13)
    End If

NextIteration:

becomes

If x <> 0 Then cell.Offset(0, 1).Value = Mid(cell.Value, x, 13)

This code only works for a specific (hard coded) pattern without any variations. Your example (test case) focuses on numbers, but your pattern also matches aa.bb.ccc.ddd.