Histogram of a RGB image using OpenCV I wrote some C++ code using the OpenCV library. The program reads the image and plot histograms of Red, Green, and Blue components. I am very new to OpenCV so I need comments and advice. What do you think about my code? Is there any better way to do that? Are there unnecessary parts in my code? Is there any part I should change?

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(){
    Mat image = imread("C:/image.jpg");
    int HistR[257] = {0};
    int HistG[257] = {0};
    int HistB[257] = {0};
    for (int i = 0; i < image.rows; i++)
        for (int j = 0; j < image.cols; j++)
        {
            Vec3b intensity = image.at<Vec3b>(Point(j, i));
            int Red = intensity.val[0];
            int Green = intensity.val[1];
            int Blue = intensity.val[2];
            HistR[Red] = HistR[Red]+1;
            HistB[Blue] = HistB[Blue]+1;
            HistG[Green] = HistG[Green]+1;
        }
    Mat HistPlotR (500, 256, CV_8UC3, Scalar(0, 0, 0));
    Mat HistPlotG (500, 256, CV_8UC3, Scalar(0, 0, 0));
    Mat HistPlotB (500, 256, CV_8UC3, Scalar(0, 0, 0));
    for (int i = 0; i < 256; i=i+2)
    {
        line(HistPlotR, Point(i, 500), Point(i, 500-HistR[i]), Scalar(0, 0, 255),1,8,0);
        line(HistPlotG, Point(i, 500), Point(i, 500-HistG[i]), Scalar(0, 255, 0),1,8,0);
        line(HistPlotB, Point(i, 500), Point(i, 500-HistB[i]), Scalar(255, 0, 0),1,8,0);
    }
    namedWindow("Red Histogram");
    namedWindow("Green Histogram");
    namedWindow("Blue Histogram");
    imshow("Red Histogram", HistPlotR);
    imshow("Green Histogram", HistPlotG);
    imshow("Blue Histogram", HistPlotB);
    waitKey(0);
    return 0;
}

Overall, this is pretty straightforward, easy-to-read code. Nicely done.

As @Loufylouf mentioned in the comments, there is a function in OpenCV that calculates a histogram already - the calcHist function. You'd be better off using that. But it doesn't hurt to try to do it yourself just to see how it's done.

You're calculating the histogram of an image with 8-bit per channel RGB pixels. You only need 256 bins, not 257. You're allocating an extra int for each histogram. That's not a huge problem, but you don't need it. (Unlike C strings, arrays do not need a terminating value or anything like that.)

Also, there's a lot of magic numbers in the code. Instead of:

int HistR[256] = { 0 };

You could tell a potential future reader of your code what the 256 (or 257) is. Something like:

const int MAX_BINS = 256;
...
int HistR[MAX_BINS] = { 0 };

Or, since the reason you have 256 bins is because the values you're analyzing are unsigned 8-bit characters, you could use the predefined UINT8_MAX constant. (It's in stdint.h.) Just remember to add 1 to it.

If it were my code, I might even define constants for red, green, and blue you use with the Vec3b type:

const int RED_CHAN = 0;
const int GREEN_CHAN = 1;
const int BLUE_CHAN = 2;

and then:

        int Red = intensity.val[RED_CHAN];
        int Green = intensity.val[GREEN_CHAN];
        int Blue = intensity.val[BLUE_CHAN];

It just clarifies what you're pulling out of the array.

Or, since this is C++, you could subclass Vec3b to add a red(), green() and blue() method and then just write:

int Red = intensity.red();

And I'd also make a constant to use instead of the 500 you have for the width of the histogram images.

I'd break this up into 3 functions - calculateHistogram(), drawHistogram(), and showImage(). calculateHistogram() would have the double loop where you add up values in the different bins. drawHistogram() would generate the HistPlot* images, and showImage() would create the windows and show the images.

Lastly, I'd add some white space! A blank line here or there to group together related lines helps me mentally organize what's going on.


Counting from 1 to 3 Please critique to help me learn:

int getNextInt(int* number)
{
    int value = *number;
    (*number)++;
    if (*number > 3)*number = 1;
    return value;
}

I want a function that will increment an external number by one, when it goes over than 3, then reset it to 1.

essentially when I repeatedly call this function I want the out to me 1,2,3,1,2,3,1,2,3

Style issue: Formatting and braces
Even if the language allows you to leave out the braces after an if, do not omit them. People tend to expand their code and forget to put them in when required. This creates nasty, hard to find bugs and the compiler will not complain.

Design issue: out parameters Output parameters tend to obscure the information flow in your program. They are not required in any way, you can do everything fine without them. Failing to keep track of all the funny little things a function might modify as a side effect is a constant source of bugs. Many people thus prefer to not use them at all and rather return a compound of all the things the function calculates and distribute them to the data structures after the function has returned. If this becomes hard you may have an overall design issue. (There are still valid reasons for using out-parameters e.g. in performance and memory critical low-level applications.)

Legacy code: Raw pointers Using plain raw pointers is only fun for very small and quick hacks, that will never see any real use. Become friends with the C++11 (and above) smart pointers. Seriously, they will save you a lot of trouble.

Last but not least

if(foo > max){
   foo = min;
}

Is in your case (continuous counting with clamped upper and lower value) equal to

foo = (foo % (max + 1 - min)) + min; // parenthesis for ease of reading

With max = 3 and min = 1 you get

foo = (foo % 3) + 1;

Using the modulo operator is an elegant approach for such "around the clock" counting.

Edit: The modulo operator is now named correctly. (Credits to @Cody Gray)


jQuery Drawer with Tab I am putting together an animated drawer from scratch for use but also as a learning experience as I am not very strong with jQuery and would really like to get better.

I am hoping that someone here might take a moment to look over my JSFiddle and give me some direction/tips to help me continue to progress?

For example: Is what I put together clean and correct way of doing things? Is creating a function to init the elements for users who have JavaScript as I have done correct? Will what I wrote function well across browsers or are there better ways of achieving this?

jsFiddle

$(document).ready(function() {

    //Hide message if user has javascript
    function initPage() {
        $('#message').css('marginTop', '-60px');
        $('#message').find('.droid').css('bottom', '-60px');
    }

    function slideMessage() {
        var message = $('#message');
        var tab = $('#tab');
        var margin = $('#message').css('marginTop');
        var speed = 300;

        if (margin != "0px") {
            tab.animate({top: "-90px"}, speed);
            message.delay(speed).animate({marginTop: "0px"}, speed);
            message.find('.droid').delay(1000).animate({bottom: "0px"}, 100);
        } else {
            message.find('.droid').delay(1000).css({bottom: "-60px"}, 100);
            message.animate({marginTop: "-60px"}, speed);
            tab.delay(speed).animate({top: "0px"}, speed);
        }
    }

    initPage();

    setTimeout(function() {
        slideMessage();
    }, 1000);

    $('#message .close, #tab').click(function() {
        slideMessage();
    });
});

There are a few issues with your code I've modified it below. Some of the changes I made:

cache your jQuery objects
reword your slideMessage condition so that it is more readable
parameterize the animations and pull them out into methods of their own
move your initialization code so that it is all together

Updated JsFiddle

$(function () {
    var $message = $('#message'),
        $tab = $('#tab');
    var speed = 300;

    function animateMessage(to) {
        // don't want to animate them right now
        // rather: animate them when this function I'll return is called
        return function () {
            return $message.animate({
                marginTop: to
            }, speed);
        };
    }

    function animateTab(to) {
        return function () {
            return $tab.animate({
                top: to
            }, speed);
        };
    }

    //little helper method to queue animations
    function queue(immediate) {
        var rest = [].splice.call(arguments, 1);
        if (immediate) {
            $.when(immediate()).then(function () {
                queue.apply(window, rest);
            });
        }
    }

    function slideMessage() {
        var tabVisible = $message.css('marginTop') !== '0px';

        if (tabVisible) {
            queue(animateTab('-160px'),
                animateMessage('0px'));
        } else {
            queue(animateMessage('-40px'),
                animateTab('0px'));
        }
    }

    //Hide message if user has javascript
    $message.css('marginTop', '-40px');
    slideMessage();

    $('#message .close, #tab').click(function() {
        slideMessage();
    });
});

In response to the comments:

This is very similar to the code you initially put up. I derived it again on a gist using the code you put in your question here (slightly different from the code in the fiddle): https://gist.github.com/3060013/6a4de29001f845c625e2f907752562c7abf9dd85

Clone that repository to see the full history.

while your code does work, it has a couple of inefficiencies and the slideMessage has too much going on.

every time you call $('...'), jQuery needs to do some work in the background to figure out what you mean in the string.  You can instead cache these items and not need to depend on retrieving them repeatedly being fast. In this case it doesn't make much of a difference, but eventually it will cause your page to be slower.
There is too much extra junk in the way to make it apparent what slideMessage is doing. A good rule of thumb is to wait a week, then if you cannot glance at a statement and know that it is both in the right place in the function and what it is doing then something is too complex. While your code is probably sensible to you right now I am willing to stake the claim that in a few weeks/months when you go to add some other functionality you would waste some time trying to figure out what this is doing.

Caching a jQuery object is an expression for introducing a variable that holds the result of the $('...') function and its related forms.
Perhaps you shouldn't? I'm not 100% on this yet. I think this part of the code can be further cleaned up. I'm still leaning against combining them. I think something that represents this pseudocode would be best, but I'm not sure how to do that best:

if tabVisible
    slide tab out then slide message in
else
    do the opposite of what I did to switch them back

That is to say, I don't think the else block should specify the logic of how to do the opposite.


constant sized circular (ring) buffer I've implemented constant sized circular buffer. It provides push and pop operations, along with modern emplace. It is also optimized for destruction of trivially destructible types.

I didn't include iterators since it would be strange to have one pair of begin and end for input iterators and other for output iterators. Allocator support will come in the next version.

I'd like the review to focus on performance of push (emplace) and pop operations. Also, there is a code duplication in those functions. Should I leave just emplace?

#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H

#include <cstddef>
#include <utility>

template <typename T, std::size_t mcapacity>
class circular_buffer
{
    T* data;
    T* begin;
    T* end;
    std::size_t msize;
    bool is_empty;

    template <bool trivially_destructible>
    struct destructor
    {
        void destroy(T* object)
        {
            object->~T();
        }

