Improving function when used from another class

It seems to me like you are really asking about static vs non-static

static

This means that your instance or instance variable is class-bound. No matter how many objects you make, they will all share the same static variable. Take this class with a static variable called InstanceID. What it will do is increment the static variable by one for each object you create

public class StaticVSNonStatic
{
    private static int InstanceID = 0;

    public StaticVSNonStatic()
    {
        InstanceID++;
    }

    public int GetInstanceID() { return InstanceID; }
}

so say that you later create N number of StaticVSNonStatic objects it won't matter which one you call because they will all share the same variable and will output the same value.

StaticVSNonStatic s1 = new StaticVSNonStatic();
StaticVSNonStatic s2 = new StaticVSNonStatic();
StaticVSNonStatic s3 = new StaticVSNonStatic();

var value = s1.GetInstanceID(); // this will be 3

And if we create any more object of StaticVSNonStatic the InstanceID value will just keep on incrementing.

non-static

Simply means a variable or an object that is not declared as static. A variable that is not static is instance-bound, and for each instance you create they will have their own variable. So if we go back to the class above and remove the static keyword the value will always be 1 regardless of which object you are accessing and regardless of how many objects you have.

  So anyway, what are your opinions upon viewing this? Is there a way to make it simpler? Are there any issues that have come up?

It seems like you do not quite understand how and when to create a class to represent an object and you don't fully understand static. But it's ok, OOP is a hard design pattern to grasp. Let's take a look of what you can improve and what makes me say that you don't understand it...

In a few places in your "seperate class" example you write

VoiceChatClass.ListenAudioAgain = false;
VoiceChatClass.AudioDevice = AudioDevices.SelectedItem.ToString();
VoiceChatClass.DeviceInfo =  Audio.Wave.WaveIn.GetCapabilities(VoiceChatClass.waveInDevice);
VoiceChatClass.PlayBackDevices = VoiceChatClass.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

Which are all static variables which you are invoking, but to me it looks like this should be non-static because to me it looks like you should be able to have multiple "unique" VoiceChat objects.

e.g., you should be able to have one VoiceChat object which has ListenAudioAgain set to false and another VoiceChat object which has it set to true. Or you could have two different VoiceChats with different PlayBackDevices. This is the way it should be but is impossible in your case because of the static.

. The first step in making sure we can have multiple "unique" VoiceChat objects is by removing the static keyword from the class, which should give you a class that looks something like this (remember that this is a guess since I can't actually know what the class looks like):

public class VoiceChat
{
    public bool ListenToAudioAgain { get; set; }
    public string AudioDevice { get; set; }
    public DeviceInfo DeviceInfo { get; set; }
    public PlayBackDevices[] PlayBackDevices { get; set; }
}

And you would use this (in your second example) by first creating (or passing it in by your parameters) an instance of the VoiceChat class. In this case we named the instance to voiceChat, and then we access its instance members.

public static void GetAudioDevices(ComboBox comboBox1, ComboBox AudioDevices)
{
    VoiceChat voiceChat = new VoiceChat()

    foreach (MMDevice device in voiceChat.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
    {
        comboBox1.Items.Add(device.FriendlyName);
        Console.WriteLine("{0}, {1}", device.FriendlyName, device.State);
    }

    voiceChat.PlayBackDevices = voiceChat.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);

    for (voiceChat.waveInDevice = 0; voiceChat.waveInDevice < NAudio.Wave.WaveIn.DeviceCount; VoiceChatClass.waveInDevice++)
    {
        voiceChat.DeviceInfo = NAudio.Wave.WaveIn.GetCapabilities(VoiceChatClass.waveInDevice);
        AudioDevices.Items.Add(voiceChat.DeviceInfo.ProductName);
    }

    if (AudioDevices.Items.Count > 0) {
        AudioDevices.SelectedIndex = 0;
    }

    AudioDevices.Items.Add("Wasapi Loopback");

    voiceChat.ListenAudioAgain = false;
    voiceChat.AudioDevice = AudioDevices.SelectedItem.ToString();

    comboBox1.SelectedItem = voiceChat.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).ToString();

    Console.WriteLine(voiceChat.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia));
}

This is a quick introduction so if there's something unclear just let me know and I'll try to clarify.


You should never use Thread.Abort(). If you don't have control over the code that's executing in the thread, then you don't know what will that abort do. It's quite possible it will leave some object in an inconsistent state, or something like that. If you do have control over the code, you should instead use cooperative cancellation using CancellationToken.


Code to create and check a numeric password

A couple of things:

Start using range.

Range is the recommended way to loop in Python.
And you can change your shutdown sequence, and while loop to use it.
This improves the clarity of your code, which is good for when others read it.
And even if no-one else will, it's always good to get good habits.
Reduce the amount of unneeded messages to the end user.
Here less is more.

Seriously, I was used to overly verbose messages when I was on windows.
And then I installed Linux and would most of the time get no feedback.
To change my keyboard layout I use loadkeys dvorak, and I get no message.
I create a file, touch file, and again no message.
The only time I get a message is if that's the intent of the command, ls, or if it's an error.

Honestly you should probably take a leap out of their book.
It's normally best to avoid recursion.

I once made a program that heavily used recursion,
it exceeded the recursion limit and there was no way for me to fix it.
I can assure you I never touched that project again.

Instead I'd use a while loop.
Use getpass.

This removes the need to display a lot of hashes to remove the password from display.
As it never displays in the first place.
Change password to create the password.

This way the method of creating a password is always the same.
Change login to take the password as an argument.

This is as it removes reliance on globals which is always a good thing.
You should check the input is a number, otherwise you program will exit with an error.

from time import sleep
from getpass import getpass # 4

def create_password(): # 5
    password = getpass('Create your password: ') # 4, 5
    try: # 7
        password = float(password)
    except ValueError:
        quit()
    if password > 9999:
        print('Password is invalid, initiating shutdown.')
        for i in range(5, -1, -1): # 1
            time.sleep(1)
            print(i)
        quit()
    return password # 5

def login(password): # 6
    while True: # 3
        password_guess = float(input('Please enter password: '))
        if password_guess == password:
            break # 3
        else:
            print("Wrong. Here's a clue", (password - password_guess) ** 2)

password = create_password()
login(password)

The above shows how I'd change your code if I were to keep the messages you added special code for.
I still think most of your messages are not needed, and so I'd remove more of them.
I also dislike your clue, as it's ridiculously insecure.
And due to floating point inaccuracy I'd store the password as a string.
Resulting in:

from getpass import getpass

def create_password(): # 5
    password = getpass('Create your password: ')
    try:
        float(password)
    except ValueError:
        quit()
    if float(password) > 9999:
        quit()
    return password

def login(password):
    while True:
        password_guess = input('Please enter password: ')
        if password_guess == password:
            break

password = create_password()
login(password)

Finally I'd think about removing the float(password) > 9999.


Prefix Sum in Ruby, Genomic Range Query from Codility

Some notes:

Use 2-space indentation.
[[0,0,0,0]]. Always a space after a comma.
str.split('') - >str.chars
prefix_sums = [[0,0,0,0]]. This kind of implicit structures hinder readability, I'd simply use a hash. A small space penalty (not in big-Oh, though), better readibility.
each_with_index. Use zip instead.
As you say, the problem is about getting partial sums (frequencies). You can implement and use a very generic abstraction (Enumerable#scanl), which can be used in more codility problems.

I'd write this purely functional solution:

def solution(input_str, slice_start, slice_end)
  impact_factors = {"A" => 1, "C" => 2, "G" => 3, "T" => 4}
  frequencies = input_str.chars.scanl(Hash.new(0)) do |freq, n|
    freq.merge(n => freq[n] + 1)
  end

  slice_start.zip(slice_end).map do |from, to|
    difference_count_by_factor = frequencies[to+1].map do |n, count|
      [impact_factors[n], count - frequencies[from][nucleotide]]
    end.to_h
    difference_count_by_factor.reject { |factor, count| count.zero? }.keys.min
  end
end


For an interview, this is bad code. It is \$O(n \log n)\$. But it can be done in \$O(n)\$ time. Your code does not show your skills in that direction. Also, many interviewers (justifiably) will be unhappy for using streams. Streams may look cute but at scale like Gmail, they cause performance problems.


LeetCode: Remove Duplicates from Sorted Array

There is not much to review here. This algorithm looks to be as good as it gets. I don't know how much value there is in nitpicking, but here I go:

Review

The summary tag should be used to describe a type or a type member. Use remarks to add supplemental information (xmldoc summary) -> put the challenge URL in a remarks tag, not in the summary.
The challenge provides an input parameter nums but C# naming conventions don't invite you to use abbreviations. You could/should change its name to numbers.
Your unit test contains a variable with a typo excpected.
Your method is declared public, meaning you should check arguments against null to avoid the nasty NullReferenceException.
You've added alot of inline comments to show how the algorithm works. Considering the simplicity of the algorithm and the presence of unit tests, I feel these comments don't add much value to the code, if any at all //else continue to next item etc.


Refactoring my simple model-view-presenter architecture

I tried it in an IDE and have some addition to the last comment. I agree that you should try

Presenter<V extends View>

plus I would add that you need to switch the signature to

public abstract class View<V, P extends Presenter>

from

public abstract class View<V, P extends Presenter<V>>

That is regarding to make it compile. Additionally, you can discard generics V since it is not used anymore in the View so the final signature would be:

public abstract class View<P extends Presenter>

Then you can get rid of ViewAdapter and the initialize method should work as you want it:

void initialize() {
    this.getPresenter().setView(this);
}


I'm assuming that you want your vector elements to be modifiable through this view, as vec is non-const.
You store a pointer to the underlying vector, but never test it isn't null.  I think it would be better to have it as a reference member.
If you want your view to be as usable as the standard vector, you'll want to provide iterators, and begin() and end() to obtain them.  You may also want implement front(), back() and at().  Methods such as size(), reserve, capacity etc. can simply forward to the contained vector.

Like std::vector, you should override operator[] on const:
const T& operator[](int index) const {
    return (*vec)[(index + offset) % vec->size()];
}

T& operator[](int index) {
    return (*vec)[(index + offset) % vec->size()];
}

Once we've implemented size() or begin()/end(), the streaming operator << uses only the public interface, so it no longer needs to be friend.
Its loop compares (signed) int against (unsigned) size_t (g++ warns about this with -Wall).  Prefer to avoid implicit promotions, so declare i as size_type to match size().  If you're pedantic, that should be vector_view<T>::size_type, which you'll forward from std::vector<T>.  My code below avoids that entirely, by using iterators.

Beware the gotcha when T is bool.  The only thing preventing your code  working on vector<bool> is:
T& operator[](int index);

If you return a std::vector<T>::reference instead, that will do the right thing there.  (std::vector<bool>::reference is a proxy object, not a bool&).
My modified class:
#include <iterator>
#include <vector>

template<typename T>
class vector_view {
    using vector_type = std::vector<T>;

public:
    using value_type = typename vector_type::value_type;
    using allocator_type = typename vector_type::allocator_type;
    using size_type = typename vector_type::size_type;
    using difference_type = typename vector_type::difference_type;
    using reference = typename vector_type::reference;
    using const_reference = typename vector_type::const_reference;
    using pointer = typename vector_type::pointer;
    using const_pointer = typename vector_type::const_pointer;

    // Iterators: I've implemented little more than the minimum to
    // make the test program work.  You could expand this, and also
    // provide a specialization of std::iterator_traits<> for each
    // one.
    struct iterator {
        vector_view& v;
        size_type i;
        iterator& operator++() { ++i; return *this;}
        iterator& operator-- () { --i; return *this;}
        reference operator*() const { return v[i]; }
        bool operator!=(const iterator other) const
            { return &v != &other.v || i != other.i;  }
    };

    struct const_iterator {
        const vector_view& v;
        size_type i;
        const_iterator& operator++() { ++i; return *this;}
        const_iterator& operator-- () { --i; return *this;}
        const_reference operator*() const { return v[i]; }
        bool operator!=(const const_iterator other) const
            { return &v != &other.v || i != other.i;  }
    };

    using reverse_iterator = std::reverse_iterator<iterator>;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;

    explicit vector_view(vector_type& vec, int offset = 0)
        : vec{vec},
          offset{offset}
    {}

    const reference operator[](size_type index) const {
        return vec[(index + offset) % vec.size()];
    }

    reference operator[](size_type index) {
        return vec[(index + offset) % vec.size()];
    }

    void rotate(int rotation_length) {
        auto size = vec.size();
        offset = (offset + size - rotation_length) % size;
    }

    void set_rotation(int rotation_length) {
        offset = rotation_length % vec.size();
    }

    int rotation() const {
        return offset;
    }

    // Iterators
    iterator begin() {
        return iterator{*this, 0};
    }
    const_iterator begin() const {
        return const_iterator{*this, 0};
    }
    const_iterator cbegin() const {
        return begin();
    }
    iterator end() {
        return iterator{*this, size()};
    }
    const_iterator end() const {
        return const_iterator{*this, size()};
    }
    const_iterator cend() const {
        return end();
    }
    // You may wish to implement rbegin/rend and crbegin/crend

    bool empty() const { return vec.empty(); }
    size_type size() const { return vec.size(); }

    // You may also want:
    // reserve(), capacity()
    // clear(), insert(), emplace(), erase(), ..., etc.

private:
    vector_type& vec;
    int offset;
};

// Consider implementing operator==(), operator<() and other
// comparisons (as non-member functions, probably).  You could
// probably use std::mismatch() for that.

// Printing: greatly simplified using range-based `for`.
#include <iostream>
#include <string>
template<typename T>
std::ostream& operator<<(std::ostream& os, const vector_view<T>& view) {
    os << "[";

    std::string separator = "";
    for (auto element: view) {
        os << separator << element;
        separator = ", ";
    }

    return os << "]";
}

// Test program: exercises both `normal` and boolean vectors.
int main() {
    std::vector<char> v{'a', 'b', 'c', 'd', 'e'};
    vector_view<char> view{v};

    for (size_t i = 0; i < view.size(); ++i) {
        std::cout << view << std::endl;
        view.rotate(1);
    }
    std::cout << std::endl;

    for (size_t i = 0; i < view.size(); ++i) {
        std::cout << view << std::endl;
        view.rotate(-1);
    }
    std::cout << std::endl;

    std::vector<bool> bvec{{false, true, true, false, false}};
    auto bview = vector_view<bool>{bvec};

    for (size_t i = 0; i < bview.size(); ++i) {
        bview.set_rotation(i);
        std::cout << bview << std::endl;
    }
}


Some small notes:

Instead of commenting here:

void quicksort (int[] a, int lo, int hi) {
    //  lo is the lower index, hi is the upper index
    //  of the region of array a that is to be sorted
    int i=lo, j=hi, h;

rename the variables:

void quicksort (final int[] a, final int lowerIndex, final int upperIndex)

It's easier to read.

(Check Clean Code by Robert C. Martin, page 53-54 also.)
Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method.

(Effective Java, Second Edition, Item 45: Minimize the scope of local variables. (Google for "minimize the scope of local variables", it's on Google Books too.))
This:

h=a[i];
a[i]=a[j];
a[j]=h;

can be extracted out to a swap method:

public void swap(final int[] arr, final int pos1, final int pos2) {
    final int temp = arr[pos1];
    arr[pos1] = arr[pos2];
    arr[pos2] = temp;
}

Maybe you should provide an easier to use helper method too for the clients:

public void quicksort(final int[] data) {
    if (data == null) {
        throw new NullPointerException("data cannot be null");
    }
    if (data.length == 0) {
        return;
    }
    quicksort(data, 0, data.length - 1);
}

Note the input validation.


Javascript: Google Analytics Track Outbound Page Views

I would write this code like:

Array.prototype
  .slice
  .call(document.getElementsByTagName("a")) // Get all links from the page
  .forEach(function (link) { // Loop through them
    const isExternal = link.hostname != document.location.hostname;  // Check if is external
    const isPDF = link.href.indexOf(".pdf") > -1; // Check is is PDF
    if(isExternal || isPDF){
      link.setAttribute("onClick", "javascript: trackOutboundLink('" + link.href + "');"); // set onClick attribute
    }
  })

Update #1

Using ES6, you can do something like this:

// Get all the links from the page
const links = [...document.getElementsByTagName('a')];

// "Explain what a pdf link is"
const isPDF = link => link.href.endsWith('.pdf');

// "Explain what an external is"
const isExternal = link => link.hostname != document.location.hostname;

// "Explain what links you want to target"
const target = link => isPDF(link) || isExternal(link);

// "Explain what should be done to those links"
const onClick = link => link.setAttribute('onClick', `javascript: trackOutboundLink('${link.href}');`);

// Filter and do the work
links.filter(target).map(onClick);

I would suggest the second method, because it's much more clear, pure and very easy to test.


I'm not sure what's happening on yours but with 10K rows it's doing 1 row per .000090625 seconds (<1 second total) -

Sub test()
Application.ScreenUpdating = False
Dim i As Integer
Dim firstrow As Integer
firstrow = 1
Dim lastrow As Integer
lastrow = 10000
'lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Start = Timer
For i = firstrow To lastrow
    If Cells(i, 1).MergeArea.Count > 1 Then
       Cells(i, 1).RowHeight = 15
    Else: Cells(i, 1).RowHeight = 12.5
    End If
Next
finish = Timer
MsgBox (finish - Start)
Application.ScreenUpdating = True
End Sub

Maybe try a for next loop instead of a do while loop and see if that changes anything?

Nope, I did a do while and it takes the same amount of time, maybe even less?

Do While i < lastrow + 1
    If Cells(i, 1).MergeArea.Count > 1 Then
       Cells(i, 1).RowHeight = 15
    Else: Cells(i, 1).RowHeight = 12.5
    End If
    i = i + 1
Loop

Try Application.ScreenUpdating = False, Application.Calculation = xlCalculationManual, Application.EnableEvents = False and maybe even Application.DisplayAlerts = False - see if those make a difference.

Even making all rows height 90 and running bottom up does 10K rows in less than a second -

For i = lastrow To firstrow Step -1
    If Cells(i, 1).MergeArea.Count > 1 Then
       Cells(i, 1).RowHeight = 30
    Else: Cells(i, 1).RowHeight = 10
    End If
Next

The only other way I could think of not looking for merged cells would be like this -

For i = lastrow To firstrow Step -1
    If Cells(i, 1).Offset(, 1).Column <> 2 Then
       Cells(i, 1).RowHeight = 50
    Else: Cells(i, 1).RowHeight = 20
    End If
Next

But that's no faster.


To be honest it's hard to follow with such abstract class names and POC.  The root of what you are describing is you have a factory method to create one of your classes.  Lucky for you it seems all the factory methods have the same method signature.  We can make this a bit easier.

Need to store the factory methods in a private field to be used by the Init method.  Also adding a "helper" method to make storing the factories easier.

public abstract class BO<TConfig> where TConfig : BOConfigBase
{
    protected TConfig Config { get; set; }
    internal List<BC> _BCs { get; set; }
    private Func<BOConfigBase, BC>[] _factories = new Func<BOConfigBase, BC>[0];

    protected void SetFactories(params Func<BOConfigBase, BC>[] factories)
    {
        _factories = factories;
    }

    public void Init()
    {
        _BCs = _factories.Select(b => b(Config)).ToList();
    }

    public void Process() => _BCs.ForEach(bc => bc.Process());
}

Now BOOne class can call it like

public class BOOne : BO<BOConfigOne>
{
    public BOOne(BOConfigOne config)
    {
        Config = config;
        SetFactories(BCA.Init, BCB.Init, BCC.Init, BCOneA.Init);
    }
}

I'm assuming each BO class would take different BC classes if not then you could constructer inject all the factories.


Clone a linked list with a random pointer

It is indeed possible to spare the map, by the cost of an additional linear pass. A key is to create a cloned list not independently, but interleaved with the original one:

    while node:
        image = LinkedListNode(node.ID)
        image.next = node.next
        node.next = image
        node = image.next

The second pass sets up the random pointers in the cloned nodes:

    while node:
        image = node.next
        image.random = node.random.next
        node = image.next

And the final pass disconnects interleaved lists:

    try:
        while True:
            image = node.next
            node.next = image.next
            image.next = image.next.next
            node = node.next
    except ValueError:
        pass

The exception comes from the last node: image.next is None.


There's quite a bit of repetition:

echo && print with roughly the same arguments - tee is probably better here
error and non-error paths - perhaps use one function to prepend the ERROR: tag and call the other?

It might be best to have the filename first, then any number of message words?  That would make the interface more like echo, for example.
There's also a problem with our use of printf - any % characters in the error message will be interpreted as replacement indicators.  Not what we want.  We could use printf %b to expand escape sequences instead:
# log FILE MESSAGE...
log () {
    local file="$1"; shift
    printf '%b ' "$@" '\n' | tee -a "$file"
}

# log_err FILE MESSAGE...
log_error () {
    local file="$1"; shift
    local message="ERROR: $1"; shift
    log "$file" "$message" "$@" >&2
}

If we do want to have a single function with arguments (e.g. to add more options), then we might want to use the while/case approach of option parsing that's often used at the program level:
#!/bin/bash

set -eu

# log [-e] [-f FILE] MESSAGE...
log() {
    local prefix=""
    local stream=1
    local files=()
    # handle options
    while ! ${1+false}
    do case "$1" in
        -e|--error) prefix="ERROR:"; stream=2 ;;
        -f|--file) shift; files+=("${1-}") ;;
        --) shift; break ;; # end of arguments
        -*) log -e "log: invalid option '$1'"; return 1;;
        *) break ;; # start of message
       esac
       shift
    done
    if ${1+false}
    then log -e "log: no message!"; return 1;
    fi
    # if we have a prefix, update our argument list
    if [ "$prefix" ]
    then set -- "$prefix" "$@"
    fi
    # now perform the action
    printf '%b ' "$@" '\n' | tee -a "${files[@]}" >&$stream
}