        void destroy_n(T* objects, std::size_t sz)
        {
            for (std::size_t i = 0; i < sz; ++i)
            {
                objects->~T();
                ++objects;
            }

            ::operator delete(objects);
        }
    };

    template <>
    struct destructor<true>
    {
        void destroy(T* object)
        {
            //empty, since trivially destroyable
        }

        void destroy_n(T* objects, std::size_t sz)
        {
            ::operator delete(objects);
        }
    };

    destructor<std::is_trivially_destructible<T>::value> destroyer;

public:
    using container = circular_buffer<T, mcapacity>;
    using value_type = T;
    using reference = value_type&;
    using pointer = T*;
    using const_reference = const reference;
    using size_type = std::size_t;

    circular_buffer():
        data((pointer)::operator new(sizeof(value_type) * mcapacity)),
        msize(0),
        begin(data),
        end(data)
    {}

    template <typename ... ArgTypes>
    void emplace(ArgTypes ... args)
    {
        end = new (end) T(args...);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    void push(const T& value)
    {
        end = new (end) T(value);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    void push(T&& value)
    {
        end->T(value);
        ++end;
        if (end == data + mcapacity)
        {
            end = data;
        }

        if (msize != mcapacity)
        {
            ++msize;
        }
    }

    const_reference front()
    {
        return *begin;
    }

    void pop()
    {
        destroyer.destroy(begin);
        ++begin;
        if (begin == data + mcapacity)
        {
            begin = data;
        }

        if (msize != 0)
        {
            --msize;
        }
    }

    size_type size()
    {
        return msize;
    }

    constexpr size_type capacity()
    {
        return mcapacity;
    }

    bool full()
    {
        return msize == mcapacity;
    }

    bool empty()
    {
        return msize == 0;
    }

    ~circular_buffer()
    {
        destroyer.destroy_n(data, mcapacity);
    }
};

#endif

Sample usage:

#include "circular_buffer.h"
#include <vector>
#include <iostream>

int main()
{
    circular_buffer<int, 10> buffer;

    for (int i = 0; i < 30; ++i)
    {
        buffer.push(i);
    }

    std::cout << buffer.full() << '\n'
        << buffer.empty() << '\n';

    for (int i = 0; i < 20; ++i)
    {
        std::cout << buffer.front() << ' ';
        buffer.pop();
    }

    std::cout << buffer.full() << '\n'
        << buffer.empty() << '\n';
}

Type aliases

The container alias is never used, it can be removed.
The const_reference alias is wrong, it is still an alias to T&.
Use a consistent aliasing scheme, only use T when aliasing value_type.
Provide a const_pointer alias.

With these points in mind, your type aliases become:

using value_type = T;
using reference = value_type&;
using const_reference = value_type const&; // is now actually reference-to-const alias
using pointer = value_type*; // use value_type alias
using const_pointer = value_type const*; // for iterators, casting, etc.
using size_type = std::size_t;

Consider the rule of 5 when your class manages a resource.

Whenever your class manages a resource, it probably needs to implement the destructor, copy and move operations. You definitely do not want pointers to be copied when a copy of circular_buffer<> is made. Possible issues:

Memory being freed twice.
Dangling references.
Invalid object states.

Use static memory when the size is known at compile-time.

This will be more efficient and exception-free during allocation. Possible replacement:

#include <type_traits>
std::aligned_storage_t<mcapacity * sizeof( T ), alignof( T )> data;

Now that you are using static memory, you can provide two private functions to avoid having to use ugly casts everywhere:

T* data() { return reinterpret_cast<T*>( &data ); }
T const* data() const { return reinterpret_cast<T const*>( &data ); }

Your constructor becomes:

circular_buffer() noexcept /* no exceptions with static memory allocation */ :
    /* members reordered to match class */
    begin( data() ),
    end( begin ),
    msize( 0 ),
    is_empty( false )
{}

We now explicitly initialize is_empty in the constructor initializer list. I think this is clearer.
To avoid weird bugs, members are initialized in the same order that they
are declared in the class.
If your class needs really big chunks of memory that aren't available statically, then don't make the capacity a template parameter: make it a constructor parameter.

Use universal references in the definition of emplace().

This avoids unnecessary copying of arguments. Replacement:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args ); // variadic template of universal references

This change requires that we also perfect-forward these universal references wherever they may be used:

T{ std::forward<ArgTypes>( args )... }; // perfect-forward example

Use std::move() when you're finished with rvalue arguments.

In push( T&& ), argument value is actually used as an T const& (which calls the copy constructor) because you forget to call std::move(). The fix is simple:

end->T( value );

Becomes:

end->T( std::move( value ) );

Factor out repeated code.

Your push() overloads and emplace() have the exact same block of code being repeated; this block is a prime candidate for being extracted into a private function:

void tidy() noexcept // feel free to use a descriptive function name
{ // the repeating block of code
    ++end;

    if ( end == data + mcapacity )
        end = data;

    if ( msize != mcapacity )
        ++msize;
}

After modifications, emplace() and push() now look like this:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args )
{
    ::new ( end ) T( std::forward<ArgTypes>( args )... );
    tidy();
}

void push( T const& value )
{
    ::new ( end ) T( value );
    tidy();
}

void push( T&& value )
{
    ::new ( end ) T( std::move( value ) );
    tidy();
}

Note the consistent use of the same construction approach (placement-new) which looks nice and prevents syntax issues with primitive types.

Mark functions as noexcept when appropriate.

Non-throwing functions of yours include size(), capacity() and a few more. This will help programmers know that certain functions do not throw, which can help with optimizations.

For compile-time conditional noexcept marking, use type traits. Here's a sample:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args )
noexcept( std::is_nothrow_constructible<T, ArgTypes&&...>::value )
{ /* ... */ }

Mark non-modifying functions as const.

const functions of yours include front(), size() and a few more. Member functions that don't modify any of the class data members should be marked as const so that they can be used in the appropriate scenario (accessed through a circular_buffer<> const&).


Rewriting nested for loops to give better formatted output The following is code from a university practical I am doing. It reads in a txt file of twenty clients, whose information is stored in the txt file like this:

Sophia Candappa     F 23 00011

As per my lecturer's instructions, I have stored this information in a class called Client (although I know an ArrayList would be better I can't use it).
The code below is a method that is used to compare all the clients to one another and determine if they are a match. They are a match if they are all of the following:

Opposite sex
Age within five years of one another
They have three interests in common

The latter is determined by the string "00011" in the example above. If the clients share the number "1" at the same place in the string on three or more occasions, then the third condition is satisfied.

My code works perfectly and outputs the desired result. However, I want to ask two questions.

Is it as efficient as it could be (without ArrayLists)? I had considered separating out all the if/else statements into separate methods, but decided against it as I thought it wouldn't reduce any of the actual loops.
How can I change the output slightly. Currently, if a client is matched it displays "[Client Name] is compatible with" then it takes a new line and outputs all the clients who are matched. I would like to change it so that if the client has just one match, it says "Client Name is compatible with"..., but if the client has two or more clients it says "Client Name is compatible with the following [two/three/four] clients...

I have tried doing the latter, but I always mess up the formatting. Thanks in advance for any help that can be offered.

public static void matchClients(Client[] clientDetails)
{
    boolean anyMatch;
    int count;
    for (int b = 0; b < numberOfClients; b++)
    {
        anyMatch = false;
        count = 0;
        for (int c = 0; c < numberOfClients; c++)
        {
            if (clientDetails[b].getClientGender()!=clientDetails[c].getClientGender())
            {
                if (Math.abs(clientDetails[b].getClientAge() - clientDetails[c].getClientAge()) <= 5)
                {
                    int interests = 0;

                    String clientOneInterests = clientDetails[b].getClientInterests();
                    String clientTwoInterests = clientDetails[c].getClientInterests();

                    int interestNumber = 0;
                    while (interestNumber < clientOneInterests.length())
                    {
                        if ((clientOneInterests.charAt(interestNumber) == clientTwoInterests.charAt(interestNumber))
                                && (clientOneInterests.charAt(interestNumber) == '1' ))
                            interests++;
                        interestNumber++;
                    }

                    if (interests >= 3)
                    {
                        anyMatch = true;
                        if (count == 0)
                        {
                            System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
                            System.out.println("\t" + clientDetails[c].getClientName());
                        }
                        else
                        {
                            System.out.println("\t" + clientDetails[c].getClientName());
                        }
                        count++;
                    }
                    interests = 0;
                }
            }
        }
        if (anyMatch == false)
            System.out.println(clientDetails[b].getClientName() + "is not compatible with any client.");
        System.out.println("");
    }
}

You should extract out at least two methods:

boolean isMatchingClients(final Client client, final Client otherClient) { ... }
int calculateCommonInterests(final String clientInterests,
    final String otherClientInterests) { ... }

It would improve readabilily a lot and make the code more flatten.

I usually prefer final variables. Making a variable final relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From @nerdytenor's answers.)
Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.

For example, the count variable could be right before the second for loop:

int count = 0;
for (int c = 0; c < numberOfClients; c++)

(Effective Java, Second Edition, Item 45: Minimize the scope of local variables)
If it's possible I'd consider storing the interest data in BitSets. Then it would be possible to and two of them and get the number of common bits with the cardinality method. Here is some test code:

@Test
public void testBitSet() {
    final BitSet interestBitSet = createBitSetFromString("11100111");
    final BitSet otherInterestBitSet = createBitSetFromString("11001001");

    final BitSet clone = (BitSet) interestBitSet.clone();
    clone.and(otherInterestBitSet);

    assertEquals(3, clone.cardinality());
}

private BitSet createBitSetFromString(final String input) {
    final BitSet result = new BitSet();

    final char[] inputArray = input.toCharArray();
    for (int index = 0; index < inputArray.length; index++) {
        if (inputArray[index] == '1') {
            result.set(index);
        }
    }
    return result;
}

The and method modifies the bitset which is a disadvantage here. Cloning helps, although it's not the most beautiful solution.
Instead of

System.out.println("");

you could use

System.out.println();

You could remove some duplication:

if (count == 0) {
    System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
    System.out.println("\t" + clientDetails[c].getClientName());
} else {
    System.out.println("\t" + clientDetails[c].getClientName());
}

The following is the same:

if (count == 0) {
    System.out.println(clientDetails[b].getClientName() + "is compatible with the following client(s)");
}
System.out.println("\t" + clientDetails[c].getClientName());

I'd create local variables for clientDetails[b] and clientDetails[c]. They are used a lot.
About the output: if you want to show the number of compatible clients in the header you have to count them (and maybe store them in an ArrayList to avoid running the loop twice) before printing the header. If you are not allowed to use ArrayLists I don't think that it's worth it.
I don't know what's the type of the clientGender field. If it's String, you should not compare it with != or ==. See: Java String.equals versus ==
The anyMatch variable is duplicated, it could be eliminated. It only stores the state whether count == 0 or not.

final boolean anyMatch = (count > 0);
if (anyMatch) {
    ...
}

Some optimization ideas:

Use two arrays: one for males, one for females, so you don't have to compare clients with the same sex.
Order the arrays by age and skip the definitely non-matching clients. You could use binary search here.
Use a two-dimensional array with the first dimension as the age. The second dimension contains the clients with the corresponding age.
You could use one array which is sorted by gender then age. You could use Arrays.sort and a custom compareTo method in the Client class:

@Override
public int compareTo(final Client o) {
    final int nameResult = name.compareTo(o.name);
    if (nameResult != 0) {
        return nameResult;
    }
    return age - o.age;
}

Finally, here is my two methods after the refactorings mentioned above:

public static void matchClients(final Client[] allClients) {
    for (final Client client: allClients) {
        checkClient(client, allClients);
    }
}

private static void checkClient(final Client client, final Client[] allClients) {
    int matchCount = 0;
    for (final Client otherClient: allClients) {
        if (!isMatchingClients(client, otherClient)) {
            continue;
        }
        if (matchCount == 0) {
            System.out.println(client.getClientName() +
                "is compatible with the following client(s)");
        }
        System.out.println("\t" + otherClient.getClientName());
        matchCount++;
    }
    final boolean anyMatch = (matchCount > 0);
    if (!anyMatch) {
        System.out.println(client.getClientName() +
            "is not compatible with any client.");
    }
    System.out.println();
}


Sorting an array to match the order of values of another array I'm running hundreds of curl operations in parallel to my own API, the response array that I get is out of order (the reason being that the first one to finish gets added to the response array first). I need to sort these back so they correspond to the input array, in order to do that I have already written a function as shown below.

I'm interested if there is a more efficient way to do this or not.

Note: The sample shows what I mean, however the input array is usually more than 100 elements long.

Sample input:

$input = array (
   'http://www.yandex.ru',
   'http://www.mail.ru',
   'http://www.google.com'
)

Response:

$response = array (
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.google.com', 200, 'yet another string')
)

Function:

function re_order($original, $scrambled) {
    foreach ($scrambled as $url_response) {
       $key = array_search($url_response[0],$original);
       $result[$key] = $url_response;
    }
    ksort($result);
    return $result;
}

Resulting array after calling the function (i.e. desired result):

$result = array (
    array('http://www.yandex.ru', 200, 'some string'),
    array('http://www.mail.ru', 200, 'some other string'),
    array('http://www.google.com', 200, 'yet another string')
)

Based on the comments I'm not entirely sure what you ended up doing so I thought I'd provide a general example in case other folks drop by.

Sample Code and Output

<?php

function random_finish()
{
  $list = array();
  $list[2001] = array(200,'result for URL ID 2001');
  $list[2002] = array(200,'result for URL ID 2002');
  $list[2003] = array(200,'result for URL ID 2003');
  $list[2004] = array(200,'result for URL ID 2004');
  $list[2005] = array(200,'result for URL ID 2005');

  $used = array();
  while ( count($used) < count($list) )
  {
    $r = mt_rand(2001,2005);
    if ( !isset($used[$r]) )
    {
      echo "... result for URL ID $r retrieved
\n";
      $used[$r] = $list[$r];
    }
  }

  return $used;
}

echo "
\n";
echo "Randomized result order...
\n";
$result = random_finish();

The above is meant to emulate random API response order and provides a result similar to the following:

Randomized result order...
... result for URL ID 2005 retrieved
... result for URL ID 2004 retrieved
... result for URL ID 2001 retrieved
... result for URL ID 2003 retrieved
... result for URL ID 2002 retrieved

Here, we emulate "using" the data as returned by using the key value to know which URL apply the response to. The key could be a globally unique URL ID or it could be a request sequence number:

echo "
\n";
echo "Use as is via request key...
\n";
foreach ($result as $key => $val)
  echo "... URL ID $key with result code " . $val[0] . " and text '" . $val[1] . "'
\n";

This matches the random response order above:

Use as is via request key...
... URL ID 2005 with result code 200 and text 'result for URL ID 2005'
... URL ID 2004 with result code 200 and text 'result for URL ID 2004'
... URL ID 2001 with result code 200 and text 'result for URL ID 2001'
... URL ID 2003 with result code 200 and text 'result for URL ID 2003'
... URL ID 2002 with result code 200 and text 'result for URL ID 2002'

If a reordering was needed it can be done efficiently by using the built in function ksort:

echo "
\n";
echo "If needed, list after ksort...
\n";
ksort($result);
foreach ($result as $key => $val)
  echo "... URL ID $key with result code " . $val[0] . " and text '" . $val[1] . "'
\n";

Which gives us an array (or list) of results sorted on the array key.  This could be a request ordering value though it would be nice to have a unique ID for each URL to be processed so that the ordering would not matter.

If needed, list after ksort...
... URL ID 2001 with result code 200 and text 'result for URL ID 2001'
... URL ID 2002 with result code 200 and text 'result for URL ID 2002'
... URL ID 2003 with result code 200 and text 'result for URL ID 2003'
... URL ID 2004 with result code 200 and text 'result for URL ID 2004'
... URL ID 2005 with result code 200 and text 'result for URL ID 2005'

Some key points from a code review standpoint:

Using a unique ID for URLs can eliminate the need to do any sorting.
Sorting using a simple built-in function is likely to be more efficient than repeated lookup activities (especially for larger lists).
Choosing a key for an array instead of accepting the default numeric keys can provide a lot of value in various situations.

In a nutshell, solution design can have a huge impact on solution complexity and efficiency.


Save list over many csv files each with given number of lines I wrote a little code for outputting to csv. It takes a list object named outtext and saves multiple .csv files. Each csv file contains cutoff elements of the list (except for the last), where cutoff is a specified number of elements/lines. This is useful when the user has to avoid writing to too large files (i.e. GitHub restricts file sizes too 100MB). The filenames are numbered from 0 to n, where n is the length of the output object divided by cutoff.

However, the code looks quite clunky and is quite long, given that it performs a relatively simple task:

import csv
import math

# dummy content
outtext = mylist = [None] * 300000

# Parameters specified by user
output_file = "path/name.csv"
cutoff = 150000

output_file_tokens = output_file.rsplit('.', 1)
num_files = int(math.ceil(len(outtext)/float(cutoff)))

for filenumber in range(num_files):
    counter = 0
    output_file = output_file_tokens[0] + str(filenumber) + "." + output_file_tokens[1]
    while counter <= cutoff:
        with open(output_file, 'wb') as f:
            writer = csv.writer(f)
            for line in outtext[:cutoff]:
                writer.writerow(line)
                counter += 1
    del outtext[:cutoff]
    print ">>> " + output_file + " successfully saved"

Is there room for improvement?

I don't know where outtext comes from, but this seems overly complicated. There's too much nesting, and there's not enough separation of concerns.

Let's back up. We want to (a) chunk our list into sizes of cutoff and (b) write each such chunk into a new file. For each chunk, we create a new file, and write all of the rows. Each of those problems is bite-size and manageable.

First, from How do you split a list into evenly sized chunks?:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

That gives us the first half of the problem:

for chunk in chunks(outtext, cutoff):
    # write chunk

Now for the second half, we just need an index. But rather than keeping our own counter, let's use enumerate(). Additionally, note that csvwriter has a writerows() method - so we don't need a loop for that.

Putting it all together:

for index, chunk in enumerate(chunks(outtext, cutoff)):
    output_file = '{}{}.{}'.format(output_file_tokens[0], index, output_file_tokens[1])
    with open(output_file, 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(chunk)

    print ">>> " + output_file + " successfully saved"

You don't need to del anything. That's going to be pretty slow too - everytime we delete a chunk we have to shift everything in memory. This way, we don't have to do that.


LeetCode #1120 Maximum Average Subtree (Python) This code snippet shows 2 common patterns I see a lot in Python that I don't really like:

Arbitrarily-named, narrowly-scoped recursive function
Inappropriate data type (in this case, an array ans to store 1 float) used purely for its mutability and scope, to store side-effects from some other scope

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maximumAverageSubtree(self, root: TreeNode) -> float:
        ans = [0]
        def helper(node):
            if not node:
                return 0, 0
            left_sum, left_count = helper(node.left)
            right_sum, right_count = helper(node.right)
            ans[0] = max(ans[0], (left_sum + right_sum + node.val) / (left_count + right_count + 1))
            return left_sum + right_sum + node.val, left_count + right_count + 1
        helper(root)
        return ans[0]

ans has to be an array, even though we just want to store one scalar value, because if we tried to use a float it would not be visible inside helper. This seems like an ugly shortcut to me.

And the other pattern I don't like is defining helper just so we can do recursion with additional return values for logic, then return helper's side effects. Is it normal to define short, sort of "throwaway" functions like this?

Non-Local Variables

ans is visible (for reading) inside of helper.  It just can't be changed, although its contents can be modified.

So yes,  ans = [0] is an ugly hack.  You don't need it.  What you need in its place is nonlocal.

def maximumAverageSubtree(self, root: TreeNode) -> float:
    ans = 0

    def helper(node):
        nonlocal ans     # <--- Refer to ans in outer (but not global) scope

        if not node:
            return 0, 0

        left_sum, left_count = helper(node.left)
        right_sum, right_count = helper(node.right)

        ans = max(ans, (left_sum + right_sum + node.val) / (left_count + right_count + 1))

        return left_sum + right_sum + node.val, left_count + right_count + 1

    helper(root)

    return ans

Arbitrary-named, narrowly-scoped recursive function

In this case, you're going to need to get used to it.

Instead of creating a new function, which is visible outside the maximumAverageSubtree function, this helper is only useful to this function.  It does not need to exposed to the outside, so it makes sense to hide it inside.

This is a common paradigm in Python.  Decorators use this all the time.  For example, a @timed decorator has an internal wrapper() function.

def timed(func):

    def wrapper(*argv, **kwargs):
        start_time = time.perf_counter()
        result = func(*argv, **kwargs)
        end_time = time.perf_counter()
        print(func.__name__, "took", end_time - start_time, "seconds")
        return result

    return wrapper

The function shouldn't be arbitrarily named; its name should reflect its purpose.  Here, we are wrapping a call to another function, so wrapper() makes sense.

Above, you have a helper() function.  That probably could be named better.  Maybe process_subtree(node).  But it is "scoped" inside maximumAverageSubtree(), so its name doesn't need to repeat that level of detail.


A tiny recursive crawler I've written a script to crawl a website recursively until all the links connected to some tutorials are exhausted. It is working smoothly now. There is always room for improvement, though!

import requests
from lxml import html

Page_link="http://www.wiseowl.co.uk/videos/"
visited_links = []

def GrabbingData(url):
    base="http://www.wiseowl.co.uk"
    visited_links.append(url)
    response = requests.get(url)
    tree = html.fromstring(response.text)
    title = tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a/text()')
    link = tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a/@href')
    for i,j in zip(title,link):
        print(i,j)

    pagination=tree.xpath("//div[contains(concat(' ', @class, ' '), ' woPaging ')]//a[@class='woPagingItem' or @class='woPagingNext']/@href")
    for nextp in pagination:
        url1 = str(base + nextp)
        if url1 not in visited_links:
            GrabbingData(url1)

GrabbingData(Page_link)

First of all, you don't need to make your solution recursive. Iterative approach in your case would be more intuitive and simple.
Moreover, there is a better way to handle pagination for this particular website - the paginated parts of the video catalog are following http://www.wiseowl.co.uk/videos/default-<number>.htm pattern, which means that you can start with number=1 up until you get 404 which would conclude the catalog:
import requests
from lxml import html

URL_PATTERN = "http://www.wiseowl.co.uk/videos/default-{}.htm"

with requests.Session() as session:
    page_number = 1
    while True:
        response = session.get(URL_PATTERN.format(page_number))
        if response.status_code == 404:  # break once the page is not found
            break

        print("Processing page number {}..".format(page_number))

        tree = html.fromstring(response.text)
        for video_link in tree.xpath('//p[@class="woVideoListDefaultSeriesTitle"]//a'):
            title = video_link.text
            link = video_link.attrib['href']

            print(title, link)

        page_number += 1

Notes about some of the improvements I've made:

re-using the same Session instance - it results into a memory usage and performance improvement because it re-uses the same TCP connection:

if you're making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

instead of searching the entire tree for the "video" elements 2 times, looping over video link elements directly once

naming: first of all, make sure to follow the lower_case_with_underscores Python naming recommendations. And, try to avoid meaningless variables like i and j if not used as throwaway loop variables; url1 was not a good variable choice as well

follow other PEP8 style guide recommendations - in particular, watch for the spaces around operators and newlines


Objective-C retain / release snippet Here are some snippets I coded and I would like some feedback on my way of handling this:

I have a utility class, as a singleton, that provides me with a method named randomColor which returns a (UIColor*):

-(UIColor*)randomColor
{
    float l_fRandomRedColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];
    float l_fRandomBlueColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];
    float l_fRandomGreenColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f];

    return [UIColor colorWithRed:l_fRandomRedColor
                    green: l_fRandomGreenColor
                    blue: l_fRandomBlueColor
                           alpha: 255];
}

Now, I know the object return by this method is autoreleased.

I store the returned value in another class and I would like to keep this value for a while, so I proceed like this:

[self setMpCurrentPieceColor:[[GraphicsUtility instance] randomColor]];

Which calls the following property:

- (void)setMpCurrentPieceColor:(UIColor*)_newColor
{
    [_mpCurrentPieceColor release];
    [_newColor retain];

    // Make the new assignment.
    _mpCurrentPieceColor = _newColor;
}

Question A)

My instance variable is released in the dealloc method. Is a the correct way to go?

Question B)

Now, let's imagine I have an array, like this:

UIColor* mBoardColors[WIDTH][HEIGHT];

I want to store the previous instance variable into the array:

[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release];
[_color retain];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = _color;

Is it correct?

Question C)

What if I want to move a color from a cell to another (moving, not copying), is it correct to do it like that?

[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1];
mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1] = nil;

Thank in advance for your precious comments and advices!

Alright, there's a number of simplifications to the Utility Class I'd like to make before I continue:

Your abstraction from arc4random (at least that's what I hope it is), is too expensive to not just use the corresponding C-code directly.  You could even make your own method in C, and use the inline qualifier for faster code than calling out to a singleton 3 times for every color.  Also, it is never good to name an Objective-C method "instance".  Singletons usually use a naming convention that makes sense with their overall implementation (i.e. NSFileManager.defaultManager).  The following will generate a random double for you between 0 and 1.  Not only is it cleaner, but it's cheaper.

#define ARC4RANDOM_MAX      0x100000000
float l_fRandomRedColor = ((double)arc4random() / ARC4RANDOM_MAX);

*As an aside, it's also a good idea to use an alpha value of 1.0f, instead of 255, because alpha is also measured on a 0-1 scale

  Question A)

  My instance variable is released in the dealloc method. Is a the
  correct way to go?

The rule in ObjC is "You own it, you destroy it."  Because mpCurrentPieceColor is an explicitly retain'ed property, you own it.  If you were to not destroy mpCurrentPieceColor in -dealloc, then your class would retain a valid reference to it, and it simply would not go away. (memory leak).

*As an aside, switching to ARC will alleviate all of these headaches.

  Question B)

  Now, let's imagine I have an array, like this:

  UIColor* mBoardColors[WIDTH][HEIGHT];...

So long as you initialize the members of the multi-dimensional array, this is correct, but definitely not optimal.  Objective-C has it's own array objects, which free you from having to make these ridiculous memory management decisions, and a dynamic, expandable multidimensional array is as simple as nesting NS(Mutable)Arrays:

[NSMutableArray arrayWithObjects:[NSArray array],[NSArray array],[NSArray array],[NSArray array],..., nil];

Not only that, but if you were to decide to expand or contract the board at any time, you could add or remove objects at a whim, and, so long as you release any references to the objects you put into the array, when the main array is released, it will release the sub-arrays, and the sub-arrays will release their objects.  It really is quite beautiful.

  Question C)

  What if I want to move a color from a cell to another (moving, not
  copying), is it correct to do it like that?

Another beauty of NSArrays is the ability to swap-out objects into a new index of the array, so long as you don't exceed the array's bounds.  See the "Replacing Objects" section of NSMutableArray's documentation.  Again, as above, memory management is vastly simplified with an NSArray, than dropping down to a multi-dimensional literal.


Generic Repository, UnitOfWork and IOC container I am stuck to define a generic repository with AutoFac IOC container. I am keeping thing very simple and only showing relevant information.

BaseEntity

public abstract class BaseEntity
{
    public int Id { get; set; }
}

IRepository