There's a non-obvious trick in there that might need explanation: I've used ${1+false} to expand to false when there's at least one argument remaining, or to an empty command when there are no arguments (empty command is considered "true" by if and while).


What improvements can I make to avoid these If statments?

You'll want to look up the Strategy Pattern.

In your specific case, you're probably going to want to do something along these lines (note - I've never worked with ManagedBeans, so I don't know what spanners that throws).

Leave your Car class as normal.  Or, well, you may want to provide specific types for assignments, if possible (So make Colour an actual class, even if it only contains an actual String - just so people can't assign a Make value to it...).

Your CarDAO should be multiple instances.  Something like:

public class CarColorFinderDAOImpl implements CarDAO {

    public Car find(String colorToFind) {
        // search by color here
    }
}

Then your CarFacade actually transforms to something like this:

public class CarFacade {

    private Map<String, CarDAO> finderDAO = new HashMap<String, CarDAO>();

    public Car find(Sring searchValue, String searchColumn) {

       return finderDAO.get(searchColumn).find(searchValue);
    }

    public void registerFinder(String searchColumn, CarDAO finder) {
        finderDAO.put(searchColumn, finder);
    }
}

Which you then call (mostly) as normal from your managed bean.
Please not that there are further abstractions available (such as encapsulating searchValue and searchColumn in some sort of FinderContract object).  But this is a quick basic one to get you started.


This is a small piece of code but few things I'm going to highlight here

When using the col class, it's best practice to have this class under a row class. This creates a grid structure e.g

.col-sm-4

.col-sm-4

.col-sm-4

One thing to note here is that in bootstrap grid structure the total number of columns you can have is 12 . You can read more on that Bootstrap Grids . So these lines defines more than 12 columns and it's abusing bootstrap usage

I can see some Inline css declarations floating about, there isn't anything bad with that but it becomes cumbersome when you have many div's in your page. I suggest defining your css in an external stylesheet

I hope this helps


Pythonic way to manipulate arrays: a case study

Coding style

For starters, read PEP 8, which is the Python style guide. This gives suggestions on whitespace around operators and commas, variable names, and the like. Your code isn’t bad if it doesn’t follow these conventions, but it will slow down more experienced Python programmers reading your code, and might make it harder for you later when you read other people’s Python.

You should also read PEP 257, which explain the Python conventions for docstrings. Rather than including a description for the function on the same line as the def, we put it on a special line inside the function definition.

With those two in mind, I might rewrite your charge function as:

def residual_charge(x):
    """Returns the residual charge of an atom."""
    if x < 4:
        return 4 - x # atom 1
    else:
        return 6 - x # atom 2

The rest of the style changes are only minor, and you can find them yourself.

Opening/closing the file

As far as I can tell, the six lines after you’ve defined charge are the only lines where you’re directly interacting with the file ACF.dat, but you don’t issue a close() command until the end of the script. That can cause problems if the input file is large, or if you want to load multiple files.

I’d make three changes:

Use Python’s with open() ... construction – this keeps all the file handling code in one place, and automatically closes it for you as well.
Wrap this in a function: it keeps the code for processing the file input in one place, and means you can use it again if you want to feed it a different file.
Go through the file a line at a time (you might not need this, but it saves loading the whole file into memory if ACF.dat is large).

So I’d write something like:

def parse_dat_file(filename):
    """Returns a numpy array based on the contents of the input file."""
    # read the file contents
    with open(filename, 'r') as f:
        for line in f:
            parsed_lines.append(line.split())

    # remove unnecessary rows and columns
    parsed_lines = parsed_lines[2:-4]
    parsed_lines = np.array(parsed_lines, dtype=float)
    parsed_lines = parsed_lines[:,0:5]

    return parsed_lines

Doing the necessary calculations

Again, I’d break this into a single function. It separates that block of work from the rest of the file, and makes it easier to organise. This means that if you get the data from another source, you can use the same code untouched.

Some notes:

In Python, a range() starts at 0 by default, so you don’t need to add it. If no start is supplied, it just counts from 0 upwards. You can find out more by typing help(range) at a Python shell.
If the data set is large, you should use xrange() instead. This is faster when you’re using a large range of objects. See What is the difference between range and xrange? for more details.

This is what I get at the end:

def process_lines(lines):
    """Returns the lines with the residual charge and
    interatomic distances computed and added.
    """
    # Calculate residual charge
    v_charge = np.vectorize(residual_charge)
    lines[:, 4] = v_charge(lines[:, 4])

    # Calculate atomic distances
    distances = []
    for i in xrange(len(lines)):
        line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)
        min_dist = np.sqrt(line_sum)
        distances.append(min_dist)

    lines = np.column_stack((lines, dist))
    lines = lines[lines[:, 5].argsort()]

    return

Printing the file

Without wishing to sound like a broken record, put this in a function as well. This one is easy:

def print_data(lines):
    """Prints the parsed and formatted data."""
    for row in lines:
         print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

Script vs. module

At the end of the script, we can add the lines

acf_lines = parse_dat_file('ACF.dat')
print_data(process_lines(acf_lines))

and it will do the printing we originally set out to do.

But now the code has been broken into separate functions, we can use it in other scripts. Say this was atomic.py; then we could write from atomic import residual_charge in another file, and we’d have access to the residual_charge function.

However, when we import this file in another script, we don’t want it to start reading and printing ACF.dat; we just want the definitions. If we put the particular code for ACF.dat in a special if statement, then it only gets run if the file is called directly:

if __name__ == '__main__':
    acf_lines = parse_dat_file('ACF.dat')
    print_data(process_lines(acf_lines))

Now, if we type python atomic.py at a command line, this code gets run and the data is printed. If we use import atomic elsewhere, then we just get the function definitions. You can find out more in What does if __name__ == "__main__": do?

Summary

If I combine everything I’ve done above and put it into a single file, then this is what I’m left with:

#!/usr/bin/python
import numpy as np

def residual_charge(x):
    """Returns the residual charge of an atom."""
    if x < 4:
        return 4 - x # atom 1
    else:
        return 6 - x # atom 2

def parse_dat_file(filename):
    """Returns a numpy array based on the contents of the input file."""
    # read the file contents
    parsed_lines = []
    with open(filename, 'r') as f:
        for line in f:
            parsed_lines.append(line.split())

    # Remove unnecessary rows and columns
    parsed_lines = parsed_lines[2:-4]
    parsed_lines = np.array(parsed_lines, dtype=float)
    parsed_lines = parsed_lines[:,0:5]

    return parsed_lines

def process_lines(lines):
    """Returns the lines with the residual charge and
    interatomic distances computed and added.
    """
    # Calculate residual charge
    v_charge = np.vectorize(residual_charge)
    lines[:, 4] = v_charge(lines[:, 4])

    # Calculate atomic distances
    distances = []
    for i in xrange(len(lines)):
        line_sum = np.sum((lines[i, 1:4] - lines[0, 1:4]) ** 2)
        min_dist = np.sqrt(line_sum)
        distances.append(min_dist)

    lines = np.column_stack((lines, distances))
    lines = lines[lines[:, 5].argsort()]

    return lines

def print_data(lines):
    """Prints the parsed and formatted data."""
    for row in lines:
         print '{0:<3.0f} {1:12.6f} {2:12.6f}'.format( row[0], row[5], row[4])

if __name__ == '__main__':
    acf_lines = parse_dat_file('ACF.dat')
    print_data(process_lines(acf_lines))


Autofiltering and deleting rows two times too slow

The code as is suffers from a few problems, the most obvious at first glance ones being:

Lack of Vertical Spacing

All the code is compressed into very little vertical space. It's not easy to mentally follow along with an infodump. Instead a maintainer would have it easier if they could see logical units in the code.