public interface IRepository<TEntity> where TEntity : BaseEntity
{
    List<TEntity> GetAll();
    void Insert(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

IUnitOfWork

public interface IUnitOfWork : IDisposable
{
    int SaveChanges();
    void Dispose(bool disposing);
    IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity;
}

IService

public interface IService
{
    IUnitOfWork UnitOfWork { get; }
}

IService<TEntity>

public interface IService<TEntity> : IService where TEntity : BaseEntity
{
    List<TEntity> GetAll();
    TEntity GetById(int id);
    void Add(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

UnitOfWork

public class UnitOfWork : IUnitOfWork
{

    private readonly IEntitiesContext _context;
    private bool _disposed;
    private ObjectContext _objectContext;
    private Hashtable _repositories;
    private DbTransaction _transaction;

    public UnitOfWork(IEntitiesContext context)
    {
        _context = context;
    }

    public int SaveChanges()
    {
        return _context.SaveChanges();
    }

    public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
    {
        if (_repositories == null)
        {
            _repositories = new Hashtable();
        }
        var type = typeof(TEntity).Name;
        if (_repositories.ContainsKey(type))
        {
            return (IRepository<TEntity>)_repositories[type];
        }
        var repositoryType = typeof(EntityRepository<>);
        _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
        return (IRepository<TEntity>)_repositories[type];
    }
}

Service<TEntity>

public class Service<TEntity> : IService<TEntity> where TEntity : BaseEntity
{
    public IUnitOfWork UnitOfWork { get; private set; }

    public Service(IUnitOfWork unitOfWork)
    {
        UnitOfWork = unitOfWork;
    }

    public List<TEntity> GetAll()
    {
        return UnitOfWork.Repository<TEntity>().GetAll();
    }
}

EntityRepository<TEntity>

public class EntityRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
    private readonly IEntitiesContext _context;
    private readonly IDbSet<TEntity> _dbEntitySet;

    public EntityRepository(IEntitiesContext context)
    {
        _context = context;
        _dbEntitySet = _context.Set<TEntity>();
    }

    public List<TEntity> GetAll()
    {
        return _dbEntitySet.ToList();
    }
}

Now these are generic repository, services and unit-of-work. In my presentation I am using IService<T> which will be injected through AutoFac. Now I have 2 concerns:

I am directly using EntityRepository inside UnitOfWork var repositoryType = typeof(EntityRepository<>), which is a problem for me because I am injecting dependencies through IOC.
If I need to use a custom Repository (by inheriting EntityRepository) in future, how can I inject it in my UnitOfWork?

First, I would caution against using the generic repository + unit of work pattern that was super trendy a few years ago because it has problems not unlike the problems you're facing (along with problems stemming from the fact that EF crosses traditional DAL/Domain/BL boundaries). Simply put, I would not use repositories with EF unless absolutely necessary, and if I had to, I would not use the generic repository pattern.

If you're hell-bent on using this pattern, then you will need to understand the origins of the problem you're facing. Because you have a generic type being returned by your UnitOfWork "factory," you aren't able to instantiate it during your bootstrapping, you are being forced to to instantiate it on-demand at runtime, resolving using the type you're using in your UnitOfWork method call.

If you are okay with using the same repository instance for all of your resolutions, then just make your objects require Repository<SomeType> in your object constructors or properties with public setters, then use RegisterGeneric(). You can see how that is used here. This bypasses the entire "at runtime" requirement.

If you want to maintain the pattern of fetching a repository using a method, then you need to treat your UnitOfWork class as a factory and use dynamic instantation.


F# Either computation expression with while loop I want to implement an Either computation expression in F#. The computation executes a function inside a while loop, and this function's return type is Result<int, string>. The function might return an Error<string> if some condition is met, and then the whole computation expression should be stopped.

This is the code I have so far to illustrate what I am trying to achieve:

type EitherBuilder () =
  member this.Bind(x, f) =
    match x with
    | Ok s -> f s
    | Error f -> Error f
  member this.Return x = Ok(x)
  member this.ReturnFrom x = x
  member this.Zero() = Ok()
  member this.Delay(f) = f
  member this.Combine(x, f) = this.Bind(x, f)
  member this.Run(f) = f()
  member this.While(guard, body) =
    if guard () then this.Bind(body (), fun _ -> this.While(guard, body))
    else this.Zero()

let either = EitherBuilder ()

let mutable i = 0

let func i =
  if i < 3 then Ok(i)
  else Error("error")

let result = either {
  let mutable res = 0
  while i < 10 do
    let! output = func i
    res <- output
    i <- i + 1
  return res
}

I have tested it and it looks like it is working and doing what I am after (in the example above, the computation is stopped when i becomes 3 and result is set to Error "error"), but I am not 100% sure if the implementation of the EitherBuilder is fully correct. I would appreciate some feedback.

There are a few things I would probably add or change about your implementation.  When I create a new computation builder, I typically put the logic in a module, and then just call the functions in that module from the builder.

Another thing I would do is prefer the use of discriminated unions for Error types.  This makes it possible to match on the error, and also lets you use a little trick with the implementation of delay/run on the computation builder to wrap up any unhandled exceptions that occur inside your computation expression as an Error as well, so you don't have to wrap things in try/with.

Next, I would implement some common operators like >>=, <*>, and <!>, as well as lift and apply functions.  These will make it easier to work with the Results outside of the computation expression and interface with functions that don't natively work with Results.

Finally, I would implement at least all the standard members for the computation builder, including TryWith/TryFinally/Using/For.  An example implementation might look like the following:

module Either =
    open FSharp.Reflection
    open System

    let inline bind f x =
        match x with
        | Ok s -> f s
        | Error e -> Error e

    let inline ok x = Ok x

    let inline zero () = Ok ()

    let inline convertExceptionToResult<'result,'event> (ex: exn) =
        let union = FSharpType.GetUnionCases(typeof<Result<'result, 'event>>)
        if typeof<'event>.IsAssignableFrom(typeof<exn>)
        then FSharpValue.MakeUnion(union.[1], [|[ex] |> box|]) |> unbox<Result<'result, 'event>>
        elif FSharpType.IsUnion typeof<'event>
        then let cases = FSharpType.GetUnionCases(typeof<'event>)
             match cases |> Seq.tryFind (fun case -> case.GetFields().Length = 1 && case.GetFields().[0].PropertyType.IsAssignableFrom(typeof<exn>)) with
             | Some case -> FSharpValue.MakeUnion(union.[1], [|[FSharpValue.MakeUnion(case, [|ex |> box|]) |> unbox<'event>] |> box|]) |> unbox<Result<'result, 'event>>
             | None -> failwithf "No Union Case of Event Type %s Supports Construction from an Unhandled Exception: \r\n%O" typeof<'event>.Name ex
        else failwithf "Unable To Construct a Failure of type %s from Unhandled Exception: \r\n%O" typeof<'event>.Name ex

    let inline delay<'result,'event> (f: unit -> Result<'result, 'event>) = fun () ->
        try f()
        with | ex -> convertExceptionToResult ex

    let inline run<'result,'event> (f: unit -> Result<'result, 'event>) =
        try f()
        with | ex -> convertExceptionToResult ex

    let inline (>>=) result f = bind f result

    let inline apply wrappedFunction result =
        match wrappedFunction, result with
        | Ok a, Ok b -> Ok (a b)
        | Error e, Ok s -> Error e
        | Ok s, Error e -> Error e
        | Error e, Error _ -> Error e

    let inline (<*>) wrappedFunction result = apply wrappedFunction result

    let inline lift f result = apply (ok f) result

    let inline (<!>) f result = lift f result

    type EitherBuilder() =
        member __.Zero() = zero()
        member __.Bind(x, f) = bind f x
        member __.Return(x) = ok x
        member __.ReturnFrom(x) = x
        member __.Yield(x) = ok x
        member __.YieldFrom(x) = x
        member __.Combine (a, b) = bind b a
        member __.Delay f = delay f
        member __.Run f = run f
        member __.TryWith (body, handler) =
            try body()
            with | ex -> handler ex
        member __.TryFinally (body, compensation) =
            try body()
            finally compensation()
        member this.Using(d:#IDisposable, body) =
            let result = fun () -> body d
            this.TryFinally (result, fun () ->
                match d with
                | null -> ()
                | d -> d.Dispose())
        member this.While (guard, body) =
            if not <| guard ()
            then this.Zero()
            else bind (fun () -> this.While(guard, body)) (body())
        member this.For(s:seq<_>, body) =
            this.Using(s.GetEnumerator(), fun enum ->
                this.While(enum.MoveNext,
                    this.Delay(fun () -> body enum.Current)))

    let either = EitherBuilder()

Looking at your example usage of the EitherBuilder, I would probably change the while loop to a tail-recursive function.  You can still use while loops with the new EitherBuilder if you want, but using a tail-recursive function allows you to eliminate the mutable state, and correctly defining your Error cases as a discriminated union will allow you to access the failing values if you need to without having the global state i.  That would look something like this:

open Either

type Errors =
| OutOfRange of int
| UnhandledException of exn // This is required to allow conversion from Exceptions to Errors

let func i =
  if i < 3 then Ok(i)
  else Error <| OutOfRange i

let result =
    let rec loop i res =
        either {
            if i < 10
            then let! output = func i
                 return! loop (i + 1) output
            else return res
        }
    loop 0 0

In which case, result has the value:

Result<int,Errors> = Error (OutOfRange 3)


I want to see if there is anything I don't need in my CSS file for my current layout Here is my link to the JSFiddle and the full screen description.

Note on the full mode screen: the footer is not sticking, but it actually sticks if I check on my browser.

So that is exactly what I want for my layout. I want someone to see if there's anything in my CSS I don't need, or if I am using improperly without affecting the layout that is displayed.

For example:

Under the Header ID I have a element called top:0; what is this used for and do I actually need it?
Under the Main ID I have margin: 0 auto -50px; I found help from someone, but quite don't understand the theory on it.
Under the Footer ID I have bottom:0; what is this used for as well and do I need it?

HTML:

CSS:

/*THIS IS THE CSS CODE FOR WNG WEBSITE*/
html, body
{
        padding:0;
        margin:0;
        height:100%;
        font-size:0.8em;
}
#page
{
        height:100%;
        min-width:960px;
}
#header
{
        position:relative;
        background-color:#115EA2;
        height:100px;
        width:100%;
        top:0;
}
#main
{
        width:1300px;
        background-color:#F1F2F3;
        margin: 0 auto -50px;
        vertical-align:bottom;
        padding: 20px 20px 40px 20px;
        color:#115EA2;
        text-decoration:none;
        height:2000px;
}
#footer
{
        position:fixed;
        width:100%;
        bottom:0;
        height: 35px;
        background-color:#115EA2;
}

Unless your element is fixed or absolutely positioned, top: 0 is doing nothing for you (#header).  Unless your descendant elements are absolutely positioned (or you need to adjust the element's stacking order due to surrounding absolutely positioned elements), you probably don't need position: relative either.

The negative margin on #main is doing nothing for you (margin: 0 auto gives identical results).  Generally, you use negative margins to nudge things around similar to relative positioning, but where it effects the position of everything that follows as well (eg. an element with margin-top: -50px will move up 50px and so will everything below it, but an element that's relatively positioned with a top: -50px will only shift that element up and not the following elements).

vertical-align: bottom isn't doing anything for you either (#main).  The vertical-align property only works on inline or table-cell elements.

It's not really a good idea to set fixed heights on elements that will have an unknown amount of content (#main).  Scrollbars give users clues as to how much content there is on the page.  It can be confusing to the user when they scroll and scroll, but there's no more content to find.  If the content is longer than you've allowed for, it will spill out of the container or get clipped off (depending on the element's overflow setting).

If you want your footer to be at the bottom of the viewport, then yes, you need bottom: 0.


Caesar Cipher, done in Ruby It's an assignment from the Odin Project.
Here's my implementation:
#!/usr/bin/env ruby

def caesar_cipher(str, shift)
    low_alpha = ("a".."z").to_a
    high_alpha = ("A".."Z").to_a
    length_alpha = low_alpha.length

    chars = str.split("")
    ciphered = ""

    chars.each do |char|
        if low_alpha.include? char
            i = low_alpha.index(char)
            shifted = (i + shift) % length_alpha

            ciphered << low_alpha[shifted]
        elsif high_alpha.include? char
            i = high_alpha.index(char)
            shifted = (i + shift) % length_alpha

            ciphered << high_alpha[shifted]
        else
            ciphered << char
        end
    end

    ciphered
end

puts caesar_cipher("What a string!", 5) # Bmfy f xywnsl!
puts caesar_cipher("Abc", 5) # Fgh
puts caesar_cipher("Xyz", 3) # Abc
puts caesar_cipher("Test", 1) # Uftu
puts caesar_cipher("Zoo", 10) # Jyy

What points could be improved? What would you have done differently and why?

Indentation
The standard indentation style in Ruby is two spaces, not four.
Single-quoted strings
If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.
Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files. In your case, you are only actually mutating one of the many strings in your code, the one assigned to ciphered.
You can make only this string mutable by either not using a literal to initialize it:
ciphered = String.new

Or by using the unary prefix String#+@ operator for strings, which turns a frozen string into a mutable string:
ciphered = +''

Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style violations I pointed out, and also was able to autocorrect all of them. Note, however, that automatically adding the magic comment broke the code originally, because Rubocop does not automatically detect which strings are mutated. So, I had to add the + manually afterwards. That's where good tests come in handy!
Inconsistent use of parentheses
Sometimes, you use parentheses around arguments, and sometimes you don't. The general rule is to always use parentheses around arguments if you have arguments, and leave out the parentheses only for "procedure-like" methods such as puts, attr_reader, require, private, etc.
For example, you are using parentheses for split and index but not for include?.
Constants
There is no need to re-compute low_alpha, high_alpha, and length_alpha every time you call the method. Their values will always be the same. Therefore, it makes sense to turn them into constants and initialize them at the beginning of the file:
LOW_ALPHA = ('a'..'z').to_a
HIGH_ALPHA = ('A'..'Z').to_a
LENGTH_ALPHA = LOW_ALPHA.length

Object#freeze
Object#freeze is a method that allows you to freeze an object. A frozen object will no longer allow itself to be modified. It is good practice in general to freeze objects that you don't intend to modify, both as a signal to the reader that this object will not be modified, and as a safety net, in case you ever accidentally try to modify it regardless.
We already made all but one of our strings frozen, so let's do that with the arrays as well:
LOW_ALPHA = ('a'..'z').to_a.freeze
HIGH_ALPHA = ('A'..'Z').to_a.freeze
LENGTH_ALPHA = LOW_ALPHA.length

Numbers are immutable anyway, no need to freeze them.
length vs. size
Many Ruby collections have both length and size methods, but some have only one. In general, IFF a collection has a size method, then that method is guaranteed to be "efficient" (usually constant time), whereas length may or may not be efficient (linear time for iterating through the collection and counting all the elements), depending on the collection.
In your case, you are using an array, for which both are constant time, but if you want to guarantee efficiency, then it is better to explicitly use size instead.
String#chars
Instead of using String#split, you can use String#chars to create an array of characters:
chars = str.chars

String#each_char
Actually, you don't need the array of characters at all. Instead, you can use the String#each_char iterator directly:
str.each_char do |char|

The conditional expression is … an expression
In Ruby, the conditional expression if / else is an expression, not a statement. (In fact, everything in Ruby is an expression, there are no statements.) Therefore, the conditional expression evaluates to a value, it evaluates to the value of the branch that was taken.
This means you can remove the duplicated ciphered << X from each branch, and instead pull it out of the conditional expression:
ciphered << if LOW_ALPHA.include?(char)
              i = LOW_ALPHA.index(char)
              shifted = (i + shift) % LENGTH_ALPHA

              LOW_ALPHA[shifted]
            elsif HIGH_ALPHA.include?(char)
              i = HIGH_ALPHA.index(char)
              shifted = (i + shift) % LENGTH_ALPHA

              HIGH_ALPHA[shifted]
            else
              char
            end

Code duplication
Speaking of duplicated code: Your then branch and your elsif branch are virtually identical. We can simplify them by extracting the duplicated code into a method:
def encrypt_letter(char, alphabet, shift)
  i = alphabet.index(char)
  shifted = (i + shift) % LENGTH_ALPHA

  alphabet[shifted]
end

and then using this method in the two branches instead:
ciphered << if LOW_ALPHA.include?(char)
              encrypt_letter(char, LOW_ALPHA, shift)
            elsif HIGH_ALPHA.include?(char)
              encrypt_letter(char, HIGH_ALPHA, shift)
            else
              char
            end

Higher-level iterators
Ruby has many powerful iteration methods in its collections library. Using each (or in this case each_char) directly is almost always sub-optimal. This particular pattern that you are using:

Initialize an accumulator. (In this case the string assigned to ciphered.)
Iterate over the collection and add to the accumulator.
Return the accumulator.

Is known as a Fold, and is available in Ruby in two forms, Enumerable#each_with_object and Enumerable#inject. Using Enumerable#each_with_object, we can further simplify your code to:
def caesar_cipher(str, shift)
  str.each_char.each_with_object(+'') do |char, ciphered|
    ciphered << if LOW_ALPHA.include?(char)
                  encrypt_letter(char, LOW_ALPHA, shift)
                elsif HIGH_ALPHA.include?(char)
                  encrypt_letter(char, HIGH_ALPHA, shift)
                else
                  char
                end
  end
end

The right higher-level iterator!
But actually, what you are doing here is simply transforming each element of the collection. You don't need something as powerful as a fold for that. This is a much simpler operation called Map, and it is also available in Ruby as Enumerable#map:
str.each_char.map do |char|
  if LOW_ALPHA.include?(char)
    encrypt_letter(char, LOW_ALPHA, shift)
  elsif HIGH_ALPHA.include?(char)
    encrypt_letter(char, HIGH_ALPHA, shift)
  else
    char
  end
end.join

Rubocop, revisited
I didn't mention this before, but in addition to the style violations I mentioned at the beginning, Rubocop was also complaining about the complexity and the length of the caesar_cipher method. At this point, Rubocop is actually happy with everything!
But we can do better.
The Algorithm
What the Caesar Cipher is really doing, is shifting the alphabet. You have recognized this, as can be seen by your variable names (shift), but you are not really taking advantage of it.
What we can do, is take our alphabets, shift them, and then use them for a key-value mapping, i.e. a Hash:
Now, our entire code looks like this:
#!/usr/bin/env ruby
# frozen_string_literal: true

LOW_ALPHA = ('a'..'z').to_a.freeze
HIGH_ALPHA = ('A'..'Z').to_a.freeze

def caesar_cipher(str, shift)
  low_encrypted = LOW_ALPHA.rotate(shift)
  high_encrypted = HIGH_ALPHA.rotate(shift)

  character_map =
    Hash.new { |_, k| k }
        .merge((LOW_ALPHA.zip(low_encrypted) + HIGH_ALPHA.zip(high_encrypted)).to_h)
        .freeze

  str.each_char.map(&character_map).join
end

Okay, there's a lot going on here. We are using Array#rotate to create the shifted character arrays:
LOW_ALPHA.rotate(3)
# => ["d", "e", "f", …, "a", "b", "c"]

Then we use Array#zip to create an array of pairs with the original character and the encrypted character:
LOW_ALPHA.zip(LOW_ALPHA.rotate(3))
# => [["a", "d"], ["b", "e"], ["c", "f"], …, ["x", "a"], ["y", "b"], ["z", "c"]]

With Array#+ we concatenate the two arrays together, and then call Array#to_h, which turns an arrays of pairs (two-element arrays) into a hash, which looks like this:
{
  'a' => 'd',
  'b' => 'e',
  'c' => 'f',
# …
  'x' => 'a',
  'y' => 'b',
  'z' => 'c',

  'A' => 'D',
  'B' => 'E',
  'C' => 'F',
# …
  'X' => 'A',
  'Y' => 'B',
  'Z' => 'C',
}

This contains our entire encryption scheme.
We have already created a hash with a default value that will simply return the key for any unknown key (so that, e.g. '!' maps to '!') and use Hash#merge to merge these two hashes into one.
Last, we call map as before, but now, as our transformation function, we simply pass the hash itself. For that, we use the & operator, which turns a Proc into a block. But wait, we don't have a Proc, we have a Hash? Indeed, but Hash implements Hash#to_proc, which converts the hash into a proc that is equivalent to using the hash's Hash#[] method.
The power of strings
The String class in Ruby is really powerful as well. For example, it has the method String#tr which does the same thing as the POSIX tr utility, it translates characters in a string. This is really the right method to use for this job:
#!/usr/bin/env ruby
# frozen_string_literal: true

LOW_ALPHA = ('a'..'z')to_a.join.freeze
HIGH_ALPHA = ('A'..'Z')to_a.join.freeze

def caesar_cipher(str, shift)
  low_encrypted = LOW_ALPHA.chars.rotate(shift).join.freeze
  high_encrypted = HIGH_ALPHA.chars.rotate(shift).join.freeze

  str.tr(LOW_ALPHA + HIGH_ALPHA, low_encrypted + high_encrypted)
end

Final thoughts
Lastly, I just want to give you something to think about, without any comments from me:
# frozen_string_literal: true

class CaesarCipher
  LOWER = ('a'..'z').to_a.join.freeze
  UPPER = ('A'..'Z').to_a.join.freeze

  def initialize(key)
    self.encrypted = (LOWER.chars.rotate(key) + UPPER.chars.rotate(key)).join.freeze
  end

  def encrypt(str)
    str.tr(LOWER + UPPER, encrypted)
  end

  alias_method :call, :encrypt

  def to_proc
    ->str { encrypt(str) }
  end

  private

  attr_accessor :encrypted

  freeze
end

caesar5 = CaesarCipher.new(5)

puts caesar5.encrypt('What a string!') # Bmfy f xywnsl!
puts caesar5.('Abc') # Fgh
puts CaesarCipher.new(3).('Xyz') # Abc
puts CaesarCipher.new(1).('Test') # Uftu
puts CaesarCipher.new(10).('Zoo') # Jyy

puts ['What a string!', 'Abc'].map(&caesar5)


Check fragment for exclude show same fragment again I use this code to check a fragment before showing it. What can you say about it?

int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0){
    String newFragmentTag = fragment.getClass().getSimpleName()+"|"+fragment.getArguments();
    String nowShowFragmentTag = getFragmentManager().findFragmentById(R.id.main_activity_fragment_container).getTag();
    if (!newFragmentTag.equals(nowShowFragmentTag)) {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())
                .addToBackStack(fragment.toString())
                .commit();
    }
}

In this line:

.replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())

you can reuse the newFragmentTag variable:

.replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)

This way you don't have to perform the same string concatenation twice, which is sort of the purpose of variables & methods in the first place.
Try to use getSupportFragmentManager() if you're using AppCompatActivity.
Since you're going to replace the fragment in R.id.main_activity_fragment_container anyways, there's no need to check the back stack. Just check if there are any fragments in the container before checking its tag.

Below is how I would rewrite the code in my style (you don't have to follow this):

FragmentManager fManager = getSupportFragmentManager();
String newFragmentTag = fragment.getClass().getSimpleName() + "  |  " + fragment.getArguments();

Fragment currentFragment = fManager.findFragmentById(R.id.main_activity_fragment_container);
if (currentFragment != null && currentFragment.getTag().equals(newFragmentTag)) {
    Log.w(TAG, "Fragment is already displayed");
    return;
}

fManager
    .beginTransaction()
    .replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)
    .addToBackStack(fragment.toString())
    .commit();


Optimization - open excel file from VB.NET using interop I have a simple app, which is something like a launcher for my macro enabled excel workbook. I made it for easier distribution, to be able to check if excel installed and also to make it look and behave like a standalone application.

I am using Office Interop which, according to MS, has many performance issues. But still, have you got any idea what I could improve to perform faster?

Imports System.Threading
Imports Microsoft.Win32
Imports Microsoft.Office.Interop.Excel

Module Module1
Public Sub Main()
    On Error GoTo ErrorHandler
    Dim singleInstance As Boolean = False
    Dim mutex As New Mutex(True, My.Application.Info.AssemblyName,
    singleInstance)
    Dim excelKey As RegistryKey = Registry.ClassesRoot.OpenSubKey("Excel.Application")
    Dim excelInstalled As Boolean = If(excelKey Is Nothing, False, True)
    If excelInstalled = True And singleInstance = True Then
        SplashForm.Show()
        Dim MyAppPath As String = My.Application.Info.DirectoryPath
        Dim ExcelFilePath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Správce rozpisů 2019\" & "Rozpis1.xlsb")

        If Not IO.File.Exists(ExcelFilePath) Then
            Dim ExcelfileBackupPath As String = IO.Path.Combine(MyAppPath, "bundle\backup\" & "Rozpis1.xlsb")
            If IO.File.Exists(ExcelfileBackupPath) Then
                My.Computer.FileSystem.CopyFile(ExcelfileBackupPath, ExcelFilePath, True)
                Call Open(ExcelFilePath)
            Else
                SplashForm.Close()
                ErrorForm.ShowDialog()
                End
            End If
        Else
            Call Open(ExcelFilePath)
        End If
        SplashForm.Close()
    ElseIf excelInstalled = False Then
        SplashForm.Close()
        CompatibilityErrorForm.ShowDialog()
    ElseIf singleInstance = False Then
        MsgBox("Správce rozpisů je již spuštěn.", vbInformation, "Aplikace je již spuštěna")
    End If
    Exit Sub
ErrorHandler:
    MsgBox("Při spouštění Správce rozpisů došlo k chybě.", vbCritical, "Došlo k chybě")
    Resume Next
End Sub

Sub Open(openThis As String)
    Dim xls As Application = New Application With {
        .WindowState = XlWindowState.xlMaximized
    }
    Dim workbook As Workbook = xls.Workbooks.Open(openThis)
    xls.Visible = True
End Sub
End Module

Interop is surely enough for this purpose. To manipulate workbooks, fill in 10.000th of cells then I usually use SpreadsheetLight (http://spreadsheetlight.com/), a free, MIT licensed .NET library that works on the XML level of the Excel files and is incredibly fast compared to the Application.Excel object.

From the point of code review, I think you could dive a bit more into VB.NET, your code still has the feeling of being VB6 or VBA. Why don't you switch to try/catch error handling for example? I assure you, you are going to like it. And as a rule of thumb, never compile any path/file names into your application, put them into app.config (especially if this is a standalone application) or into start parameters (especially if this application is called from within an enterprise database application).


A small "TODO" app built using a modular pattern I am just beginning to learn JavaScript and although I feel I am starting to grasp the language, I don't feel I know how to structure an app properly. I decided to start small and build a "TODO"-app using a modular pattern.

I am aware that I should use more validations, there are unused functions, and there may be a missing semicolon here and there. My main focus on this thing was to see if I could structure an app in a good way.

I would love some feedback on my setup. Is this a proper way to set up such a small application? Am I missing something completely? Am I using the modular pattern correctly?

Generally, have I gotten the gist of it?

(function todoApp() {

var storage = (function () {
    var _db,
        todos,
        addTodo,
        removeTodo,
        updateTodo,
        getAllTodos,
        save;

    if (!window.localStorage.todoApp) {
      window.localStorage.todoApp = JSON.stringify({todos: []});
    }

    _db = JSON.parse(window.localStorage.todoApp);

    addTodo = function addTodo(todo) {
      var id = Date.now().toString();
      _db.todos.push({id: id, todo: todo});
      save();
    };

    removeTodo = function removeTodo(id) {
      _db.todos.every(function (c, i) {
        if (c.hasOwnProperty("id") && c.id == id) {
          _db.todos.splice(i, 1);
          save();
          return false;
        }
      });
    };

    updateTodo = function updateTodo(id, todo) {
      _db.todos.every(function (c, i) {
        if (c.hasOwnProperty("id") && c.id == id) {
          _db.todos[i].todo = todo;
          save();
          return false;
        }
      });
    };

    getAllTodos = function getAllTodos() {
      return _db.todos;
    };

    save = function save() {
      window.localStorage.todoApp = JSON.stringify(_db);
    };

    return {
      addTodo: addTodo,
      removeTodo: removeTodo,
      updateTodo: updateTodo,
      getAllTodos: getAllTodos
    };

  })();

  var view = (function (storage) {
    var $todos = $("[rel='jstodo-container'] > [rel='jstodo-todos']"),
        todos = storage.getAllTodos(),
        render;

    render = function render() {
        $todos.html("");
        todos.forEach(function (c) {
          $todos.append("
" + c.todo + "
");
        });
    };

    return {
      render: render
    };
  })(storage);

  view.render();

  $("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    view.render();
  });
})();
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

  <title>JS Bin</title>

Todos:

    <input type="text" rel="jstodo-input"/>
    <button rel="jstodo-submit">Legg til!</button>

Here is a jsbin of the project (in case the Stack Snippet has permission issues).

There's some stuff that's confusing in this coding and it's structure. A few things of note:

First when defining a class you do not need the beginning ( and ending )(); What that is for is to create a nameless function that will then be run once and then for all intents and purposes be removed from memory after. You are wanting to create a class that can be referenced and used later on.
Simply:

function todoApp(){
    //define class here
}

This then creates an object constructor that you then call to create and store the object:

var myTodoApp = new todoApp();

Then your jQuery call after that, outside of your constructor, not in:

  $("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    myTodoApp.storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    myTodoApp.view.render();
  });

When giving a class (your todoApp function) a custom class for a variable, that 'sub-class' should be defined separately and then referenced inside of your class.

Inside of your class, anything you want to be accessible outside of your class should start with this.

var mayTodoApp = new todoApp();

$("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
    myTodoApp.storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
    myTodoApp.view.render();
  });

function todoApp(){
    this.storage = new storageClass();
    this.example = 'this is a string accessible outside of the class';
    //run any initialization code here
}

function storageClass(){
    var _db,
        todos,
        addTodo,
        removeTodo,
        updateTodo,
        getAllTodos,
        save;

        this.addTodo = function addTodo(todo) {
            //do stuff
            this.save(); //note: need 'this.' for class to access itself
        };
}

This is more along the structure you are looking for. A few things I would suggest looking into is the concept of this and maybe some Google results on javascript object oriented programming. Also having a good strong IDE (integrated development environment) helps a lot. I recommend Komodo personally, but to each their own. There might be a better one out there for you. But a good strong one can give code completion and show you syntax errors to help you get the structure down.

One other thing of note that helps quite a bit: Javascript is all read and processed into the DOM before anything is actually run (accept for dynamically added stripts, but that is a whole different beast). What this means is that before any coding is already run, the interpreter has already processed over the class definition. In other words, you can call your classes before defining them:

function todoApp(){
    this.storage = new storageClass();
}
function storageClass(){
    this.addTodo = function(todo){
    }
}
var todo = new todoApp();
todo.storage.addTodo('fooBar');

Will do the same as:

var todo = new todoApp();
todo.storage.addTodo('fooBar');

function storageClass(){
    this.addTodo = function(todo){
    }
}

function todoApp(){
    this.storage = new storageClass();
}

Outside of class definition, order matters, or course. You must create the object instance of your class before using it. Note that the latter is the standard. Classes should be defined below the coding to be run globally, this makes for better readability.

EDIT:    I also just noticed your JSON objects. You do not need to define then in that manner. Javascript automatically determines variable type which is why you use var instead of char and int and such. For this same reason JSON objects are automatically defined by format. It's a harder concept for some to grasp at first and I would definitely read more into it but basically it is an associated array, or array of pairs (keys and values). that is in this format:

{key: 'value', key: 'value'}

It is defined inside of curly brackets { } the key is a name to reference the value, and does not need quotes. The value needs quotes unless you want to use a variable. Also numbers do not need quotes for the values. Values can be objects or arrays as well. And the pairs are delimited by a comma ,. As long as you follow these rules javascript does the rest.

var home = '1234 Fake St.';
var example = {date: '12/01/2016', time: '9:42am', location: home, peopleAttending: 10};


Producer/Consumer programs I am studying mutual exclusion in college, and we just covered the producer/consumer problem.  The class does not involve writing code, but I decided to implement a bounded buffer version of this problem.  I have never written a multi-threaded program before, nor have I written a program with mutual exclusion before, so I decided to request a review here.

I implemented three variations, a busy-waiting variation, a Semaphore variation, and a Monitor variation.  All of these reside in a class named Program, which is needed for the threading.  The Monitor variation looks as if there should be a simpler solution with fewer variables. Is this so?

This is the part of the code that never changes:

const int buffSize = 10;
static char[] buffer = new char[buffSize];
static int valuesToProduce = 95;

static void Main(string[] args)
{
    Thread p = new Thread(new ThreadStart(Program.produce));
    Thread c = new Thread(new ThreadStart(Program.consume));
    p.Start();
    c.Start();
}

This is the busy-waiting producer/consumer and their related global variable:

static int avail = 0;

static void produce()
{
    for(int i=0; i<valuesToProduce; i++)
    {
        while (avail == buffSize) { };
        buffer[i % buffSize] = (char)(32 + i % 95);
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        avail++;
    }
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail < 1) { };
        char c = buffer[i % buffSize];
        Console.WriteLine("Consumed: {0}", buffer[i % buffSize]);
        avail--;
    }
}

This is the Semaphore implementation:

private static Semaphore isFull = new Semaphore(buffSize, buffSize);
private static Semaphore isEmpty = new Semaphore(0, buffSize);

static void produce()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        isFull.WaitOne();
        buffer[i % buffSize] = (char)(32 + i % 95);
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        isEmpty.Release(1);
    }
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        isEmpty.WaitOne();
        char c = buffer[i % buffSize];
        Console.WriteLine("Consumed: {0}", c);
        isFull.Release(1);
    }
}

And this is the Monitor implementation:

static int avail = 0;
private static object _buffer = new object();
private static object isFull = new object();
private static object isEmpty = new object();

static void produce()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail == buffSize)
        {
            Monitor.Enter(isFull);
            Monitor.Wait(isFull);
            Monitor.Exit(isFull);
        }

        Monitor.Enter(_buffer);
        buffer[i % buffSize] = (char)(32 + i % 95);
        avail++;
        Console.WriteLine("Produced: {0}", buffer[i % buffSize]);
        Monitor.Exit(_buffer);

        Monitor.Enter(isEmpty);
        Monitor.Pulse(isEmpty);
        Monitor.Exit(isEmpty);
    }
    avail++;
}

static void consume()
{
    for (int i = 0; i < valuesToProduce; i++)
    {
        while (avail < 1)
        {
            Monitor.Enter(isEmpty);
            Monitor.Wait(isEmpty);
            Monitor.Exit(isEmpty);
        }

        Monitor.Enter(_buffer);
        char c = buffer[i % buffSize];
        avail--;
        Console.WriteLine("Consumed: {0}", buffer[i % buffSize]);
        Monitor.Exit(_buffer);

        Monitor.Enter(isFull);
        Monitor.Pulse(isFull);
        Monitor.Exit(isFull);
    }
}