This can be as easy as adding a single empty line before each section starting with `nFilasActual´.

Lack of Abstraction

This code is indented four levels deep. After the second level of indentation, you should consider extracting the code into a method, just to maintain a cohesive level off semantic abstraction.

Intermingling "high-level" method calls and "low-level" iterations is very much less than ideal. Instead you want code that's in the same procedure to have a roughly equal level of abstraction. This reduces the strain on the reader, because reading requires less context-switching.

Here are a few simplifications I'd make:

Extract Simple Helper Procedures

Since you repeat the following code twice, it's a good candidate for a separate procedure:

Sub SilentDeleteVisibleRows(filteredRange As Range)
    Application.DisplayAlerts = False
    filteredRange.Offset(1, 0).Resize(filteredRange.Rows.Count - 1) _
      .SpecialCells(xlCellTypeVisible).Rows.Delete
    ' This assumes DisplayAlerts was True before calling this method.
    ' Alternatively the state could be stored into a variable.
    Application.DisplayAlerts = True
End Sub

Searching the number of lines is also something you do thrice:

Function NumberOfLines(sheet As Worksheet) As Long
    NumberOfLines = sheet.Cells(Rows.Count, 4).End(xlUp).Row
End Function

You might also want to extract the whole With block into some procedure with a good name to help the readability of the code overall (and reduce the level of indentation, freeing horizontal space).


Writing binding providers in CoffeeScript?

ko.bindingConvenrions.conventions ".person-editor"
   ".person-editor"  :
      'with'   :  myViewModel.person
   ".first-name"     : ( person ) ->
                        value : person.firstName
   ".last-name"      : ( person ) ->
                        value : person.lastName


However, is it optimal?

I don't see wasted operations or opportunities to simplify the main logic itself.

However, "optimal" is a bit tricky term. To begin with, optimal in terms of what? In terms of readability, I think this is fine. In terms of performance, it's not great. Cloning the list of nodes for every path is not efficient. If performance is important to you, then you need to rethink that part. I can think of at least these alternative algorithms:

Use a shared linked list passed down to all method calls, that grows and shrinks as you go deeper or come back higher in the tree. This will avoid the duplication of the entire path.
Use a shared array list passed down to all method calls, and also pass the current depth n. In each method call, overwrite the n-th element, and print the list contents up until the n-th element. This will avoid the duplication of the entire path. For an extra boost, if you know in advance the depth of the tree, initialize the array list with a size big enough to contain the entire path, so it doesn't need to be resized along the way. In fact, instead of an array list, you could use a plain array for best performance.

  Is there room for improvement?

Use interface types in method signatures and variable declarations. For example:

printPaths(Node node, List<Integer> path) { ... }
List<Integer> path = new ArrayList<Integer>();

You can omit the return statement here:

if(node.leftChild == null && node.rightChild == null) {

    System.out.println(path);
    return;

} else {

    printPaths(node.leftChild,new ArrayList<Integer>(path));
    printPaths(node.rightChild,new ArrayList<Integer>(path));
}

And you should add a space in front of the opening paren of the if, and after commas in argument lists, like this:

if (node.leftChild == null && node.rightChild == null) {
    System.out.println(path);
} else {
    printPaths(node.leftChild, new ArrayList<Integer>(path));
    printPaths(node.rightChild, new ArrayList<Integer>(path));
}

Another alternative is to keep the return but drop the else:

if (node.leftChild == null && node.rightChild == null) {
    System.out.println(path);
    return;
}
printPaths(node.leftChild, new ArrayList<Integer>(path));
printPaths(node.rightChild, new ArrayList<Integer>(path));

  Also, am I correct in thinking that the time complexity of this function is O(n)?

Yes. You visit all the n nodes exactly once.

Unfortunately, no, as @Florian explains very well in his answer.
You might want to consider accepting his answer instead.


A quick recap from SO

If you want to implement the Singleton pattern (first read about SOLID, though, and pay special attention to injection), make the constructor private.
Your query method is static, why? it defaults (without the user being able to do anything about this) to the last connection that was established. Are you sure that's what the user wanted? Of course not! But then again, all of the other methods, like execute exhibit the same behaviour, so Everybody will end up working on the same connection, until they run into trouble and revert to using their own instances of PDO.

As ever, everything I have to say about custom wrapper classes around an API like PDO offers, can be read here. What I think of DB wrappers in general can be found here.

If you want to have all current connections available globally, then your code should shift towards a Factory, not a Singleton pattern:

class Factory
{
    private static $connections = array();
    public static function getDB($host, array $params)
    {
        if (!isset(self::connections[$host]))
        {
             self::connections[$host] = new DB($params);
        }
        return self::connections[$host];
    }
}


There's a lot of repeated code in that long if..else.  Here's an idea (code not tested) for shortening it up:

def is_authorized?(controller, action)
  permissions = Rails.application.config_for :admin_auth
  authority = current_admin.authority

  global_auth = permissions.fetch(authority, [])
  return true if global_auth.include? 'all'

  # Note the implicit assumption in this code, and the original code,
  # that global_auth is a Hash if we have not already returned

  ctrl_auth = global_auth.fetch(controller, [])
  ctrl_auth.include? 'all' || ctrl_auth.include? action
end

Please see the inline comment for an assumption your making about the config data.

At a higher level, the deeper reason this code has to be overly complicated and do nil checks and checks for different kinds of data (array or hash) is because the config data structure has no regularity.

The real fix here is probably to wrap that returned data structure in an object that regularizes it, essentially using something similar to the NullObject pattern.  So that your code could then read like this:

permissions = Rails.application.config_for :admin_auth
permissions = ConfiguredPermissions.new permissions

permissions.global_access? || permissions.for?(controller, action)

You can also avoid the if..else in your redirect method:

  def refuse_access_to_admin_site
    flash[:error] = 'Permission denied'

    location = request.referer.present? ? :back : admins_products_path
    redirect_to location
  end


Shell script to calculate the total space consumed by a user by file-size

AWK="/bin/awk"

It's easier and more readable if you just set your PATH to something appropriate.

USERS="`"$AWK" '$7 >= "2002" && $7 <= "2018"' $FILE | "$AWK" '{print $3}' | sort -u`"

Backticks should almost always be replaced by $( … ), which is faster because it does not invoke a subshell.

Literal numbers should not be quoted.  It happens to still do what you want in awk; in some languages it won't.  A bad habit, easily avoided.

There's no need to invoke awk a second time to extract the third field.  Simply pair the action {print $3} with the condition ($7 >= …) that's already there.

It's good form to indent the body of a for block (or any other block).

echo "User $user " | tr -d "\n";

To suppress a newline on echo, use echo -n.

column -t

This has some awkward consequences, like tabs inside of labels ("TotalTABSpace") and unaligned numbers.  printf will give much prettier results.  Both bash and awk provide it.

total/1024/1024/1024

Nothing wrong with this, as such, but 2**30 is useful shorthand for gigabyte.

==============================================================

Bash can generate sequences like this with the idiom printf "=%.0s" {1..62}.  The = is the character and 62 is the count.

You're traversing the file three times and extracting the same information each time.  This is going to get slow as the file grows.  Awk has associative arrays: you can store a subtotal for each user, then iterate and print those subtotals at the end of the awk script, accomplishing the whole thing in one go.

Putting it all together:

/bin/awk -vusrfmt="User %-20s Total Space consumed: %11.6f GB\n" \
         -vsumfmt=$( printf "=%.0s" {1..62} )"\nTotal Space consumed by All Users: %.6f GB\n"  '
  $7 >= 2002 && $7 <= 2018 {
    subtot[$3]+=$4
    tot+=$4
  }
  END {
    for (u in subtot) printf usrfmt, u, subtot[u] / 2**30
    printf sumfmt, tot / 2**30
  }'


When it comes to outputting HTML from PHP, there are a couple of alternatives:

Using a MVC framework which will separate the logic (Controller) from the data (Model) and the output (View).
Include files that contains HTML, and that can use some PHP as well ("Templates"). MVC frameworks normally makes use of this.
For short HTML, I believe there is nothing that beats using PHP's echo function and write the HTML you want manually.

A big problem with your current function is that to output several HTML tags, you'd have to write things that actually belongs together very far apart. For example:

addHTML(array("p", "p"),
  array('class="some"', 'class="other"'),
  array("Lorem ipsum", "dolor sit amet"));

It's not very readable to see that one tag will become
Lorem ipsum
 and the other
dolor sit amet
.

If you really really want to have some self-written PHP function for this, then I suggest putting things that belong together, together. Something like this:

addHTML(array(array("p", "class" => "some", "Lorem ipsum"),
             array("p", "class" => "other", "dolor sit amet")));

However, simply writing this would be so much simpler, and a whole lot easier to read: (Especially for people who are used to reading HTML)

echo '
Lorem ipsum
';
echo '
dolor sit amet
';

(My PHP is a bit rusty but I hope you get the idea)


To add something to Flambino's answer, I'd suggest moving any non-trivial code to the model (code is then easier to test, re-usable and controllers are kept simple):

class User
  def self.new_from_auth(auth)
    attributes = [:first_name, :last_name, :username, :email]
    user_attributes = if auth
      info = auth.extra.raw_info
      Hash[attributes.map { |attr| [attr, info.send(attr)] }]
    else
      {}
    end
    User.new(user_attributes)
  end
end

class UsersController
  def new
    @user = User.new_from_auth(session[:auth])
  end
end


In no particular order:

Your approach to default keyword arguments with the **k is unusual. I’d expect to see something more like:

def ascii_table(table, header=None, align='left', border=False):
    if header is None:
        header = []

Note that I’ve dropped the space between the function name and the opening parens (per PEP 8 style), and also used None as the default for the header parameter – this is to avoid quirks around mutable default arguments.

This style is more in keeping with other Python code, and makes it easier for somebody to see what parameters this function takes. It also makes it easier to spot when somebody is calling this with entirely wrong arguments.
Newlines are cheap! Don’t put stuff on a single line, especially if … else blocks. For example, this block:

if border: printable.append('│ ' + ' │ '.join(printrow) + ' │')
else: printable.append(' │ '.join(print row))

would usually be written more like:

if border:
    printable.append('│ ' + ' │ '.join(printrow) + ' │')
else:
    printable.append(' │ '.join(print row))

That style is more conventional, and makes it easier to see the structure of the code.
Loop over the elements of a list directly, not its indices. For example, this loop:

for i in range(len(header)):
    assert header[i]
    if align == 'center':
        printrow.append(header[i].center(widths[i]))
    ....
    # do stuff with header[i]

could be better written as something like:

for h, w in zip(header, widths):
    if align == 'centre':
        printrow.append(h.center(w))
    ...

Iterating directly over lists is more Pythonic, and generally makes for cleaner code.
Don’t cram too much into a single expression; it becomes difficult to parse and hurts readability. This is on the edge of what I’d consider acceptable:

for i in range(max(map(len, table))):

This is unreadable:

for i in range(max(map(len, table))): widths.append(max(max(map(len, [row[i] for row in table if len(row) > i])), len(header[i]) if len(header) > i else 0))

You should break it across multiple lines.
You can tidy up some of your logical conditions. For example, this:

if i > 0 and i < max(map(len, table)) - 1:

can be reduced to:

if 0 < i < max(len(t) for t in table) - 1

which is a bit easier to read.
This could potentially choke on a large table, because you’re building all the rows in a list printable. I would consider rewriting this as a generator – essentially, replace every printable.append(foo) with yield foo.

Then your function just lazily computes the rows, and passes them to the caller. It’s up to them how they want to use it – whether they want to save it, do some more processing, join it into a string (and then they can choose the newline).

Generators and iteration are a very powerful feature of Python – if you’re not familiar with them already, this PyCon talk is a good introduction.


Your formatting is a little off,  indentation is very important when reading any code.

I fixed the indentation and I also added some new lines in some of your paragraph tags. they are formatted by the browser pretty nicely so you can added new lines in there to make them more readable with out side scrolling and they will still show up the way you intended.

I also took out all your empty lines, because it is formatted nicely and is easily readable, blank lines make it look messy to me.

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>DEdesigns</title>

        <link rel="stylesheet" href="style.css">

DEdesigns

Home

About

Services

Contact

About Me

                    Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
                    when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                    It has survived not only five centuries, but also the leap into electronic typesetting,
                    remaining essentially unchanged

My Work

                                rem Ipsum is simply dummy text of the printing and typesetting industry.
                                Lorem Ipsum has been the industry's standard dummy text ever since the 1500

                                rem Ipsum is simply dummy text of the printing and typesetting industry.
                                Lorem Ipsum has been the industry's standard dummy text ever since the 1500

                                rem Ipsum is simply dummy text of the printing and typesetting industry.
                                Lorem Ipsum has been the industry's standard dummy text ever since the 1500

Services

one

two

three

Contact Me

some contact me stuff goes here

This is my footer


I don't know how fast you expect this to run, but you need to understand that the inner part of your nested loop runs 36 trillion (1000000 * 2000 * 2000 * 3 * 3) times. This means that small changes in the run time of the inner loop will have a large impact on the total run time of the code, turning 1 hour of runtime to years.

Without knowing anything about the domain of your simulation, I can only propose this:

Reduce the number of times the loops run
Parallelize the code, so that you can have multiple threads working on  different parts concurrently.
Optimize the inner loop as much as possible. Perhaps there is some approximation of the calculation you're running that's significantly faster? Is there any way that you can make better use of processor caches or avoid branch mispredictions? Have a look at this latency chart.


Java 8 unit test for third-party data feeds

I am only going to talk about the sports method, from there you should be able to get the info you need for the others as they are all basically the same.

DRY isn't a big priority

As I said in my earlier comment, DRY (don't repeat yourself) principle applies to production code more than unit test code. I think even in general it's easy to take this too far, readability is important, but that's off-topic. Your code however is tough to grasp.

To me, something like the below is more clear. I like to specify "given/when/then" in comments (although usually I do nothing more than // Given, etc.) but it's not necessary.

@Test
public void shouldProcessSports() {

    List<SportsRecord> fakeList = Lists.newArrayList();

    // Given an incoming feed of the sports variety
    String testRecordFeed = constructSportsRecordFeed();
    SportsRecord fakeSportsRecord = new SportsRecord();

    Function<AggregateFeed, List<SportsRecord>> list = AggregateFeed::getSports;

    when(mockAdapter.apply(testRecordFeed)).thenReturn(fakeSportsRecord);
    when(list.apply(dataFeed)).thenReturn(fakeList); // (*) See note below

    // When the processor accepts the feed and exchange
    processor.accept(testRecordFeed, exchange);

    // Then there should be one result and it should be the sports record
    assertEquals(1, fakeList.size());
    assertSame(fakeSportsRecord, fakeList.get(0));
}

Note: I don't have much experience with the :: operator, if AggregateFeed::getSports.apply(dataFeed) or something similar is valid I would prefer that instead of making the list variable.

DRY is still relevant though!

While writing tests like this takes up more space I think it's more important that the test be clear.

All that said I don't think DRY is completely useless in unit tests. Suppose you were doing more checks on fakeList, like making sure it's not null, contains a specified number of elements, etc. I would put all those assertions in a separate method. Basically the assertions that are tangential to what you are testing. For example, you're not specifically testing the list has one element above, the assertion you care most about is that the only element is fakeSportsRecord. You can't really do something like that so you have to assert that the first element is fakeSportsRecord. Anyways, I tend to put these tangential assertions in methods like this:

private static void verifyListExistsAndHasSingleElement(List<?> list) {
    assertNotNull(list);
    assertEquals(1, list.size());
}

Naming might be a little poor.

The name are mostly fine, but I felt like I needed to add more.

fakeList → resultList or outputList
testRecordFeed → incomingRecordFeed or givenRecordFeed
fakeSportsRecord → expectedSportsRecord
list, this is by far the worst. As shown in the note I don't know if this variable is even necessary. Even just function is better because it's a function, not a list.


Separate your logic and site specific functionality like this:

function Router{
    $url = array_values(array_filter(explode('/', strtolower($_SERVER["REQUEST_URI"]))));
    switch($url[0]){
        case "admin": $this->Admin($url);
            break;
        case "article": $this->Article($url);
            break;
        default: displayIndex();
    }
}

function Admin($uri){
    if( !$this->us->isAdmin ) {
        $this->GoToLoginPage();
    }
    array_shift( $uri );
    $department = new Admin( $uri );
}

function Article($uri){
    if( count( $uri ) == 2 ) {
        displayArticle( $uri[1] );
    } else {
        displayError();
    }
}

It's much cleaner, and easier to update.


Sum of maximum primes as another prime below a million

I've just switch my code from List<Integer> to int[] and the time went down from 19 to 11 seconds. This can be done using a loop or more simply with Guava's Ints.toArray().

While unboxing is cheap, you're needing it in the innermost loop. Which brings us to the point that there's no need for 3 nested loops, you're doing it right and I'm not. My code is faster, possibly because of my helper being faster...

public static int get50() {
    int max = 21;
    int prime_max = 953;
    ArrayList<Integer> primes = Helper.getPrimes(1000000);
    for (int len = 21; len <= primes.size(); len += 2) {

Use some constants... all those magic numbers in code are a pain. Btw., optimizing via the given values 21 and 953 saves about nothing.

Sometimes, a loop with decreasing len could be faster, but not here as the resulting length is close to the beginning.

    if (primes.get(len - 1) > 1E6) {

Again, constants please.

You could simplify the code by storing the partial sums and compute p[i] + p[i+1] + ... + p[j] simply as sum[j+1] - sum[i].

        if (primes.get(len + k - 1) > 1E6 || sum > 1E6) {

The first condition can never be true.

        if (Helper.isPrime((int) sum)) {
            if (len > max) {
                max = len;
                prime_max = (int) sum;
            }
            break;
        }

I'm not sure about the break, but I guess that's because of the resulting sum being unique for a given length.

  If possible && If reduces time Then using the new Java 8 methods.This would help me learn it too.

I strongly doubt, using Java 8 features will help, though using Java 8 surely can, because of the new optimizations.

I did some similar optimizations to my code now and the resulting time is 440 ms, where the initialization of my prime helper takes 438 ms (it always sieves up to 128 million and it's hard to change).

As we don't know why is my code faster, I'm adding my loop body taking just a few milliseconds:

for (int len=1; len<primes.length; ++len) {
    for (int i=0; i<primes.length-len; ++i) {
        final int j = i+len;
        if (i>0 && (len&1) == 0) break;
        final long sum = sums[j] - sums[i];
        if (sum>limit) break;
        if (!helper.isPrime(sum)) continue;
        best = len;
        result = sum;
        break;
    }
}


Space and time efficient Algorithm for generating prime numbers

Coding style

First, let me comment on your coding style / readability:

NonPrimeNumbers does not follow Java Naming Conventions. Local variables should start with lower case.

Your variable names are simply bad.

i is the candidate prime number, so its name should reflect that, e.g. candidatePrime.
k should become arrayIndex (as you did when printing the results).
j should become multiple.
When finding the primes, you should also use the variable name bitPosition instead of (i>>1)%32.

Don't reuse variables for two different meanings, as you did with range. Use two different ones, e.g. primesRange and arrayRange.

At mostly all places where you added comments, introduce method calls instead of one big ugly main() method.

(NonPrimeNumbers[k]&(1<<(i>>1)))==0 then should read isPrime(candidatePrime) or isPrime(arrayIndex,bitPosition).
NonPrimeNumbers[j>>6]|=1<<(j>>1) should become setNonPrime(multiple).
and so on.

Of course, NonPrimeNumbers then has to become an instance field instead of a local var.

Performance

You seem to be looking for performance. I won't do a detailed profiling of your program, that task is up to you. But you can check some modifications that might speed up your program (esp. for bigger prime numbers):

Instead of the single for(int i=3;i*i <= range;i+=2) loop you could try two nested loops, with an intermediate check if a prime number is possible:

for (int arrayIndex=0; arrayIndex<arrayRange; arrayIndex++) {
    if (nonPrimeNumbers[arrayIndex] != 0xffffffff) {
        for (int bitPosition = 0, pattern = 1;
             bitPosition < 32;
             bitPosition++, pattern <<= 1) {
            ...
        }
    }
}

Maybe you can mostly do without the candidatePrime variable, just with arrayIndex and bitPosition, only using it when you found a prime.

You have to try what gives you the best performance...


I have some general comments as I'm not too familiar with the Windows API.

Comments that are just tautologies are not very useful
typedef struct is a pointless idiom in C++, as C++ doesn't have tag names
Why are you using unsigned short (2 bytes wide) when the DEVMODE structure uses DWORD (32-bits wide)? In general, you should use the Windows typedef to stay consistent and avoid unnecessary type issues
You have some redundant casts, like in tsGetMonitorCount(). Also C-style casts can sometimes silence warnings which is not what you want
Why does tsGetVideoMode return a bool? I would expect it to return a video mode
The "Fuck you Windows" comment is unprofessional and unlikely to impress any readers of your code. I (and future readers) will also have no idea what the purpose of the comment is, so it's useless altogether


Printing the PID of a program immediately before it runs

Bug
This line:

    argv_copy[argc] = (char *) NULL;

should be:
    argv_copy[argc-1] = NULL;

You are removing one argument so you need to terminate the array at the right place.
Copy unneeded
Instead of:

    execvp(argv[1], argv_copy);

you could do:
    execvp(argv[1], &argv[1]);

and avoid making a copy.


HackerRank Left rotation code using Java 8

String[] nd = scanner.nextLine().split(" ");
        int c;
        int n = Integer.parseInt(nd[0]);

        int d = Integer.parseInt(nd[1]);

First, why declare c here?  You don't use it until much later.  So let's take it out of here and define it closer to its first use.  I would also rename it, as I find c insufficiently descriptive.

Second, why use nextLine this way?  Consider

        int numbersCount = scanner.nextInt();
        int rotationCount = scanner.nextInt();

I don't know that this is any faster, but it's more direct in code.

I would also add

        rotationCount %= numbersCount;

You could do this in the declaration, but I find it more readable separate.

What this does is remove any superfluous rotations.  If we are rotating numbersCount times exactly, we're already done.  Because that's just the original array.  By taking the modulus or remainder, we're getting rid of all those full cycle rotations.  Since that's just wasted time, this purely improves those large rotations at the expense of an extra division for all rotations.

        int[] numbers = new int[numbersCount];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scanner.nextInt();
        }

Again, I wouldn't use nextLine here.  The scanner is perfectly capable of this.  If you want to read line by line, consider going to something like a BufferedReader that works that way.

You have

                if (j==n-1)
                { c=0;}
                else
                { c=j+1;}
                arr[j]=a[c];

So we finally find c.  It's the index into the old array.  But it could have been more readably written

                int originalIndex = (j + 1 == numbers.length) ? 0 : j + 1;

or

                int originalIndex = j + 1;
                if (originalIndex == numbers.length) {
                    originalIndex = 0;
                }

And whatever you do, please don't do things like {c=0;}.  It's hardly any shorter.  It's just different.  Unless different indicates something, it's not helpful.

But I would actually skip the rotation.  Instead, break the output into two pieces:

        for (int i = rotationCount; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }

        for (int i = 0; i < rotationCount; i++) {
            System.out.print(numbers[i] + " ");
        }

This will display the output as rotated without rotating.

Or just read it rotated.

        int rotationPoint = numbers.length - rotationCount;
        for (int i = rotationPoint; i < numbers.length; i++) {
            numbers[i] = scanner.nextInt();
        }

        for (int i = 0; i < rotationPoint; i++) {
            numbers[i] = scanner.nextInt();
        }

Then the output could be something like

        System.out.println(String.join(" ", numbers));

There's no need to rotate at all, much less to rotate one at a time.

class Solution {

    public static void main(String[] args) {
        System.out.println(String.join(" ", readInputRotated());
    }

    public static int[] readInputRotated() {
        try (Scanner scanner = new Scanner(System.in)) {
            int[] rotated = new int[scanner.nextInt()];

            int rotationPoint = rotated.length - scanner.nextInt();
            for (int i = rotationPoint; i < rotated.length; i++) {
                rotated[i] = scanner.nextInt();
            }

            for (int i = 0; i < rotationPoint; i++) {
                rotated[i] = scanner.nextInt();
            }

            return rotated;
        }
    }

}

This also uses the try-with-resources form to manage the Scanner lifecycle without explicitly calling close.

Your original code was \$\mathcal{O}(mn)\$ where \$m\$ and \$n\$ are the number of rotations and the input size.  This is \$\mathcal{O}(n)\$ (because you read the input) and the "rotation" is \$\mathcal{O}(1)\$.


Delete lines from a CSV file that contain fields listed in a text file

[Side note: It's helpful to present complete, working code when asking questions, together with any input files. That makes it easier for us. We can use the same names for files and so on. It makes things easier and less confusing. In the following, I'm just going to show you the basic code with all the irrelevant details stripped out.]

There's no need to walk through the words file line-by-line. We can just load it once into an array at the beginning:

$words = Get-Content WordsFile.txt

And then we can look in that array when we are processing the CSV records. That's pretty simple:

Import-Csv CsvFileIn.txt |
    where TheField -notin $words |
    Export-Csv CsvFileOut.txt

Notes:

where TheField -notin $words is short for where {$_.TheField -notin $words}. That syntax was introduced in PowerShell 3.0 I think.
The -notin operator is case-insensitive. If you want it to be case-sensitive, then use -cnotin instead. (That is the same with all string comparisons in PowerShell: they are all case-insensitive.)
I'm assuming the words file is not huge. If it's huge, then the -notin operator may be too slow because it searches the array record-by-record (it does a "linear" lookup, as we say in the business). If it were huge, it would be better to use a .NET HashSet instead of an array, but if not, there's no need for the extra complexity.


Finding the sum of the digits appearing in the leaves via in-order traversal

Here's a version of the function that I find nicer:

(defn parse [s]
  (apply + (->> s
             (partition-all 2)                 ; iterate pairs of chars in s
             (map (comp str first))            ; leaf node is the first in the pair
             (filter (partial re-find #"\d"))  ; keep only digits
             (map #(Integer/parseInt %)))))    ; turn 'em into ints

I imagine it can be further reduced to be more idiomatic Clojure, but I find this pretty readable.

Important assumption: this algorithm only works if the input is an inorder traversal of a complete binary tree.  If the original tree was not complete, a single inorder traversal is not sufficient to reconstruct it and find the leaves.


Creating an array that loops out on the frontend - Don't Repeat Yourself?

Architecturally, I'm adverse to hard-coding HTML tags within PHP code. If, for example, you wanted to migrate the code base from PHP to another language (Java, Python, Ruby, Go, Haxe,  whatever) then you have to rewrite both the logic (PHP) and the presentation (PHP) code.

Consider decoupling the logic from the presentation so that you can change how the data appears without having to change how the data is retrieved. This simplifies switching implementation languages and opens the possibility to create different views of the same data for different devices.

To do this, you have to create an interface or contract between the logic and the system that renders the logic for the user. Fortunately, this is where XML excels.

Instead of hard-coding <strong>, you would create an XML document that represents the information you want to display. The XML document becomes the contract between the logic and presentation, which allows both to vary independently. Once the XML document is in place you can pass it to an XSLT Processor to generate the desired HTML content.

This offers the following advantages:

Decoupled. The presentation logic moves to XSLT, completely decoupling it from the PHP code.
Migration. Migrating from PHP to another language means the presentation logic need not change.
Devices. It becomes trivial to change the presentation for different devices (use a new template).
DRY. With display logic in a central location, duplicated code is easier to eliminate.
Databases. Many databases now allow constructing XML documents within stored procedures, eliminating complex code readily expressed in SQL.
SaaS. It simplifies creating a SaaS API -- transforming XML to JSON is fairly easy a solved problem.

This has the following disadvantages:

Effort. Migrating to an XML/XSLT solution for presentation takes a lot of work.
Knowledge. Introduces a second programming language (XSLT) into the software.
Developers. Far fewer developers know XSLT than PHP.
XSLT 1.0. Using PHP, the processor is limited to XSLT v1.0 (many great features are in XSLT 2.0).
Bugs. The XSLT Processor has some pesky known bugs, which could be avoided by moving to XSLT 2.0 with the SAXON processor.


Efficient way to iterate over elements of array for matching contents of another array

Your particular example gets 10 times faster by just removing the jQuery and using a for loop and .indexOf() instead of the jQuery versions.  It's also worth stopping the iteration when you find an excluded value since you don't need to look any more once the flag is already set:

var excludeMe = ["in west", "philadelphia", "born and", "raised"];
var needsExclusions = ["philadelphia", "raised"];
var someFlag = true;

for (var i = 0; i < excludeMe.length; i++) {
    if (needsExclusions.indexOf(excludeMe[i]) !== -1) {
        someFlag = false;
        break;
    }
}

Here's a jsperf that illustrates the speed difference: http://jsperf.com/exclusion-test

If you had a much large data set, then it might pay off to put the needsExclusions values into an object to serve as a direct lookup index (faster than array.indexOf()), but that's probably only faster when the list gets a lot longer because there's setup overhead to build the initial index.


A little "infile" Asynchronous Module Definition

I re-read your code several things, I can't say I would want to use it.

Requiring the parameters to be modules seems neat with 1 module or 2. For larger applications, that would become silly.
The most common use case with require is var xxx = load("Xxx") but you do not provide anything of the sort, in fact, load does not return anything
Having load being called in 2 different ways with 2 different ways of execution is wrong, I would suggest to simply use 2 different functions.
Consider rewriting the if block for "wrong usage" with falsey values and/or add some comment, it is pretty much unreadable now

At the very least I would modify the apply call to a call call, so that this has all the modules :

var ret = module.call(modules);

which makes for

load('utils',[],function(){return {veryUseful:function(){alert('hey')}}});
load(['utils'],function(){this.utils.veryUseful()});

and return ret in case the caller wants to work with the module directly.


C functions for fast IO for competitive programming

On Windows, you'd rather use the console API directly instead of stdio.h. This should increase performance somewhat, since these functions are what getchar etc will end up calling anyhow.

Other issues:

All functions should be declared to take void as parameters, rather than to accept any parameter. If they are properly inlined this should hopefully not have any impact on the program, but in some cases it might mess up the calling convention.
Rather than making a mess with compiler switch #ifdef all over the place, you could in the header file do something like:

#ifdef _WIN32
  #define fast_io_read_char fast_io_read_char_windows
#else
  #define fast_io_read_char fast_io_read_char_linux
#endif

And so on. Then separate the implementation of each function, so that you have one file fastio_windows.c and one fastio_linux.c. You can add both files to linking both no matter, the #ifdef in the header will determine which functions that actually get linked to the binary.
Left shifting the signed type long rev is questionable code - you have to ensure that n is never negative or too large.
Missing #include <stdbool.h> so the code won't compile.
getchar calls incorrectly use char instead of int so the code cannot handle EOF. If you don't intend to handle EOF, then you should still cast the result of getchar() to char - to silence compiler warnings and write self-documenting code that shows that you have considered this.


Relying on short-circuit evaluation instead of using the IF control structure

This is an abuse of short-circuit evaluation.  It's not immediately obvious what the intent is.  Sure, i can eventually see that you're getting an ID, calling Req.abort(), whatever.  But i shouldn't have to decipher a line of code first to figure out what it does.
Conciseness never trumps readability in source code.  (Sure, minifying/packing JS has its benefits.  But you don't write packed/minified code; you start out with decent code and then run a tool on it.)

Since your intent is to do the one thing if the other stuff is true, the code should say that.


Fizzbuzz questions - job interview rejected

You don't use counter, isFizz() or isBuzz(), testFizzBuzz() calls to a fizzBuzz method which doesn't appear to exist. (Passing a boolean argument which seems illogical).
Your code is formatted well, but the points above mean that a reviewer would doubt your competence.
Have you shown us all your code? If not, why not?
Did you compile, run and test your code? If not, why not?


Routine to convert decimal digits to Densely Packed Decimal

Using a tiny (24 byte) lookup table and some multiplication trickery, I was able to make the following implementation (roughly 1.5 times as fast as the original):

        .section .text
        .type bcd2dpd_mul,@function
        .globl bcd2dpd_mul

        # convert BCD to DPD with multiplication tricks
        # input abcd efgh iklm in edi
        .align 8
bcd2dpd_mul:
        mov %edi,%eax           #   = 0000 abcd efgh iklm
        shl %al                 #   = 0000 abcd fghi klm0
        shr %eax                #   = 0000 0abc dfgh iklm
        test $0x880,%edi        # fast path for a = e = 0
        jz 1f

        and $0x888,%edi         #   = 0000 a000 e000 i000
        imul $0x0490,%di        #   = aei0 0000 0000 0000
        mov %eax,%esi
        and $0x66,%esi          # q = 0000 0000 0fg0 0kl0
        shr $13,%edi            # u = 0000 0000 0000 0aei
        imul tab-8(,%rdi,4),%si # v = q * tab[u-2][0]
        and $0x397,%eax         # r = 0000 00bc d00h 0klm
        xor %esi,%eax           # w = r ^ v
        or tab-6(,%rdi,4),%ax   # x = w | tab[u-2][1]
        and $0x3ff,%eax         #   = 0000 00xx xxxx xxxx
1:      ret

        .size bcd2dpd_mul,.-bcd2dpd_mul

        .section .rodata
        .align 4
tab:
        .short 0x0011 ; .short 0x000a
        .short 0x0000 ; .short 0x004e
        .short 0x0081 ; .short 0x000c
        .short 0x0008 ; .short 0x002e
        .short 0x0081 ; .short 0x000e
        .short 0x0000 ; .short 0x006e
        .size tab,.-tab

which was optimized further with help from the folks on Stackoverflow.


Indent the blocks properly.
Define the immutable exclusion lists before the loop.
To enhance readability, maintainability, and to avoid missing typos such as the dot after DODSCAN, which should be a comma, write just one array element per line without commas.

$excludedAccounts = @{
    unique = @(
        'ACCOUNTS - DODSCAN'
        'ACCOUNTS - Domain Admins'
        'ACCOUNTS - LADM_WS_Admins'
        'ACCOUNTS - Tech Enterprise'
    )
    account0 = @(
        'esrxadm1n_esi'
        '#Update'
        'medco_tech'
        'medco_admin'
    )
}

foreach ($row in $csv) {
    if ($row.Type0 -eq 'Domain') {
        $newName = "$($row.Domain0) - $($row.Account0)"
        $isRowExcluded = $newName -in $excludedAccounts.unique
    } else {
        $newName = "$($row.Netbios_name0) - $($row.Account0)"
        $isRowExcluded = $row.'Account0' -in $excludedAccounts.account0
    }
    $row.'Unique Account Name' = $newName
    $row.'Excluded' = [string]$isRowExcluded
}


The Good
I don't write multithreaded code very often, so other reviewers will probably have other comments (read: I'm a multithreading beginner myself), but I like what I'm seeing.

Interlocked.Increment(ref this._number);

I don't see anything that could go wrong with this. This is how I've read a thread-safe increment should be done, using the Interlocked class.

while (Interlocked.CompareExchange(ref this._number, currentNumber - 1, currentNumber) != currentNumber)

Looks good to me. currentNumber belongs to the thread that's running this, so no thread can mess with that currentNumber while currentNumber - 1 or CompareExchange is being evaluated, and again the Interlocked class at play has my full trust.

The Bad
Ignorance is bliss, nothing in sight.

The Ugly
The very first thing that jumped at me, is the abundance of redundant this qualifiers. They're not needed, you have underscores:

int _number;
readonly ManualResetEventSlim _event;

I like the underscore prefix, because it allows me to have a _number field and a number parameter or local variable, for example:
public CountdownLatch(ManualResetEventSlim event)
{
    _event = event;
}

The way I read currentNumber, "current" stands for "current thread's working copy of _number". I find the name number conveys that more succinctly.


Technical Issues

public function __construct()
{
    require_once 'errors.php';
    $this->errorText = $errorText;
}

Will not do what you think it will do.

$val1 = new Validate();
$val2 = new Validate();

The second instance will not include 'errors.php', and thus $errorText will not be defined.

You should probably consider generalizing your error message handling since you might need to have different messages or internationalization.

In other words, your class should probably either return error codes (class constants), or your class should have some kind of facility for requesting a different error message at run time.

If you do stick with your current approach though, consider structuring it something like:

public function __construct()
{
    $this->errorText = $this->getErrorText();
}

private function getErrorText()
{
    include 'errors.php';
}

Your errors.php would then look like:

<?php
return array(
    'something' => 'Some message'
    'somethingElse' => 'some other message',
    ...
);

This would of course mean that the file is included on every object instantiation though.  A different approach could be to store the messages in a static variable the first time they're needed.

Also, while I'm talking about this, errors.php could be a problematic path.  You should probably use something like dirname(__FILE__) . '/errors.php'; so the path is more resistant to outside factors.

if (!method_exists($this, $rule)) {
    throw new Exception("Method {$rule} does not exist");
    exit;
}

There's two issues here:

exit will never be reached
exit shouldn't here

When you throw an exception, you bail out of the current scope up until you hit a catch block.  No code under the throw will be executed.

function f() {
    throw new Exception();
    //No code here is ever excecuted
}

function f() {
    if (...) {
        throw new Exception();
        //Code here is never excecuted
    }
    //Code here will be executed only if the throw above is not reached
}

function f() {
    try {
        if () {
            throw new Exception();
            //Code here is never exceuted
        }
        //Code here is executed if the throw is not reached
    } catch (Exception $e) { }
    //Code here is always executed
}

It gets a bit more complicated than that, but those examples should illustrate the basic behavior.

exit shouldn't be in there anyway though.  Would you actually want script execution to completely stop?  Typically exit should only be used if there is no way to continue the program execution without compromising security or stability.

Imagine if instead of throwing exceptions, you had only the exits there.  This means that no error message would be displayed.  Nothing would be logged.  The code would just bail.

Imagine if someone was using your class based only on the API.  They would have no idea why the code exited.

Typically low level flow control like exiting or redirecting to a different page, so on, should be handled in dedicated "controller" code and not in classes that have responsibilities unrelated to that.

Throwing an exception is the right thing to do here. It allows the code that called rule to decide how to handle it.  rule should only responsible for saying "Hey, ummm, something wen't horribly wrong," not deciding how to handle it.  (In fact, an uncaught exception is basically an exit with debugging information included :p.  You do have to be careful with uncaught exceptions though as you need to make sure they don't get displayed to end clients.  Some exceptions, like PDOException, may contain sensitive data like database credentials.)

Design Issues

Your class does way too much. This is just using a class as a collection of functions. Each validation can be seen as a "responsibility" and thus your class completely violates the single responsibility principle.

Imagine that in the future you want to add a new validation.  How can you do this?  Well, you have two options, both of which are unpleasant:

Edit the source code. What if many people are using your class though, or you're using it across 10 applications?  Suddenly you have a lot of version management going on.  Since you control the class, you could just commit it all to git which would alleviate the synchronization, but what about end-consumers of your code?  This isn't a viable option for them.
Extend the class. This is also a bad option. You would have to change all of the object types in your code to be a MyValidation instead of Validation.  Depending on how widespread this was, this could be a huge chore.

Or, you have a third option.  Scrap your current design and abstract each validation into its own class.  You could have a very simple interface:

interface Validator
{

    /**
     * Validates the given $data against whatever rule(s) the implementation of this
     * interface enforces.  Returns an array of error messages, or an empty array
     * if $data is valid.
     *
     * @param mixed $data
     * @return array An array of error messages
     */
    public validate($data);

}

And then you could build on this:

class RangeValidator implements Validator
{

    private $_from;
    private $_to;

    const ERROR_INVALID_TYPE = 'type';
    const ERROR_OUT_OF_RANGE = 'range';

    //You could pull this into an abstract base class to handle code -> message mapping automatically.
    //That would also allow for easy internationalization later.
    private $_messages = array(

    );

    public function __construct($from, $to)
    {
        //You could make this a lot looser and perhaps put it in methods setFrom and setTo.
        //Just an example.
        if (!is_int($from)) {
            throw new InvalidArgumentException("\$from must be an int.  Given value: '{$from}'");
            }
            if (!is_int($to)) {
                throw new InvalidArgumentException("\$to must be an int.  Given value: '{$from}'");
        }
        $this->_from = $from;
        $this->_to = $to;
    }

    public function validate($data)
    {
        if (is_int($data) || (is_string($data) && ctype_digit($data))) {
            if ($data >= $this->_from && $data <= $this->_to) {
                return array();
            } else {
                return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);
            }
        } else {
            return array(self::ERROR_INVALID_TYPE => $this->_messages[self::ERROR_INVALID_TYPE]);
        }
    }

}

This looks very laborious at first, but it gives you a certain degree of flexibility you didn't have before.  Consider how you add a new validator now.  You just create a new class completely unrelated to any of the other ones.  (Technically it would implement Validator, and perhaps extend an abstract base class.  What I mean though is that it doesn't change any of the other classes.)

In this system, consumption of your code is much simpler too.  How does someone that doesn't have write access to your git repository create their own validator?  They just implement validator in their own namespace rather than in yours.  (Oh, side note, you should probably be using namespaces.)

For simplicity, you could make a "composite" Validator that just ties a bunch of validators together:

class EvenValidator implements Validator
{
    //Imagine that this validates whether or not a number is even
    //(Yes, really weird example :p)
}

class CompositeValidator implements Validator
{

    $this->_validators = array();

    public function __construct(array $validators = array())
    {
        foreach ($validators as $validator) {
            $this->addValidator($validator);
        }
    }

    public function addValidator(Validator $validator)
    {
        $this->_validators[] = $validator;
    }

    public funtion validate($data)
    {
        $errors = array();
        foreach ($this->_validators as $validator) {
            $errors += $validator->validate($data);
        }
        return $errors;
    }

}

You could then use it like:

$range = new RangeValidator(1, 100);
$even = new EvenValidator();
$comp = new CompositeValidator(array($range, $even));

$comp->validate(5); //Returns an array of one message: 5 isn't odd
$comp->validate(2); //Returns an empty array
$comp->validate(222); //Returns an array of one message: 222 out of range
$comp->validate(223); //Two messages: 223 out of range and odd

This is some pretty clumsy usage here.  With more than 5 seconds of thought though, an interface could be designed that allowed for very robust functionality while leaving the code highly maintainable and extensible.

You could even take it a step farther than a composite validator and make a "Form" class that has "Element"s which each have zero or more "Validator"s.  (The approach take by Zend Framework, and I'm sure others).

If you're familiar with any PHP frameworks, you might note that all of that above looks eerily familiar.  In particular, that's a modified version of the Zend_Validate interface from the Zend Framework.

I would suggest you pick a framework, go through the code, figure out how they designed things, and then ask yourself why they designed them that way: what the alternatives could have been and why they picked the path they chose.  If you do look at frameworks for design, make sure you look at more than one.  Though most of the major PHP frameworks/libraries are very well written overall, all of them have at least one area where they far from shine.

Also, if you haven't already, read everything you can find about SOLID.


Refactoring method in ApplicationController for Rails App

I would solve this with a combination of inheritance and duck typing.

Use a base method on a User class root_path to be your entry point.
Pull out that nasty "signed out" user concept to a NullUser object, it is safer than passing nils around or constantly calling user_signed_in? everywhere.
Delegate from the root_path method in the base class to specific_root_path in subclasses once you are past your "early exit" logic.

# application_controller.rb

class ApplicationController < ActionController::Base
  before_filter :set_current_user

  def user_root_path
    @user.root_path
  end

  def set_current_user
    @user = current_user
    @user ||= NullUser.new
  end
end

# user.rb

class User < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  def admin?
    # your admin logic
  end

  def root_path
    return admin_root_url  if self.admin?
    return school_admin_athletes_path if self.role?("School Admin")
    if self.athlete_contributor? &&
      !self.class.name.eql?("Athlete")
      return contributor_dashboard_url
    end

    specific_root_path
  end

  def specific_root_path
    root_url
  end
end

class NullUser
  include Rails.application.routes.url_helpers

  def root_path
    root_url
  end
end

# athlete.rb

class Athlete < User

  def specific_root_path
    if self.username.present?
      edit_vitals_athlete_profile_path
    else
      account_finalize_path
    end
  end

end

# high_school_coach.rb

class HighSchoolCoach < User

  def specific_root_path
    school_admin_athletes_path
  end

end

# college_coach.rb

class CollegeCoach < User
  def specific_root_path
    if self.sports.blank? || self.college_id.blank?
      account_finalize_path
    else
      search_index_path
    end
  end
end

This logic should be equivalent to your original logic, if it isn't, it is pretty close.


Consistent way to handle transient timeouts with WCF calls (timeouts, unreliable network, server load, etc)

One clean up is to consolidate the common code in the catch blocks, by putting it into a function. Other ideas:

5 tries is not many for WCF in general. I would increase it to 50 or so. If you do this, you need a ceiling to multiple applied to to the minimum sleep time.
The milliseconds to sleep should be initialized to a semi-random value: a minimum value, plus a random fraction of an additional amount. Usually I make the additional amount equal to the minimum value. This will keep all your clients from hammering the server with the same rhythm, in the event all clients start at the same time.

With regards to questions:

Make the method generic, with a type parameter defining the return value.
I usually have only two catch blocks, one for FaultException to communicate exceptions explicitly from server to client, and one for Exception, to catch everything else. The Exception block is where you initiate a retry. Read about FaultContractAttribute.
The only good way to allow cancellation is to run all of this in a background thread, possibly using BackgroundWorker.


A quick review:

High Level Overview

This code is okay except for 2 major items: you are not declaring your variables, making them escape all scope. And you use non-English variable names and function names, not every developer speaks Polish, though we should all understand English.

Naming

English is the one true language for naming, please find English equivalents for odejmijCzas, roznicaCzasu etc.

Idioms and Custom

Do not use = new Object();, use = {}

Scope

You must declare everything with var, let, or const
I would declare dateTimeFormat and odejmijCzas inside $(document).ready(function() { to keep the namespace clean

JSHint.com

Consider using http://jshint.com/ to perfect your code, most of these items were found by this tool as well


Analysis of call center employee performance

Yes, functions would be a splendid idea.  However a lot of the
calculations aren't repeated, so it's hard to see which parts could be
factored out usefully.

Apart from that I'd suggest putting the *_target and *_weight
variables into a dictionary or another data frame so that they can be
referred to by name, making it more easy to use them from functions:

parameters = pandas.DataFrame({
    'target': [0.75, 0.75, 0.25, 5.25],
    'weight': [0.30, 0.30, 0.40, 0.00]
}, index = ['csat', 'fcr', 'nps', 'aht']).transpose()

With the data frame above it's easy to select just the parameters for
"csat" for example, using parameters.csat.target or  .weight.

That also makes certain queries more generic:

df['goal_attainment'] = sum(df[name] / parameters[name].target * parameters[name].weight
                            for name in parameters if name not in {"aht"})

A couple of frequently used queries can also be reused,
e.g. df['survey_count'] should likely be cached, similarly for the
comparisons:

survey_count = df['survey_count']
positive_survey_count = df['survey_count'] > 0

(Maybe take a closer look to the Pandas API, e.g. how the data could be
structured with nested names and multi indexes.)


Vectorizing Two Sample Kolmogorov-Smirnov test

I'll take this in chronological order, from the top down. I think I have covered all aspects of the code =)

function [OUT] = k_stest(x1,x2,p)

This looks nice, but it would be better if you had spaces between the input arguments. Also, k_stest is not a very good name, as it's hard to understand what it does just be looking at the name. I read in another review that "You don't need the brackets around the output variable, but you should always include it". I don't necessarily agree,  I usually omit them, but that's just a matter of personal preferences.

% Set default p-value
    if nargin == 2
        p = 0.05;
    end

This is OK. Depending on how you call the function you might add some additional checks. Is p a scalar? Are x1 and x2 vectors? This is not necessary, but can be useful if you want to use this function a long time from now and don't remember the specifics. assert can be very useful here.

% Compute lenghts
    N1 = length(x1);
    N2 = length(x2);

numel (number of elements) is better than length. It's more robust and a lot faster for long vectors.

% Set vector t over which the empirical distribution function will be computed.
    t = linspace(min(min([x1 x2])),max(max([x1 x2])),2*max([N1 N2]));

This is dangerous, and a bit messy.

[x1 x2] assumes both x1 and x2 are row-vectors, i.e. horizontal vectors. A lot of functions in Matlab returns vectors as column-vectors i.e. vertical vectors by default, including the colon operator (:).

If you happen to call this function with two vertical vectors instead of two horizontal vectors, this would fail (due to [x1 x2]).

Instead, you should do:

x12 = [x1(:); x2(:)];
t = linspace(min(x12), max(x12), 2*max([N1, N2]));

This way you're converting x1 and x2 to vertical vectors, and concatenate them vertically, prior to the linspace call. Now you only need one call to max and min.

The way you're initializing D is OK!

% Set c from tabulated values
    if p == 0.10
        c = 1.22;
    elseif p == 0.05
        c = 1.36;
    ...

Comparing floating point values using == is dangerous. For instance 0.1 + 0.2 == 0.3 will return false. Instead, you should compare the values with the desired value, but with some tolerance (for instance eps).

    if abs(p - 0.10) < eps
        c = 1.22;
    elseif abs(p-0.05) < eps
        c = 1.36;

If two values are closer to each other than +/- eps then they are essentially equal.

% Search though the vector t, computing the empirical distribution function for each t,
% and overwriting the statistic if a higher value is found.
    for i = 1:length(t)
        F1 = sum(x1<=t(i))/N1;
        F2 = sum(x2<=t(i))/N2;
        if abs(F2-F1) > D
            D = abs(F2-F1);
        end
    end

You are right, vectorization is the way to go! Use bsxfun to create a logical matrix where each element that satisfy the condition x1 <= t(ii) are true and the others are false. Then sum the entire mask, and take the maximum difference.

mask1 = bsxfun(@le, x1(:), t);
mask2 = bsxfun(@le, x2(:), t);
s1 = sum(mask1) / N1;
s2 = sum(mask2) / N2;
D = max(abs(s1 - s2));

% Compare the statistic to determine if the samples pass or fail.
    if D == -1;
       disp('Error, invalid input vectors')
       return
    elseif D > c*sqrt((N1+N2)/(N1*N2));
        OUT = 0;
    else
        OUT = 1;
    end
end

The check for invalid input vectors should be in the start of the function. I can't see a reason why you want it in the end instead. And as far as I can tell it will never fail (if the input is invalid then you will get an error further up).

Instead of the if and elseif, you can simply do:

OUT = D <= c*sqrt((N1+N2)/(N1*N2));

To sum it all up, your function can be written like this. I've omitted the comment for simplicity. You should include them in your code.

function OUT = k_stest(x1, x2, p)

if nargin == 2
    p = 0.05;
end

% Add check for invalid input vectors!

N1 = numel(x1);
N2 = numel(x2);

x12 = [x1(:); x2(:)];
t = linspace(min(x12), max(x12), 2*max([N1, N2]));

if abs(p - 0.10) < eps
    c = 1.22;
elseif abs(p-0.05) < eps
    c = 1.36;
% Continue with the rest of the values
%
end

mask1 = bsxfun(@le, x1(:), t);
mask2 = bsxfun(@le, x2(:), t);
s1 = sum(mask1) / N1;
s2 = sum(mask2) / N2;
D = max(abs(s1 - s2));

OUT = D <= c*sqrt((N1+N2)/(N1*N2));

end


C# approach to prevent null references in strings

System.String is a class, a reference type. Wrapping it in a value type makes for a pretty confusing start: it's like the opposite of boxing, where a value type is wrapped with a reference type. It's ...awkward.

Value types should be immutable; _theString doesn't immediately strike me as a readonly field:

private string _theString;

And _theString is a very, very bad name - I would have simply gone with _value, like this:

private readonly string _value;

Calling ToString shouldn't have side-effects - here calling ToString is mutating the instance, changing the reference stored in _theString:

public override string ToString()
{
    //perform initialization in case this was created without using the ctor
    return _theString ?? (_theString = "");
}

There is little to no gain in doing this, and it makes your value type violate a fundamental rule: value types should be immutable, no ifs, no buts. I'd change it to this:

public override string ToString()
{
    return _value ?? string.Empty;
}

The only way client code can retrieve the encapsulated value, is by calling ToString - this is practical and useful, but not exactly instinctive. I would expose a getter:

public string Value { get { return ToString(); } }

The Equals(string) implementation relies on implementation details of another method:

return ToString() == "" //we are never 'null'

I don't see a need for an explanatory comment when using "normal" string methods:

return ToString().IsNullOrEmpty();

You have hard-coded "" in a bunch of places - I find string.Empty conveys "" in a more unambiguous way, and I would replace all occurrences of "" with string.Empty.

I think your struct is violating the Single Responsibility Principle, with methods like ReduceTo - I think these members belong as extension methods, extending the String type itself.

Also when writing code at that level, you should make sure every public member has proper XML comments, so that client code consuming it has a bit of documentation in IntelliSense.


Dependency Inversion Priciple

The smell is that your code violates the Dependency Inversion Priciple which reads

  Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

This meas that your API depends on the Load method of the XmlDocument and not an abstraction such as a service like this one.

interface IXmlLoader
{
    XmlDocument Load(string path);
}

In consequence you cannot replace it for testing or use dependency injection and easily exchange it later if necessary. A correct implementation could look like this where you pass the dependency via the constructor. In some cases it might be also a property:

class XmlController
{
    private readonly IXmlLoader _xmlLoader;
    public XmlControler(IXmlLoader xmlLoader)
    {
        _xmlLoader = xmlLoader;
    }

    // Sometimes a property.
    // public IXmlLoader XmlLoader { get; set; }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        await Task.Run(() => _xmlLoader.Load(_appEnvironment.WebRootPath + @"\\user.config"));
        return Ok(xmlDoc);
    }

}

This is just an example. In your real code you should add null checks.

Another smaller smell is the hardcoded string user.config that you should at least configure via a property.