Style
Standard C# naming convention for methods is PascalCase. For static and instance members there are more variants around but often they are prefixed with _ and/or area also PascalCase so they can be easily distinguished from local variables and parameters. Following standard naming conventions makes your code look more familiar to other C# developers.
Structure
It is all static methods and global variables which seriously hurts maintenance and makes testing the code real painful as you probably have already discovered (I guess you have managed with a lot of commenting in and out code).
The easiest way to simplify this is to provide an abstract base class which the various implementations can derive from an implement. You should also pass the buffer size and values to produce/consume as parameters to break dependencies on global variables.
Something along these lines:
public class ProducerConsumerBase
{
    protected char[] _Buffer;
    protected int _TotalNumberOfValues;

    protected ProducerConsumerBase(int bufferSize, int totalNumberOfValues)
    {
        _Buffer = new char[buffSize];
        _TotalNumberOfValues = totalNumberOfValues;
    }

    public abstract void ProduceAll();
    public abstract void ConsumeAll();
}

this can then be derived like this:
public class BusyWaitingProducerConsumer : ProducerConsumerBase
{
    public BusyWaitingProducerConsumer(int bufferSize, int totalNumberOfValues)
        : base(bufferSize, totalNumberOfValues)
    {
    }

    public void ProduceAll()
    {
        ...
    }

    public void ConsumeAll()
    {
        ...
    }
}

public class SemaphoreProducerConsumer : ProducerConsumerBase
{
    public SemaphoreProducerConsumer (int bufferSize, int totalNumberOfValues)
        : base(bufferSize, totalNumberOfValues)
    {
    }

    public void ProduceAll()
    {
        ...
    }

    public void ConsumeAll()
    {
        ...
    }
}

The main method of your program then would be:
static const int BuffSize = 10;
static const int ValuesToProduce = 95;

static void Main(string[] args)
{
    var producerConsumer = new BusyWaitingProducerConsumer(BuffSize, ValuesToProduce);
    Thread p = new Thread(new ThreadStart(producerConsumer.Produce));
    Thread c = new Thread(new ThreadStart(producerConsumer.Consume));
    p.Start();
    c.Start();
}

And you can easily swap out the concrete implementation you want to test with without having to change or comment out a lot of code.
Bugs
Your busy-waiting implementation is broken in that you will need to at least call Interlocked.Increment and Interlocked.Decrement on avail because ++ and -- are not atomic operations - they consist of a read, an increment/decrement and a store. For example if avail is 1 and avail++ and avail-- are executed on two different threads simultaneously then the end result could be 0, 1 or 2.


Measuring the distance between NumPy matrixes This takes two sets of five random points stored as a NumPy matrix, and then calculates the NumPy matrix between a point of the first set and a point of the second set. While the code works, I feel it's inelegant, as if I was writing in PHP or some other language. How can the function CalculateMatrixDistances be improved?

import random
import numpy as np
import scipy
from scipy import spatial

P=5
V=5

def CalculateMatrixDistances(MatRows,MatColums):
    numberRows=MatRows.shape[0]
    numberColumns=MatColums.shape[0]
    MatrixDistances=np.matrix( [0 for c in range(numberColumns)] )
    for r in range(numberRows):
        d=[scipy.spatial.distance.euclidean (MatRows[r],MatColums[c]) for c in range(numberColumns)]
        MatrixDistances = np.vstack([MatrixDistances, d])
    MatrixDistances=np.delete(MatrixDistances, (0), axis=0)
    return MatrixDistances

PositionP=np.random.rand(P,2)
PositionV=np.random.rand(V,2)

MatrixDistancesVP=CalculateMatrixDistances(PositionV,PositionP)

print PositionP
print PositionV
print MatrixDistancesVP

(This is already implemented as
scipy.spatial.distance.cdist.
I'm going to assume that it's more optimised too.)

Why initialise MatrixDistances to zero if you're only going to
delete the first column regardless?  A matrix can also have zero for
any dimension.

Some more general observations:

As always, take a look at
PEP8 for Python
conventions, in particular naming of functions and variables, but also
missing whitespace.
The imports could be more consistent; the import spatial isn't being
used.
A zero matrix should probably be allocated with numpy.matlib.zeros
since it's shorter.
In Python 2 use xrange if you don't need the full list; also use the
function form of print for compatibility with Python 3 (it's also
more consistent to use it this way).
The repeated vstack may not be the most efficient option, but you
should consult a profiler for that.

When keeping the naming it should still rather look like this maybe.

import random
import numpy as np
import numpy.matlib
import scipy
import scipy.spatial

P, V = 5, 5

def CalculateMatrixDistances(MatRows, MatColums):
    numberRows = MatRows.shape[0]
    numberColumns = MatColums.shape[0]
    MatrixDistances = np.matlib.zeros((0, 5))
    for r in xrange(numberRows):
        d = [scipy.spatial.distance.euclidean(MatRows[r], MatColums[c]) for c in xrange(numberColumns)]
        MatrixDistances = np.vstack([MatrixDistances, d])
    return MatrixDistances

PositionP = np.random.rand(P, 2)
PositionV = np.random.rand(V, 2)

MatrixDistancesVP = CalculateMatrixDistances(PositionV, PositionP)

print(PositionP)
print(PositionV)
print(MatrixDistancesVP)
print(scipy.spatial.distance.cdist(PositionV, PositionP))


CSV lookup problem solved with CoffeeScript Source code with some test:

assert = require('assert')

compile_csv_search = (text, lookupKey)->
    [header, body...]= text.split('\n').filter(Boolean).map((el)->
        el.split(',')
    )
    col = header.indexOf(lookupKey)
    assert(col isnt -1)
    lookupIndex = body.reduce(
        (acc, row, i)->
            cell = row[col]
            acc[cell] = i
            return acc
        {}
    )
    return (lookupName)->
        rowNum = lookupIndex[lookupName]
        return body[rowNum].reduce(
            (acc, el, i)->
                acc[header[i]] = el
                return acc
            {}
        ) if rowNum?

# test one
(()->
    csvText = "ip,name,desc\n"+
        "10.49.1.4,server1,Main Server\n"+
        "10.52.5.1,server2,Backup Server\n"
    csv_by_name = compile_csv_search(
        csvText
        "name"
    )

    assert.deepEqual(
        csv_by_name("server2")
        {ip: "10.52.5.1", name: "server2", desc: "Backup Server"}
    )
    assert not csv_by_name("server9")?
)()

I think it is pretty descriptive.

Your lookupIndex may not work as intended unless the value you're using for the lookup is unique across all rows. You'll always find the last row in the CSV data, since the reduce function that creates lookupIndex will overwrite any existing lookup key/value with a new row number. That may not be a problem, but it is a limitation in your function.

You're doing a few things that you don't strictly need in CoffeeScript:

Explicit returns
Parentheses around function arguments
A "JS-style" IIFE, when CoffeeScript has the do keyword
You can define multi-line strings in CoffeeScript; just use 3 quotes (like Python)
CoffeeScript also has a for..of object iterator which would probably be more readable than your reduce calls (although semantically different)

Admittedly, the first 2 post are as much a question of context and preference. Sometimes you do need parentheses (e.g. when chaining function calls), and sometimes an explicit return is more readable. Still, though, your syntax seems a little funky in some places (for instance omitting commas in the call that to compile_csv_list, yet including the parentheses?)

In more general terms:

You're mixing snake_case and camelCase. Just stick to camelCase as that's the JS (and thus CoffeeScript) convention. For instance you'll see that assert.deepEqual is camel-cased. Speaking of convention; 2 spaces of indentation is the most common rule.
You're requiring assert, presumably for use in your tests - but you also use it in the function itself. That seems like a bad idea. Especially since you can just throw your own, possibly more detailed, exception whenever you want.
You could consider checking the header line for the lookupKey before parsing the rest of the lines.
I hope your CSV data is fairly easy to deal with; otherwise I'd find a full featured CSV parsing library, if I were you. Right now, you're just splitting on newlines and commas - but CSV may contain strings with commas in them, and which aren't "cell" delimiters. And a string may contain quotes - in which case the outer string has two quotes around it or something, if I recall correctly... CSV is a bizarre format with no simple rules for escaping things. The only real way to parse it, if you want to be thorough, is to go byte by byte; a regex just won't cut it.

Anyway, here's a version with some style changes. The only functional difference is that it doesn't use assert in the function itself.

compileCSVSearch = (csv, lookupKey)->
  [header, rows...] = csv.split("\n").filter(Boolean).map (line) -> line.split ","

  columnIndex = header.indexOf lookupKey
  throw "Can't find a '#{lookupKey}' column" if column is -1 # consider throwin ag proper Error obj

  lookupTable = {}
  for row, i in rows
    value = rows[columnIndex]
    lookupTable[value] = i

  (lookupValue) ->
    index = lookupTable[lookupValue]
    return unless index?
    copy = {}
    copy[key] = value for own key, value of rows[index]
    copy

# Tests

do ->
  assert = require "assert"

  csvText = """ip,name,desc
               10.49.1.4,server1,Main Server
               10.52.5.1,server2,Backup Server\n"""

  csvByName = compileCSVSearch csvText, "name"

  assert.deepEqual csvByName("server2"),
    ip: "10.52.5.1",
    name: "server2",
    desc: "Backup Server"

  assert.equal csvByName("server9"), undefined