Decompose two vectors I hope that the word "decompose" is correct, but the problem is simple:
I got two lists after an operation and I want to know what change happend from one list to the other.
As such I want to "decompose" the two lists A and B into "Both", "Only A" and "Only B".
template <class T>
void decompose(std::vector<T*> &a, std::vector<T*> &b, std::vector<T*> &only_a, std::vector<T*> &only_b, std::vector<T*> &both) {
    only_a = a;
    only_b = b;
    for (T* x : a) {
        for (T* y : b) {
            if (x == y) {
                both.push_back(x);
            }
        }
    }

    {
        auto it = only_a.begin();
        while (it != only_a.end()) {
            bool erase = false;
            for (T* x : both) {
                if (x == *it) {
                    it = only_a.erase(it);
                    erase = true;
                }
            }
            if (!erase) {
                it++;
            }
        }
    }

    {
        auto it = only_b.begin();
        while(it != only_b.end()) {
            bool erase = false;
            for (T* x : both) {
                if (x == *it) {
                    it = only_b.erase(it);
                    erase = true;
                }
            }
            if (!erase) {
                it++;
            }
        }
    }
}

I feel like there should be a faster way to do this than three twice intertwined loops.

For something easy to read and maintain I'd use set_difference and set_intersection which would work well on sorted ranges with no duplicates:
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(both));

only_a.reserve(a.size() - both.size());
std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(only_a));

only_b.reserve(b.size() - both.size());
std::set_difference(b.begin(), b.end(), a.begin(), a.end(), std::back_inserter(only_b));

...but that requires that you iterate over the ranges three times, and I think you are looking for something more efficient.
First, I would not start by copying a and b into only_a and only_b respectively. Instead, take inspiration from the example implementations for the standard functions I linked to above and create your own similar algorithm. This requires that Ts can be compared with operator<:
#include <algorithm>
#include <iterator>

template <class T>
void decompose(std::vector<T>& a,
               std::vector<T>& b,
               std::vector<T>& only_a,
               std::vector<T>& only_b,
               std::vector<T>& both)
{
    // Sort the input or require the input to be sorted like some algorithms do
    // If you'd like the input to be unchanged, make a and b const and make
    // copies of them instead and sort those copies.
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());

    // clear destination vectors or skip this if you want to append instead
    only_a.clear();
    only_b.clear();

    // the actual algorithm - loop for as long as both vectors have elements

    auto ait = a.begin();
    auto bit = b.begin();

    while(ait != a.end() && bit != b.end()) {
        if(*ait < *bit) {
            only_a.push_back(*ait++);  // can only be in a
        } else if(*bit < *ait) {
            only_b.push_back(*bit++);  // can only be in b
        } else {
            both.push_back(*ait++);    // must be in both
            ++bit;
        }
    }

    // Add the remaining elements if not both ait and bit have reached their end()
    if(ait != a.end()) std::copy(ait, a.end(), std::back_inserter(only_a));
    else if(bit != b.end()) std::copy(bit, b.end(), std::back_inserter(only_b));
}

Or make it even more generic and let it work with iterators only and add the possibility for the user to supply a Compare functor. This do require the ranges to be sorted in the same order as they would be if the Compare functor was used with std::sort on the ranges. The default Compare functor is here std::less<> that, if not specialized for the type involved, uses operator< to compare the elements.
#include <functional> // less
#include <iterator>   // iterator_traits

template <
    class First1, class Last1, class First2, class Last2,
    class OnlyAinserter, class OnlyBinserter, class BothInserter,
    class Comp = std::less<typename std::iterator_traits<First1>::value_type>
    // class Comp = std::less<> // <- is sufficient in C++14 and forward
>
void decompose(First1 ait, Last1 aend, First2 bit, Last2 bend,
               OnlyAinserter onlyait, OnlyBinserter onlybit, BothInserter bothit,
               Comp comp = Comp{})
{
    // loop for as long as both vectors have elements
    while(ait != aend && bit != bend) {
        if(comp(*ait, *bit)) {
            *onlyait++ = *ait++;  // can only be in a
        } else if(comp(*bit, *ait)) {
            *onlybit++ = *bit++;  // can only be in b
        } else {
            *bothit++ = *ait++;   // must be in both
            ++bit;
        }
    }

    // Add the remaining elements if not both ait and bit have reached aend/bend
    if(ait != aend) std::copy(ait, aend, onlyait);
    else if(bit != bend) std::copy(bit, bend, onlybit);
}

Which can then be called like this using the default Compare functor:
decompose(a.begin(), a.end(), b.begin(), b.end(),
    std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both));

Or like below, supplying a Compare functor. In this example the ranges are required to be sorted in descending order:
decompose(a.begin(), a.end(), b.begin(), b.end(),
    std::back_inserter(only_a), std::back_inserter(only_b), std::back_inserter(both),
    [](auto& A, auto& B) { return A > B; } // std::greater<>
);


Slowed Data reader in C# I am writing code to update data in the sample table (i.e. stbl) atoms of a video/audio file and found that in my method UpdateValues slows down to almost a crawl when executed. The line values.Add(value) was determined to be where the greatest time was taken through the debugger. Stepping through the program it was determined to take ~10mS to process. This List<int> is not touched by any other portion of the program. No other code appears to affect this list during the process.

public byte[] UpdateValues(int offset, string varName)
{
    //Create initial list
    List<int> values = new List<int>();
    //Set initial position to offset from (size, name, flags, count)
    int position = ((varName == "stsz") ? 20 : 16);
    //temporary byte array
    byte[] tempSize = new byte[4];

    //continue until position is equal to length of data
    while (position < this.data.Length)
    {
        //Get value from position
        Array.Copy(this.data, position, tempSize, 0, 4);

        if (BitConverter.IsLittleEndian)//Check for Endianess
            Array.Reverse(tempSize);//Reverse if necessary

        //update the value to include the new offset
        int value = BitConverter.ToInt32(tempSize, 0) + offset;

        //Add the new value to a list
        values.Add(value);//fixed from 'Values', no change in output time
        //increment the location
        position += 4;
    }

    //Sets the values back to the original location as updated
    return SetValues(values, varName);
}

The SetValues method is not slow and takes less than a second to complete:

public byte[] SetValues( List<int> values, string name )
{
    int location = 0;

    int _size = (values.Count * 4) + ((name == "stsz")? 20 : 16);
    this.data = new byte[_size];
    byte[] temp = BitConverter.GetBytes(_size);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(temp);

    //add size into first 4
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add box type label
    temp = Encoding.ASCII.GetBytes(name);
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add FLAGS
    temp = new byte[(name == "stsz")? 8 : 4];//add 4 bytes of 0 flags and version
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //add Entry Count
    temp = BitConverter.GetBytes(values.Count);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(temp);
    Array.Copy(temp, 0, this.data, location, temp.Length);
    location += temp.Length;

    //Add list of offsets to total
    foreach (int a in values)
    {
        temp = BitConverter.GetBytes(a);
        if (BitConverter.IsLittleEndian)
            Array.Reverse(temp);
        Array.Copy(temp, 0, this.data, location, temp.Length);
        location += temp.Length;
    }
    return this.data;
}

There are several Comments that are unnecessary. You should get rid of them, since your code explains a few of those Comments.

Most C# coding standards suggest that you always use braces for if statements, so instead of this:

 if (BitConverter.IsLittleEndian)//Check for Endianess
        Array.Reverse(tempSize);//Reverse if necessary

you would format it like this:

if (BitConverter.IsLittleEndian)
{
    Array.Reverse(tempSize);
}


Key / Value store with type classes for formatting / parsing I'm currently working on a Scala HTTP library, fetch, mostly because I have yet to find one that suits all my needs.

As part of this library, I need a generic key / value store, which I intend to use both for request / response headers and URL query parameters. This store uses type classes for value parsing and formatting, which makes it both type-safe and convenient to use: ETags, for example, can be manipulated through an ETag class, but I do not need the key / value store to be aware that etags even exist.

This is what I have come up with:

trait ValueReader[S, T] {
  def read(value: S): Try[T]
}

trait ValueWriter[S, T] {
  def write(value: S): Option[T]
}

class KeyValueStore[T](val values: Map[String, T] = Map()) {
  def apply[S](name: String)(implicit reader: ValueReader[T, S]): S =
    reader.read(values(name)).get

  def getOpt[S](name: String)(implicit reader: ValueReader[T, S]): Option[S] = for {
    raw    <- values.get(name)
    parsed <- reader.read(raw).toOption
  } yield parsed

  def get[S](name: String)(implicit reader: ValueReader[T, S]): Option[Try[S]] = values.get(name) map reader.read

  def set[S](name: String, value: S)(implicit writer: ValueWriter[S, T]): KeyValueStore[T] =
    writer.write(value).fold(this)(set(name, _))

  def set(name: String, value: T): KeyValueStore[T] = new KeyValueStore(values + (name -> value))

  def setIfEmpty[S](name: String, value: S)(implicit writer: ValueWriter[S, T]): KeyValueStore[T] =
      if(contains(name)) this
      else               set(name, value)

  def remove(name: String): KeyValueStore[T] =
      if(contains(name)) new KeyValueStore[T](values - name)
      else               this

  def contains(name: String): Boolean = values.contains(name)
}

See this class for sample implementations of readers and writers.

I'd be very happy for this code to be criticised and improvements to be suggested, especially in the following areas:

variance: I will probably end up making this covariant in T. Is there any reason not to do so?
I've included three "accessor" methods: apply (which throws), getOpt (safe but doesn't let the caller know what went wrong) and get (safe, granular, but heavier). Is there a standard pattern for this, or is what I'm doing considered acceptable / idiomatic?
I'm pretty sure I'm not the first person to need this kind of class, are there standard methods that are expected and I'm not providing?
what's the general consensus on "operator-like" methods, such as - for remove or + for add?

I don't see how to understand the KeyValueStore without understanding the ValueFormat implementation you reference. You don't have any substantial comments in either implementation, including "why". Their mutual dependency makes it very difficult to review either of them.

Readability issues:

You use ValueReader[S,T] in the KeyValueStore and ValueReader[T] in the ValueFormat -- this caused many minutes of confusion and blind paths.
Similarly, you define trait ValueReader[S,T] and then you immediately turn around and use ValueReader[T,S] in the body of KeyValueStore. Swapping the parameters causes more confusion.


Multiple jQuery events on one element with different functions and target selectors According to this two questions: [1] and [2]

I need a way to combine these two methods of handling the event attachment in jQuery.

$('selector').on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown:  function() {},
    mouseup:    function() {}
});

I prefer the previous method but need something like the following to work with "live"-events. (The problem is, that the next pattern kills the clarity if the code will be a bit larger and even if there're comments between the handlers, it breaks the code.):

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           // this comment breaks the chain
           .on('mousedown',  'selector3', function(){})
           .on('mouseup',    'selector4', function(){});

However, since there's no real world example to do it like this?:

$(document).on({
    mouseenter: 'selector1': function() {},
    mouseleave: 'selector2': function() {},
    mousedown:  'selector3': function() {},
    mouseup:    'selector4': function() {}
});

...I've ended up with this simple on-wrapper function: https://gist.github.com/4191657

;(function($) {
    $.fn.act = function() {
        var args = arguments;
        return this.each(function() {
            for (var i = args.length; i--;) {
                $(this).on(args[i][0], args[i][1], args[i][2]);
            }
        });
    };
})(jQuery);

Now the usage is quite simpler:

$(document).act(
    ['mouseenter', 'selector1', function() {}],
    ['mouseleave', 'selector2', function() {}],
    ['mousedown', 'selector3', function() {}],
    ['mouseup', 'selector4', function() {}]
);

As @Joonas said that this funtion improves anything. I had the need to came up here with a new question.

So my question, have you any thoughts, suggestions or improvements to this function? Or is there maybe a better solution to handle this problem?

Try placing the comments inside the callback instead to avoid breakage. I also do this on if-else statements as well so comments remain uniform.
Event maps are better when appending multiple event handlers to the same selector.
If you want a bit readability, move the handlers away from the attaching procedure. That way, they look clean

So here it is in the end:

//handlers

function selector1handler(){
    //comment here
};

function selector2handler(){
    //comment here
};

function selector3click(){
    //comment here
};

function selector3mouseover(){
    //comment here
};

//add handlers

$(document)
    .on('mouseenter', 'selector1', selector1handler)
    .on({
        click : selector3click,
        mouseover : selector3mouseover
    },'selector3')
    .on('mouseleave', 'selector2', selector1handler)


cron daily and weekly scripts for a minimal Nginx server environment I've created the following cron for daily and weekly scripts for a minimal Nginx server environment (as part of my larger script).

The daily cronjob updates WordPress and brings back original permissions (that are changed by WordPress in its update). The weekly task clears accumulated WordPress cache, make local backups, and delete old backups.

I wonder where this script could be shortened.

cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
    for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
    chown www-data:www-data /var/www/html/* -R
    find /var/www/html/* -type d -exec chmod 755 {} \;
    find /var/www/html/* -type f -exec chmod 644 {} \;
CRON_DAILY
chmod +x /etc/cron.daily/nses_cron_daily

# ---------------------------------------------------------------------------------------------------- #

cat <<-"CRON_WEEKLY" >> /etc/cron.weekly/nses_cron_weekly
    for dir in /var/www/html/*/wp-content; do cd "$dir" && cd cache && rm -rf *; done;

    zip -r /root/backups/dirs/html-$(date +\%F-\%T).zip /var/www/html
    find /root/backups/dirs/* -mtime +30 -exec rm {} \;
    mysqldump -u root -pPASSWORD --all-databases > /root/backups/db/db-$(date +\%F-\%T).sql
    find /root/backups/db/* -mtime +30 -exec rm {} \;
CRON_WEEKLY
chmod +x /etc/cron.weekly/nses_cron_weekly
echo "Change DB root password in crontab."

As mentioned by cas in the discussion, you can simplify your loops:
for dir in /var/www/html/*/; do
    if pushd "$dir"; then
        /usr/local/bin/wp plugin update --all --allow-root &&
        /usr/local/bin/wp core update --allow-root &&
        /usr/local/bin/wp theme update --all --allow-root
        popd
    fi
done

You can also “simplify” the chmod calls:
find /var/www/html/* -exec chmod a-x,a=rX,u+w {} \+

This processes directories and files in one go, and calls chmod as few times as possible (\+ instead of \;). Using the recursive flag to chmod means you can also drop find:
chmod -R a-x,a=rX,u+w /var/www/html/*

In the weekly job,
for dir in /var/www/html/*/wp-content; do cd "$dir" && cd cache && rm -rf *; done;

should be doable as
for dir in /var/www/html/*/wp-content/cache/; do rm -rf "${dir}/*"; done

instead, or even
rm -rf /var/www/html/*/wp-content/cache/*

The \+ comment regarding find is also relevant here.
I highly recommend using “proper” backup tools instead of ad hoc backups (but it’s great to have backups, whatever they are). In particular, automysqlbackup is packaged in Debian and works great for MySQL backups, with automatic pruning and nice password handling; I find BorgBackup great for file archiving.
As cas also tried to suggest, you could do away with the heredocs and perhaps make life simpler for yourself by retrieving the scripts directly. One way to do this would be to store them separately, alongside nses.sh, and retrieve them either as part of a git clone or using curl.


c - memcopy for embedded system I just implemented my memcpy function without any previous lookup.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void * copy ( void * destination, const void * source, size_t num )
{
    if ((destination != NULL) && (source != NULL))
    {
        unsigned int *dst = destination;
        const unsigned int *src = source;

        unsigned int blocks = num/sizeof(unsigned int);
        unsigned int left = num%sizeof(unsigned int);

        while(blocks--){
            *dst++ = *src++;
        }

        if (left){
            unsigned char *cdst = (unsigned char *)dst;
            const unsigned char *csrc = (const unsigned char *)src;

            while(left--)
                *cdst++ = *csrc++;
        }

    }

    return destination;
}

When looking at other memcpy implementations I find some differences:

unaligned address not handled
use of long instead unsigned int

Now what I didn't understand is point number 2. As far I know int will always be CPU WORD size i.e for 16bit it will be 2bytes and 32bit it will be 4bytes. But for long it must be 32bit minimum.

Alignment
unsigned int *dst = destination; fails when destination is not aligned for unsigned.  Same for src. (OP seems be somewhat aware of this given "unaligned address not handled")
Aliasing
Possible strict aliasing violation.  See What is the strict aliasing rule?
Fails when buffers overlap
Without restrict, buffer may overlap and code does not well handle overlaps in both directions.
Recommend to use restrict like memcpy().
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

CPU WORD size
"I know int will always be CPU WORD size" discounts 8-bits CPUs (common in embedded code).  On those, an int is at least 16-bit, not 8-bit.
The low-level copy size is typically related to the CPU word size, but much of this is implementation dependent.
Usually unsigned is good or best, but one would need to profile the implementation to know for sure.
Minor: Unneeded code
Test of left not unneeded as later while(left--) does the job.
// if (left)

NULL Testing
Common to not test for null-ness.  memcpy() is not require to do so, nor is it required to not test NULL.  What should be done depends on overall coding goals, so it is up to you.


Project Euler 92: Square digit chains A number chain is created by continuously adding the square of the
  digits in a number to form a new number until it has been seen before.

  For example,

  44 → 32 → 13 → 10 → 1 → 1
  85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

  Therefore any chain that arrives at 1 or 89 will become stuck in an
  endless loop. What is most amazing is that EVERY starting number will
  eventually arrive at 1 or 89.

  How many starting numbers below ten million will arrive at 89?

To tackle this problem I used the following procedure.

set array[1] to 1
set array[89] to 89
loop through all starting numbers from 2 to 10,000,000
for each starting number, calculate sum of squares until a previously calculated number is found
mark off all numbers in the chain you have just created as either 89 or 1
count the number of starting numbers that now have 89 as their array value

However even after using this relative clever strategy, my code still takes half a minute to compute. Is there something wrong I have done in my logic, or are there any other obvious improvements? I also think this strategy uses a large chunk of memory.

def square_digits(num):
    # Squares the digits of a number, eg 44=4^2+4^2=32
    total = 0
    while num:
        total += (num % 10) ** 2
        num //= 10
    return total

def single_chain(num, square_dict):
    # Evaluates a single chain untill 1 or 89
    temp_nums = []
    while True:
        if num in [1, 89]:
            break
        try:
            # If we hit a previously calculated value, break
            num = square_dict[num]
            break
        except:
            temp_nums.append(num)
            num = square_digits(num)
    for i in temp_nums:
        # Backtrack through the chain saving each number
        square_dict[i] = num
    return num == 1, square_dict

def pre_calculation(limit):
    # Precalculates the first values
    square_dict = dict()
    for i in range(1,limit+1):
        num = i
        while num not in [1,89]:
            num = square_digits(num)
        if num == 1:
            square_dict[i] = 1
        else:
            square_dict[i] = 89
    return square_dict

def square_chains(limit, square_dict):
    # Finds the number of chains ending in 1 and 89
    count_1 = 0
    count_89 = 0
    for i in range(1, limit):
        boolean, square_dict = single_chain(i, square_dict)
        if boolean:
            count_1 += 1
        else:
            count_89 += 1
    print "Chains ending in 1: ", count_1
    print "Chains ending in 89: ", count_89

if __name__ == '__main__':
    square_dict = pre_calculation(9*9*7)
    square_chains(10**7,square_dict)

I already posted the incremental improvement answer. Here's the home run answer.

Consider the number 4,666,777. This number happens to chain into 89. That takes some amount of work to figure out. But eventually we get there. What does this tell us? Since we're only interested in the sum of the squares of the digits, the actual ordering of the digits is irrelevant. That is... once we know that 4,666,777 is valid, we also know that 6,466,777 is valid, and 7,664,776 is valid, and ... All 140 unique permutations of the digits 4666777 are things we want to count. The key is: once we're done with 4666777, we do not even need to consider the other 139!

There are only 11,440 unique digit combinations from 1 to 10,000,000. Any solution checking all of them is thus doing ~900x more work than necessary. We can use itertools.combinations_with_replacement to get the unique digit combinations, and then use itertools.groupby to help determine how many such combinations there are.

Still with the memoized my_square_chain:

def euler89():
    count_89 = 0
    fact7 = fact(7)
    digits = range(10)

    for num in itertools.combinations_with_replacement(digits, 7):
        cur = sum(d**2 for d in num)
        if cur > 0 and my_square_chain(cur) == 89:
            count = fact7
            for _, g in itertools.groupby(num):
                count /= fact(len(list(g)))
            count_89 += count
    return count_89

This runs in 0.120s on my box. A performance improvement of 265x from my incremental changes, and 381x from the original solution.


Root finding using bisection method in Python This code below is supposed to calculate the root of a function using bisection method. I am a newbie to Python, so  I do not know how to raise errors. Also, I would like to have a general review on this algorithm design, where I could have optimised, utilised some tricks or any sort of improvements. I feel like I am really not using the full funcionality of Python somehow.

Any comments on how to write a succinct code is appreciated. Thanks.

"""
Program to find root of a function using bisection method
"""
import sys
import math

def is_equal(a,b):
    return abs(b-a) < sys.float_info.epsilon

def bisection(f, a, b, TOL=0.01, MAX_ITER=100):
    """
    f is the cost function, [a,b] is the initial bracket,
    TOL is tolerance, MAX_ITER is maximum iteration.
    """
    f_a = f(a)
    f_b = f(b)

    iter = 0
    while iter < MAX_ITER:
        c = (a+b)/2
        f_c = f(c)

        if math.isclose(f_c,0.0,abs_tol=1.0E-6) or abs(b-a)/2<TOL:
            return (c, iter)
        else:
            if f_a * f_c < 0:
                b = c
                f_b = f_c
            else:
                a = c
                f_a = f_c
            iter = iter + 1
    return None

def func(x):
    """
    The cost function: f(x) = cos(x) - x
    """
    return math.cos(x) - x

root, iter = bisection(func, -1, 1, TOL=1.0E-6)
print("Iteration = ", iter)
print("root = ", root, ", func(x) = ", func(root))

Type hints

They can help; an example:

def is_equal(a: float, b: float) -> bool:

The return type of bisection should probably be Optional[float].

Argument format

MAX_ITER and TOL should be lower-case because they are the arguments to a function, not a global constant.

Early-return

        return (c, iter)
    else:

does not need the else, so you can drop it.

In-place addition

        iter = iter + 1

can be

        iter += 1

Return parens

This does not need parentheses:

        return (c, iter)

The tuple is implied.


Simple Linux char driver Since the resources I found to learn are generally out-of-date, I'm having to read a lot of documentation, which makes the learning process somewhat haphazard. The module makes a simple character stack which can be read and written to by multiple processes.

#include<linux/init.h>
#include<linux/module.h>

#include<linux/fs.h>
#include<linux/types.h>
#include<linux/kdev_t.h>
#include<linux/cdev.h>

#include<linux/mutex.h>

#include<asm/uaccess.h>

#define MHELLO_STACK_SIZE 20

static int major;
static dev_t dev;
static struct cdev my_cdev;
static int count;
static DEFINE_MUTEX(lock);
static char stack[MHELLO_STACK_SIZE];
static int head;

static ssize_t hello_read(struct file* f,char* buf,size_t count,loff_t * offset)
{
    unsigned int res;
    printk(KERN_ALERT"R\n");

    mutex_lock(&lock);

    if(head<0)
    {
        mutex_unlock(&lock);
        return 0;
    }
    res=copy_to_user(buf,stack+head,1);
    head--;

    mutex_unlock(&lock);
    return 1;
}
static ssize_t hello_write(struct file* f,const char* buf,size_t count,loff_t * offset)
{
    unsigned int res;
    printk(KERN_ALERT"W\n");

    mutex_lock(&lock);

    if(head >= MHELLO_STACK_SIZE-1)
    {
        mutex_unlock(&lock);
        return -ENOSPC;
    }
    head++;
    res=copy_from_user(stack+head,buf,1);

    mutex_unlock(&lock);
    return 1;
}

static int hello_open(struct inode* inode,struct file* f)
{
    mutex_lock(&lock);
    count++;
    printk(KERN_ALERT"O %d\n",count);
    mutex_unlock(&lock);
    return 0;
}
static int hello_release(struct inode* inode,struct file* f)
{
    mutex_lock(&lock);
    count--;
    printk(KERN_ALERT"C %d\n",count);
    mutex_unlock(&lock);
    return 0;
}
const struct file_operations fops=
{
    .owner=THIS_MODULE,
    .read=hello_read,
    .write=hello_write,
    .open=hello_open,
    .release=hello_release
};

static int hello_init(void)
{
    int result=-1;

    mutex_init(&lock);
    mutex_lock(&lock);

    count=0;
    head=-1;

    result=alloc_chrdev_region(&dev,0,1,"mhello");

    if(result<0)
        printk(KERN_ALERT"Can't allocate major.\n");

    major=MAJOR(dev);
    printk(KERN_ALERT"Hello, my major no. is %d.\n",major);

    cdev_init(&my_cdev,&fops);
    my_cdev.owner=THIS_MODULE;

    cdev_add(&my_cdev,dev,1);

    mutex_unlock(&lock);
    return 0;
}
static void hello_exit(void)
{
    mutex_lock(&lock);
    unregister_chrdev_region(dev,1);
    cdev_del(&my_cdev);
    mutex_unlock(&lock);
    printk(KERN_ALERT"Goodbye world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("foo");

So, this isn't a full answer to your question, but maybe still relevant.

Included with the Linux sources is scripts/checkpatch.pl - which checks for things like coding style compliance, but also warns on use of outdated interfaces.

If you have a checked out (clean) git repository of the kernel, you can simply copy your source file into there and run

linux$ git diff HEAD | scripts/checkpatch.pl -

Doing that on the above code does point out a few things not just coding-style related.


JPEG compression and DCT algorithm verification Here is the code I am using to apply DCT on 8x8 blocks, which I'm not sure is correct. I have tried to follow Wikipedia's discrete cosine transformation (DCT) formula as closely as possible. Please let me know if there are any changes to be made.

//round up a float type and show two decimal places
double rndup(double n)
{
  double t;
  double temp;
  t=n-floor(n);
  if (t>=0.5)
  {
          n*=100.0;//where n is the multi-decimal float
          n=ceil(n);
          temp = floor(n);
          temp = n - temp;
          n-=temp;
          n/=100.0;
          }
  else
  {
          n*=100.0;//where n is the multi-decimal float
          n=floor(n);
          temp = floor(n);
          temp = n - temp;
          n-=temp;
          n/=100.0;
  }
  return n;
}
//two functions that work together to apply DCT to a 8x8 block
void a_check(int u,int v, double *Cu, double *Cv)
{
if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0);
if (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);
}
void applyDCT(double *DCTMatrix, double *Matrix,int x, int y)   //arguments: DCTMatrix = matrix where DCT values go, Matrix = input Matrix which needs to be processed
{
double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;
for(int u=0;u<8;u++)
{
    for(int v=0;v<8;v++)
    {
        a_check(u,v,&Cu,&Cv);
        cos_x = cos( (3.14/8) * (double)u * ( (double) ( (x+u) + (1.0/2.0))));
        cos_y = cos( (3.14/8) * (double)v * ( (double) ( (y+v) +(1.0/2.0))));
        DCT_value = Cu * Cv * Matrix[u*8 + v] * cos_x * cos_y;
        DCT_value = rndup(DCT_value);
        DCTMatrix[u*8 + v] = DCT_value;
    }
}
}

I'll comment on readability as it could use some serious improvements.

Your indentation is very inconsistent.  Sometimes you indent two spaces, four spaces, eight spaces, or no spaces.  Choose a style and keep it consistent throughout the program.

Two common styles (using four spaces):

void func()
{
    if (isTrue)
    {
        // ...
    }
}

void func() {
    if (isTrue) {
        // ...
    }
}

Your use of whitespace is also inconsistent.  It'd be more readable to separate all operators and operands with one space and keep those consistent throughout the program.

Don't do this:

int number=1+2+3;

Do this:

int number = 1 + 2 + 3;

This comment:

//where n is the multi-decimal float

can just be placed above the function.  There's no need to put it in multiple places.
The comment next to applyDCT() should probably be placed on top of the function instead.  A comment that long should either be relocated or broken up into separate-lined comments.
These:

if (u == 0) *Cu = sqrt(1.0 / 8.0); else *Cu = sqrt(2.0 / 8.0);
if (v == 0) *Cv = sqrt(1.0 / 8.0); else *Cv = sqrt(2.0 / 8.0);

are not very readable nor maintainable.  Prefer to apply curly braces, especially if you'll need to add to any of the conditions:

if (u == 0)
{
    *Cu = sqrt(1.0 / 8.0);
}
else
{
    *Cu = sqrt(2.0 / 8.0);
}

// the same applies to the second aforementioned line

Do not declare/initialize variables on the same line:

double Cu=0,Cv=0,cos_x=0,cos_y=0, DCT_value = 0;

This is also not very readable nor maintainable, especially if you'll ever need to add comments or modify individual variables.

Instead, have them on their own line:

double Cu = 0;
double Cv = 0;
double cos_x = 0;
double cos_y = 0;
double DCT_value = 0;

Moreover, in C++, you should try to use variables as close in scope as possible (next to where they will first be used).  This will reduce the need for long lists of variables like above.


Finding the number of moves a knight can perform while standing on a given square This is a problem from CodeSignal which can be founded over here
Here is an image on what we have to do:

Code
def map(cell):
    new_cell1 = ''

    for i in cell:
        if i == 'a':
            new_cell1 += '1'
        if i == 'b':
            new_cell1 += '2'
        if i == 'c':
            new_cell1 += '3'
        if i == 'd':
            new_cell1 += '4'
        if i == 'e':
            new_cell1 += '5'
        if i == 'f':
            new_cell1 += '6'
        if i == 'g':
            new_cell1 += '7'
        if i == 'h':
            new_cell1 += '8'

    new_cell1 += cell[-1]
    return new_cell1

def chessKnight(cell):
    cell = map(cell)
    num_of_moves = 0

    if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
        num_of_moves += 1

    if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])+2 <= 8 and int(cell[1])+2 > 0):
        num_of_moves += 1

    if (int(cell[0])+1 <= 8 and int(cell[0])+1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
        num_of_moves += 1

    if (int(cell[0])-1 <= 8 and int(cell[0])-1 > 0) and (int(cell[1])-2 <= 8 and int(cell[1])-2 > 0):
        num_of_moves += 1

    if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
        num_of_moves += 1

    if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])+1 <= 8 and int(cell[1])+1 > 0):
        num_of_moves += 1

    if (int(cell[0])+2 <= 8 and int(cell[0])+2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
        num_of_moves += 1

    if (int(cell[0])-2 <= 8 and int(cell[0])-2 > 0) and (int(cell[1])-1 <= 8 and int(cell[1])-1 > 0):
        num_of_moves += 1

    return num_of_moves

Question
The Code works as expected and returns the right answer, but I have just put a bunch of if conditions which doesn't look nice to me. Is there any way to implement the problem but without so much if blocks?

Never use existing function names for new functions
Python already has a function called map() Defining your new map() function can cause a lot of confusion, and undefined behaviour in your program.
By cheating
Since you have asked for an alternate solution, here it is
Being a chess engine developer, I would never calculate something trivial like the number of knight attacks since a simple array of size 64 with the pre-calculated ones can easily work. All you need is a simple function that converts a square like a1 to 0 and h8 to 63.
Here is the implementation,
def str_sq_to_int(sq):
    return (ord(sq[0])-97) + ((ord(sq[1])-49) * 8);

def knightAttacks(cell):
    attacks = [
        2, 3, 4, 4, 4, 4, 3, 2,
        3, 4, 6, 6, 6, 6, 4, 3,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        4, 6, 8, 8, 8, 8, 6, 4,
        3, 4, 6, 6, 6, 6, 4, 3,
        2, 3, 4, 4, 4, 4, 3, 2
    ]
    return attacks[str_sq_int(cell)]

The explanation is simple, the function str_sq_to_int() takes a square like 'a1' and returns an index using the ASCII value of the character to calculate the index. You can also use a simple dictionary to map each square to an index, but this one is easy
Then, it uses a pre-calculated set of values, to return the correct answer.


Application Settings Helper I'm developing an app which stores some different user settings in app.config such as connection strings, paths for saving reports, default printer e.t.c
For retrieving them I made a static class StoredSettingsTools which contains an Enum of settings types and a public method which calls (depending of setting type) some private method and get the settings from app.config:

public static class StoredSettingsTools
{

    public enum StoredSettingsType
    {
        DBConnection,
        Printer,
        ReportsFolder
    };

    private static ConnectionStringsSection GetConfigurationConnectionStringsSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConnectionStringsSection conectionSettings = (ConnectionStringsSection)config.SectionGroups.Get("UserSettingsGroup")
            .SectionGroups.Get("StoredConnectionSettings")
            .Sections.Get("defaultConnectionString");
        return conectionSettings;
    }

    private static Hashtable GetConfigurationPrinterSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];
        Hashtable sectionSettings = ConfigurationManager.GetSection(userSettingsGroup.Sections.Get("printerSettings").SectionInformation.SectionName) as Hashtable;
        return sectionSettings;
    }

    private static Hashtable GetConfigurationReportsFolderSection()
    {
        ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
        Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
        ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];
        Hashtable sectionSettings = ConfigurationManager.GetSection(userSettingsGroup.Sections.Get("reportsFolderSettings").SectionInformation.SectionName) as Hashtable;
        return sectionSettings;
    }

    public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
    {
        Hashtable table = new Hashtable();
        switch (sectionType)
        {
            case StoredSettingsType.DBConnection:
                {
                    ConfigurationSection section = GetConfigurationConnectionStringsSection();
                    ConnectionStringSettingsCollection col = ((ConnectionStringsSection)section).ConnectionStrings;

                    foreach (ConnectionStringSettings settings in col)
                    {
                        table.Add(settings.Name, settings.ConnectionString);
                    }

                    return table;
                }
            case StoredSettingsType.Printer:
                {
                    table = GetConfigurationPrinterSection();
                    return table;
                }

            case StoredSettingsType.ReportsFolder:
                {
                    table = GetConfigurationReportsFolderSection();
                    return table;
                }

        }
        return null;
    }
}

Is anything wrong with this code? Could it be more object-oriented?

You don't use ExeConfigurationFileMap configMap in any of your methods just get rid of it. If you do copy&pasta you should always check if some cleaning needs to be done.
You are calling this

Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
ConfigurationSectionGroup userSettingsGroup = config.SectionGroups["UserSettingsGroup"];

in every GetXXX method. Extract it to a separate method.
Something like

table = GetConfigurationPrinterSection();
return table;

doesn't buy you anything. Just return directly which makes it possible to reduce the scope of table to only the first case.
The GetConfigurationConnectionStringsSection() method already returns a ConnectionStringsSection so there is no need to read it as ConfigurationSection only to cast it to a ConnectionStringsSection. Changing this would also make the ConnectionStringSettingsCollection col superfluous.
To make your life a little bit easier you could use the var type at places where it is obvious from the right hand side of an assignment which type is meant.
The lines where you read the e.g printerSettings are a little bit long.

If we would change the GetXXX methods like mentioned we would get

private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup group, string sectionName)
{
    return group.Sections.Get(sectionName).SectionInformation.SectionName;
}
private static Hashtable GetConfigurationPrinterSection()
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup("UserSettingsGroup");
    Hashtable sectionSettings = ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup,"printerSettings")) as Hashtable;
    return sectionSettings;
}

private static Hashtable GetConfigurationReportsFolderSection()
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup("UserSettingsGroup");
    Hashtable sectionSettings = ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, "reportsFolderSettings")) as Hashtable;
    return sectionSettings;
}

but as you see we still have some code duplication here, so a method FetchSetting(string groupName, string sectionName) would help us to remove that duplication like so

private static Hashtable FetchSetting(string groupName, string sectionName)
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup(groupName);
    return ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, sectionName)) as Hashtable;
}
private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup sectionGroup, string sectionName)
{
    return sectionGroup.Sections.Get(sectionName).SectionInformation.SectionName;
}
private static Hashtable GetConfigurationPrinterSection()
{
    return FetchSetting("UserSettingsGroup", "printerSettings");
}

private static Hashtable GetConfigurationReportsFolderSection()
{
    return FetchSetting("UserSettingsGroup", "reportsFolderSettings");
}

which looks quite nice and tidy.

But wait, what about the ConnectionStringsSection ? If we remove everything which isn't necessary we will end with

private static ConnectionStringsSection GetConfigurationConnectionStringsSection()
{
    return (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");
}

but because the HashTable table will only be used for that value we should generate the HashTable there which will lead to

private static Hashtable GetConfigurationConnectionStringsSection()
{
    var section= (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");

    Hashtable table = new Hashtable();
    ConnectionStringSettingsCollection col = section.ConnectionStrings;

    foreach (ConnectionStringSettings settings in section.ConnectionStrings)
    {
        table.Add(settings.Name, settings.ConnectionString);
    }

    return table;
}

leaving the former GetStoredSettings() like this

public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
{

    switch (sectionType)
    {
        case StoredSettingsType.DBConnection:
            {
                return GetConfigurationConnectionStringsSection();
            }

        case StoredSettingsType.Printer:
            {
                return GetConfigurationPrinterSection();
            }

        case StoredSettingsType.ReportsFolder:
            {
                return GetConfigurationReportsFolderSection(); ;
            }
        default:
            {
                return null;
            }
    }
}

which looks strange with the given name, so let us rename the GetXXX methods which will lead to this

private static Hashtable FetchConnectionStringsSetting()
{
    var section= (ConnectionStringsSection)FetchConfigurationSectionGroup("UserSettingsGroup")
        .SectionGroups.Get("StoredConnectionSettings")
        .Sections.Get("defaultConnectionString");

    Hashtable table = new Hashtable();
    ConnectionStringSettingsCollection col = section.ConnectionStrings;

    foreach (ConnectionStringSettings settings in section.ConnectionStrings)
    {
        table.Add(settings.Name, settings.ConnectionString);
    }

    return table;
}
private static Hashtable FetchPrinterSetting()
{
    return FetchSetting("UserSettingsGroup", "printerSettings");
}

private static Hashtable FetchReportsFolderSetting()
{
    return FetchSetting("UserSettingsGroup", "reportsFolderSettings");
}
private static Hashtable FetchSetting(string groupName, string sectionName)
{
    ConfigurationSectionGroup userSettingsGroup = FetchConfigurationSectionGroup(groupName);
    return ConfigurationManager.GetSection(FetchSectionName(userSettingsGroup, sectionName)) as Hashtable;
}
private static ConfigurationSectionGroup FetchConfigurationSectionGroup(string groupName)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
    return config.SectionGroups[groupName];
}
private static string FetchSectionName(ConfigurationSectionGroup group, string sectionName)
{
    return group.Sections.Get(sectionName).SectionInformation.SectionName;
}
public static Hashtable GetStoredSettings(StoredSettingsType sectionType)
{

    switch (sectionType)
    {
        case StoredSettingsType.DBConnection:
            {
                return FetchConnectionStringsSetting();
            }

        case StoredSettingsType.Printer:
            {
                return FetchPrinterSetting();
            }

        case StoredSettingsType.ReportsFolder:
            {
                return FetchReportsFolderSetting(); ;
            }
        default:
            {
                return null;
            }
    }
}


Better way to incorporate HTML and PHP When I look at this style of code I feel like there has to be a better way to write this:

    Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/>

    State:
    <select id="cxState">
        <option></option>
    <?$states = getStates();
    while($state = $states->fetch_assoc())
    {?>
        <option value="<?=$state['st']?>"><?=$state['state']?></option>
    <?}?>
    </select>

    Status
    <select id="cxStatus">
        <option></option>
    <?$statusList = getCxStatusList();
    while($status = $statusList->fetch_assoc())
    {?>
        <option value="<?=$status['cxType']?>"><?=$status['cxTypeDescription']?></option>
    <?}?>
    </select>

I'd like to mention that keeping eclipses HTML code coloring would be a huge bonus...

Code separation

What you have there is everything mixed together - just by moving the php logic to the top of the file, makes it easier to read. With some minor reformatting it becomes easier to read/maintain:

<?php
$states = getStates();
$statusList = getCxStatusList();
?>

    Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/>

    State:
    <select id="cxState">
        <option></option>
    <?php while($state = $states->fetch_assoc()): ?>
        <option value="<?= $state['st'] ?>"><?= $state['state'] ?></option>
    <?php endwhile; ?>
    </select>

    Status
    <select id="cxStatus">
        <option></option>
    <?php while($status = $statusList->fetch_assoc()): ?>
        <option value="<?= $status['cxType'] ?>"><?= $status['cxTypeDescription'] ?></option>
    <?php endwhile; ?>
    </select>

Format for readability

If you're jumping in and out of php - having lines like this: {?> make things hard to read, especially if there is some nesting in the code. Whether you choose to use curly braces or the alternate (colon) syntax is up to you, but in html code using a style which aides readability (putting the curly brace/colon on the same line as the statement it relates to) helps.

No PHP Short tags

Shorttags are often considered a bad practice, and as such should be avoided unless the code is your own, and you control where it's going to be used. Note that you can use <?= with PHP 5.4 irrespective of the shorttags setting.

Consistent whitespace

The following:

<? foo(); ?>

Is easier to read than

<?foo();?>

Especially where it appears inline somewhere - use whitespace for readability.

Sprintf

If you find that your code gets to be like this:

<foo x="<?= $x ?>" y="<?= $y ?>"  z="<?= $z ?>"> ...

Then it's probably easier to read and maintain using:

<?php echo sprintf('<foo x="%s" y="%s" z="%s">...', $x, $y, $z); ?>


Small FizzBuzz program After watching this video by Tom Scott, I decided to make a program that follows that idea. This is what I came up with:

# If a number is divisible by the key, add the value
RULES = {
    3: "Fizz",
    5: "Buzz"
}

def is_divisible(num: int) -> list:
    output = []
    for divider in RULES:
        if (num % divider) == 0:
            output.append(RULES[divider])
    return output

for num in range(100):
    output = is_divisible(num + 1)  # Increment num by 1 so it is 1-100 not 0-99
    if not output:
        print(num + 1)
    else:
        print("".join(output))

My whole idea behind the way I made this is because I wanted it to be as expandable as possible. That way if you wanted to change the code to do something different (like the examples at the end of the above video), you could just add it. I would like to know if there is anything I could do to improve its changeableness and if there are any glaring problems that when fixed doesn't affect the changeability of the code.

You do not provide a testable function that performs the task of returning the desired answer for a specific test case. It is the 'normal number' handling that you intermangled with your test code. The main structure of your program structure should look somewhat like

def fizzbuzz(int):
    #[...]
    return answer

for num in range(1, 101):
    print(fizzbuzz(num))

You are free to do helper functions but you should always provide a complete testable solution.
Completely separate the functionality you want to provide from the tests. even split into different files.


"Of three points supplied, is one a midpoint of the other two?" Write a method named hasMidpoint that accepts three integers as parameters and returns true if one of the integers is the midpoint between the other two integers; that is, if one integer is exactly halfway between them. Your method should return false if no such midpoint relationship exists.

Here are two different versions of code that I wrote at two different occasions to accomplish the same thing. How can I make my code better, and is there a better way to accomplish this task?

public static boolean hasMidpoint(int a, int b, int c) {
        if ( a == b && b == c) {
            return true;
        } else if ((a + b) / 2.0 == c || (b + c) / 2.0 == a || (a + c) / 2.0 == b) {
            return true;
        } else {
            return false;
        }
    }

public static boolean hasMidpoint(int p1, int p2, int p3) {
        if((double)(p1 + p2) / 2 == p3 ||  (double) (p2 + p3) / 2 == p1 || (double) (p1 + p3) / 2 == p2){
            return true;
        }
        return false;
    }

All of the previous answers seem to work on averages of each of the 2 numbers (expressed as either division or multiplication). But I'm working on averages of all 3 numbers, on the assertion that the average of 3 numbers would be the midpoint of the min and the max...

It would seem to be fewer operations.

I'm not a Java developer, so be kind if I've missed something....

public static boolean hasMidpoint(int a, int b, int c) {
    int iTotal = a + b + c;
    // I took mleyfman's idea and replaced division with multiplication
    return (3 * a == iTotal) || (3 * b == iTotal) || (3 * c == iTotal);
}

Edit: Implementing suggestions, the code is now:

public static boolean hasMidpoint(int a, int b, int c) {
    long total = a + b + c;
    // I took mleyfman's idea and replaced division with multiplication
    // A midpoint will always be the average of the 3 values, so 3*midpoint must equal sum of a, b and c.
    return (3 * a == total) || (3 * b == total) || (3 * c == total);
}


Python: Combining Two Rows with Pandas read_excel I am reading an Excel file using Pandas and I feel like there has to be a better way to handle the way I create column names.  This is something like the Excel file I'm reading:

                1       2      # '1' is merged in the two cells above 'a'and 'b'
    Date        a   b   c   d  #  likewise for '2'.  As opposed to 'centered across selection'
1   1-Jan-19    100 200 300 400
2   1-Feb-19    101 201 301 401
3   1-Mar-19    102 202 302 402

I want my to merge the 'a','b','c',and'd' columns heads with the '1'and '2' above them, so I'm doing the following to get my headers the way that I want:

import pandas as pd
import json

xls = pd.ExcelFile(r'C:\Path_to\Excel_Pandas_Connector_Test.xls')
df = pd.read_excel(xls, 'Sheet1', header=[1])  # uses the abcd row as column names

#  I only want the most recent day of data so I do the following
json_str = df[df.Date == df['Date'].max()].to_json(orient='records',date_format='iso')

dat_data = json.loads(json_str)[0]

def clean_json():
    global dat_data
    dat_data['1a']      = dat_data.pop('a')
    dat_data['1b']      = dat_data.pop('b')
    dat_data['2c']      = dat_data.pop('c')
    dat_data['2d']      = dat_data.pop('d')

clean_json()

print(json.dumps(dat_data,indent=4))

My desired output is:

{
"Date": "2019-03-01T00:00:00.000Z",
"1a": 102,
"1b": 202,
"2c": 302,
"2d": 402
}

This works as written, but is there a Pandas built-in that I could have used to do the same thing instead of the clean_json function?

Yes, there is an easier way, using pandas.Index.get_level_values.

First, I could only get your example dataframe when calling the read with df = pd.read_excel("/tmp/temp.xls", header=[0, 1]), so I get both headers correctly.

Then you can just do this:

import pandas as pd
import json

# read df
df = pd.read_excel("/tmp/temp.xls", header=[0, 1])
df.index = pd.to_datetime(df.index)

# combine multilevel columns to one level
df.columns = (pd.Series(df.columns.get_level_values(0)).apply(str)
              + pd.Series(df.columns.get_level_values(1)).apply(str))

# get Date as a column
df = df.reset_index()
df.columns = ["Date"] + list(df.columns[1:])

print(df)
#          1a   1b   2c   2d
# 2019-01-02  100  200  300  400
# 2019-01-02  101  201  301  401
# 2019-01-03  102  202  302  402

After which you can just do something similar to what you are doing, but directly getting the index of the maximum instead of comparing all values to the value of the maximum:

json_data = json.loads(df.loc[df.Date.idxmax()].to_json(date_format='iso'))
print(json.dumps(json_data, indent=4))

Which produces the desired output:

{
    "Date": "2019-01-03T00:00:00.000Z",
    "1a": 102,
    "1b": 202,
    "2c": 302,
    "2d": 402
}


Maximum element in a binary tree This method finds the maximum in a binary tree. I have used generics to make this code more usable. However, I am not sure if I have written efficient and good Java code.

This is a method inside a class using generics and implementing Comparable interface for the generic parameter E.

private E maximumElement(TreeNode<E> root, E parentValue) {
  E max;
  if(root==null)
        max=parentValue;
  else {
    max = root.element;
    E leftMax = maximumElement(root.left, max);
    E rightMax = maximumElement(root.right, max);
    if(rightMax.compareTo(max) > 0)
              max = rightMax;
    if(leftMax.compareTo(max) > 0)
              max = leftMax;
   }
   return max;
}

static, and possibly public

I'd recommend having this method outside your binary tree class itself. It can operate on a binary tree, but it's not a method that requires to be specified directly inside the binary tree. Also, it doesn't use any state other than what is passed through its parameters. As such, I would make it static and probably also public.

First call

It's currently a bit weird to call this method from the start, the parentValue parameter is used for further recursions, but what value should it be passed originally? Considering this problem, I'd separate this method into a public part and a private part, such as:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
     return maximumElement(root, root.element);
}

private static <E extends Comparable<E>> E maximumElement(TreeNode<E> root, E parentValue) {
     ...
}

General stuff

It's good practice to always use braces. It improves readability and reduces the risk of bugs.
Using early returns helps reduce indentation and makes it more apparent how special cases are handled (otherwise you have to scroll down to make sure that the value isn't changed)

Rewritten version with some additional formatting improvements:

private static <E extends Comparable<E>> E maximumElement(TreeNode<E> root, E parentValue) {
    if (root == null) {
        return parentValue;
    }
    E max = root.element;
    E leftMax = maximumElement(root.left, max);
    E rightMax = maximumElement(root.right, max);
    if (rightMax.compareTo(max) > 0) {
        max = rightMax;
    }
    if (leftMax.compareTo(max) > 0) {
        max = leftMax;
    }
    return max;
}

If you want to remove the parentValue parameter, you would need to introduce a null check:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
    if (root == null) {
        throw new IllegalArgumentException("root cannot be null");
    }
    E max = root.element;
    if (root.left != null) {
        E leftMax = maximumElement(root.left);
        if (leftMax.compareTo(max) > 0) {
            max = leftMax;
        }
    }
    if (root.right != null) {
        E rightMax = maximumElement(root.right);
        if (rightMax.compareTo(max) > 0) {
            max = rightMax;
        }
    }
    return max;
}

This repeated != null checks and everything inside can be extracted to a method

private static <E extends Comparable<E>> E maxMaximum(E current, TreeNode<E> other) {
    if (other != null) {
        E otherMax = maximumElement(other);
        if (otherMax.compareTo(current) > 0) {
            return otherMax;
        }
    }
    return current;
}

Which leads to:

public static <E extends Comparable<E>> E maximumElement(TreeNode<E> root) {
    if (root == null) {
        throw new IllegalArgumentException("root cannot be null");
    }
    E max = root.element;
    max = maxMaximum(max, root.left);
    max = maxMaximum(max, root.right);
    return max;
}


EF lookups and enums I have a lookup table "RequestTypes" that has the following data:

ID      Type
----   -----

1      Leave
2      Loan
3      BlahBlah

Using EF, and whenever the need arise to check the type of the request, I used to do something like:

if (row.RequestType.ID == 1)
{
     // request is leave
}
else if (row.RequestType.ID == 2)
{
    // request is loan
}
//......

As you can see, there are lots of magic numbers. Anyway, I then created an enum that matches the lookup values:

public enum RequestTypesEumn
{
     Leave = 1,
     Loan = 2,
     BlahBlah = 3
}

and when I need to check the request type, I do something like:

if ((RequestTypesEumn)row.RequestType.ID == RequestTypesEumn.Leave)
{
     // request is leave
}
else if ((RequestTypesEumn)row.RequestType.ID == RequestTypesEumn.Loan)
{
    // request is loan
}
//......

That's a little bit better, except it is a lot of casting. So I created a partial class of the Request object and overloaded the == and != operators to match it against the automatically generated virtual property RequestType:

public static bool operator ==(RequestType type, RequestTypesEumn typeEnum)
{
    if (type== null)
       return false;

    return (type.ID == (int)typeEnum);
}

public static bool operator !=(RequestType type, RequestTypesEumn typeEnum)
{
    if (type== null)
       return true;

    return (type.ID != (int)typeEnum);
}

So now I can simply do:

if (row.RequestType == RequestTypesEumn.Leave)
{
     // request is leave
}
else if (row.RequestType == RequestTypesEumn.Loan)
{
    // request is loan
}
//......

Let alone inline code in ASP.NET as in repeaters and grids, for example to change the row color depending on the type we'll need to check the type and so on.

Is that a good practice? is it the best possible way to deal with enums especially when the logic requires a lot of matching as in my case?

Instead of overloading the == and != operator you could simplify the part with the heavy casting by casting only once.
Instead of multiple if..else..else if statements you should use a switch..case.
using braces {} for single statment if's will make your code less error prone.
also this will be just a typo, but you really should fix it. RequestTypesEumn vs. RequestTypesEnum this can be easily achieved if you place the cursor on the name of the enum and hit the F2 key. And while we are at this enum, the enum in the name automatically implies that these are multiple items, so RequestTypeEnum instead of RequestTypesEnum would be better.

RequestTypeEnum currentRequestType = (RequestTypesEumn)row.RequestType.ID;

switch(currentRequestType )
{
    case RequestTypeEnum.Leave:

        // request is leave
        break;

    case RequestTypeEnum.Loan:

        // request is loan
        break;

    //......
}


List contents of a folder using a shell script and mail the folder I want to list the contents of a folder and mail the list using a shell script. I Came up with the following script, please let me know if it is okay:

for file in *
do
  if [ -f "$file" ]; then
      echo "$file" | mail -s "List of files" Someone@somewhere.com
  fi
done

As @Juaniyyoo already mentioned, ls is the usual way to list all the files in a directory. I'm not sure if you really want to send a separate email for each file. If you do, you can iterate over each file with a while loop.

ls | while read file; do mail ... <<< "$file"; done

If what you really intended was to send the whole list in one go, this is even simpler.

ls | mail ...

ls has a lot of options for controlling the output format. With no options, it will just write the name of each file.  ls -l lists permissions, number of links, owner user, owner group, size, modification date and name. The date modified might be interesting, i.e. when it was received, but the other one are probably not.

ls -l | sed -E 's/([^ ]+ +){5}//' | mail ...

Use this command to filter out the first 5 columns, and thus only get the date and filename columns. You might also want to sort the output - for this use the option --sort=time.

The first output line from ls -l is a header saying something like total 8440. You can skip this first line with tail -n+2.

ls -l | tail -n+2 | sed -E 's/([^ ]+ +){5}//' | mail ...

If you want the date and time in another format, use the --time-style option for ls.

Using ls instead of your rolling with your own loop provides a lot of utility, and prevents you from "reinventing the wheel".


Get a value from a list in Sharepoint 2010 I am using SharePoint 2010 and get values from a list using the code below.

It might be called like this: getValueFromList("addresses", "secondName", "city", "manhattan");

It will return the "secondName" of the first entry that has "city = manhattan". Is there a way to make it more efficient?

private string getValueFromList(string theList, string returnColumnName,   string matchColumnName, string valueToMatch)
{
    try
    {
        SPSite siteh2 = SPContext.Current.Site;

        using (SPWeb oWeb = siteh2.OpenWeb())
        {

            //SPWeb oWeb = SPControl.GetContextSite(Context).OpenWeb();
            SPList oList = oWeb.Lists[theList];

            SPQuery oQuery = new SPQuery();
            oQuery.Query = "<Where><Eq><FieldRef Name='" + matchColumnName + "' />" +
                "<Value Type='Text'>" + valueToMatch + "</Value></Eq></Where>";

            //oQuery.Query = "<Query><Where><Eq><FieldRef Name='Username' /><Value Type='Text'>whelanp</Value></Eq></Where></Query>";

            SPListItemCollection results = oList.GetItems(oQuery);

            if (results.Count == 0)
                return "";

            foreach (SPListItem oListItem in results)
            {
                return cleanValue(oListItem[returnColumnName].ToString());
            }
            return "";
        }
    }
    catch (Exception ex)
    {
        return "";
    }
}

Naming conventions:

As per the Microsoft guidelines, use PascalCase for method names. Read more here: Capitalization Conventions. Your method names will become GetValueFromList and CleanValue.

Object Initialization and Format String:

Use the String.Format method to build your string, don't use concatenation. The building of your CAML query will be:

var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch)
};

More reading on Object and Collection Initializers.

Get SharePoint list:

Don't blindly use web.Lists["listName"], it depends on the number of lists you have in your environment what call you should use.

Using web.Lists["listName"], SharePoint will look for all lists in the current web-object and fetch all metadata from them. Then it compares the name you provided and return the correct list.

And SPWeb.GetList("url/to/list") will make a call to the DB for each list for which info is needed.

If you have a lot of lists (thousands), use the second method, otherwise the first will normally score better. Also, this depends on the performance of your hardware. But in general, I tend to avoid the indexer (using the second method or even web.TryGetList("listTitle")).

The foreach loop:

You have this piece of code:

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}

Why have a loop if you will return on the first item? If you only want to return the first entry, use the SPQuery.RowLimit property and set it to 1:

var spQuery = new SPQuery
{
    Query = String.Format("<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where>", matchColumnName , valueToMatch),
    RowLimit = 1
};

Following code:

SPListItemCollection results = oList.GetItems(oQuery);

if (results.Count == 0)
    return "";

foreach (SPListItem oListItem in results)
{
    return cleanValue(oListItem[returnColumnName].ToString());
}
return "";

will now look like this:

var results = list.GetItems(spQuery);
if (results.Count == 0)
    return "";

var item = results[0];
return CleanValue(item[returnColumnName].ToString());

Or in one return statement:

return results.Count > 0 ? CleanValue(item[returnColumnName].ToString()) : String.Empty;

Nitpicking:

Variable names:

theList should be replaced by listName or listTitle.
Avoid adding the o before the names, use spList and spQuery instead.


Reading numbers from a file with lazy ByteString This is my code for lazily reading a very large file which contains numbers separated by a new line character. Is there a way to simplify this using the ByteString module or would I have to use Data.Text

import Data.ByteString.Lazy.Char8 as L
main = do
  contents <- L.getContents
  print (sumFile contents)
     where sumFile x = sum $ Prelude.map tups $ Prelude.map L.readInt (L.words x)
         where read' = tups.(L.readInt)

tups :: (Num a) => (Maybe (a, b)) -> a
tups (Just (a,b)) = a
tups Nothing = 0

Here are some notes.

bytestring's documentation clearly states that:

  This module is intended to be imported qualified, to avoid name clashes with Prelude functions. eg.

  import qualified Data.ByteString.Lazy.Char8 as C

This lets you unambiguously write map without Prelude qualifier.

There are some properties of map that allow you to write map f . map g as map (f.g).
tups can be rewritten as one-liner with maybe and fst

tups = maybe 0 fst

All of this leads to following code:

import qualified Data.ByteString.Lazy.Char8 as L
main = L.getContents >>= print . sum . map (maybe 0 fst . L.readInt) . L.words


Computationally approximating PI Is this an efficient way to compute the value of Pi, where the limit of j \$\propto\$ accuracy?

PI = 0;

for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1);

The formula I used to write this is:

$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$

Your code will work eventually, but this series converges very very slowly.  In fact, as you can read on Wolfram's web site:

  ... this sum converges so slowly that 300 terms are not sufficient to calculate pi correctly to two decimal places!

Here's a better way to do it which implements this function:

$$ \pi = \sum_{k=0}^\infty \frac{4(-1)^k}{2k+1} \bigg(\frac{1}{2^{2k+1}} + \frac{1}{3^{2k+1}}\bigg)$$

(function(){
  PI=0;
  n=-4;
  for(k=0;k<100;k++) {
    z = 2*k+1;
    n *= -1;
    PI += n/z*(Math.pow(2, -z) + Math.pow(3, -z));
  }
  console.log(PI);
})();


Small: Setting locale I'm new to Rails/Ruby and I would like to get feedback on my little ApplicationController which is able to detect the visitor's language. I'm especially interested in optimizations on the control structure in the set_locale method (2 nested if statements and 3 assignments to one variable). I'm using the http_accept_language gem.

class ApplicationController < ActionController::Base
  AVAILABLE_LANGUAGES = %w{de en}

  before_filter :set_locale
  protect_from_forgery

  def set_locale
    if params[:locale].nil?
      if preferred_language = request.preferred_language_from(AVAILABLE_LANGUAGES)
        I18n.locale = preferred_language
      else
        I18n.locale = I18n.default_locale
      end
    else
      I18n.locale = params[:locale]
    end
  end

  def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { :locale => I18n.locale }
  end
end

You can do it in an "one-liner". Although one-liners are frequently associated with less readability, I honestly believe this is not the case. Something like this would work:

I18n.locale = params[:locale] ||
              request.preferred_language_from(AVAILABLE_LANGUAGES) ||
              I18n.default_locale

I see a few advantages in this solution:

Your code will be a bit cleaner, since you can collapse 9 lines of code filled with if/else conditions into 3 (or 1, if you don't break the line);
You won't need to allocate preferred_language in case params[:locale] is nil;
And the biggest advantage of them all: clarity. The precedence of the options is much more explicit.


Xamarin image download and resizing for Android This code addresses performance issues specific to Android running Xamarin / C# when downloading images (BMP/PNG) into a listview. The caller simply specifies the URL to fetch the image from, and the preferred dimensions.

Optimisations I could do, but haven't:

Not sure if I should use the Android or Java namespace
Stage the downloaded byte[] in an intermediate location - not sure if memory exhaustion is possible
Image caching
Convert to an Android Drawable
Abstract the source to be something other than a URL, e.g. the local resources
Make a static "helper" class (not sure how to do this...)

using System;
using System.Threading.Tasks;
using Android.Graphics;
using Android.Content.Res;
using System.Net;

namespace validAndroid
{
    public class ImageUtils
    {
        async Task<BitmapFactory.Options> GetBitmapOptionsOfImageAsync(byte[] imageBytes)
        {
            BitmapFactory.Options options = new BitmapFactory.Options {
                /*Setting the InJustDecodeBounds property to true while decoding avoids memory allocation,
                 * returning null for the bitmap object but setting OutWidth, OutHeight and OutMimeType .
                 * This technique allows you to read the dimensions and type of the image data prior to
                 * construction (and memory allocation) of the bitmap.*/
                InJustDecodeBounds = true
            };

            // The result will be null because InJustDecodeBounds == true.
            Bitmap result = await BitmapFactory.DecodeByteArrayAsync (imageBytes, 0, imageBytes.Length -1, options);

            int imageHeight = options.OutHeight;
            int imageWidth = options.OutWidth;

            System.Diagnostics.Debug.WriteLine (string.Format ("Original Size= {0}x{1}", imageWidth, imageHeight));

            return options;
        }

          static int CalculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Raw height and width of image
            float height = options.OutHeight;
            float width = options.OutWidth;
            double inSampleSize = 1D;

            if (height > reqHeight || width > reqWidth)
            {
                int halfHeight = (int)(height / 2);
                int halfWidth = (int)(width / 2);

                // Calculate a inSampleSize that is a power of 2 - the decoder will use a value that is a power of two anyway.
                while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)
                {
                    inSampleSize *= 2;
                }
            }

            return (int)inSampleSize;
        }

        async Task<Android.Graphics.Bitmap> LoadScaledDownBitmapForDisplayAsync(byte[] imageBytes, BitmapFactory.Options options, int reqWidth, int reqHeight)
        {
            // Calculate inSampleSize
            options.InSampleSize = CalculateInSampleSize (options, reqWidth, reqHeight);

            // Decode bitmap with inSampleSize set
            options.InJustDecodeBounds = false;

            return await Android.Graphics.BitmapFactory.DecodeByteArrayAsync (imageBytes,0,imageBytes.Length-1,  options);
        }

        public  async  Task<Bitmap> GetImageForDisplay(string imageURL,int reqWidth, int reqHeight )
        {
            byte[] imageBytes = null;

            using (var webClient = new WebClient())
            {
                imageBytes= webClient.DownloadData(imageURL);
            }

            BitmapFactory.Options options = await GetBitmapOptionsOfImageAsync(imageBytes);
            var bitmapToDisplay = await LoadScaledDownBitmapForDisplayAsync ( imageBytes,options, reqWidth, reqHeight);
            imageBytes = null;
            return bitmapToDisplay;
        }
    }
}

WebClient.DownloadData is a blocking method; you should use DownloadDataTaskAsync. Network I/O is almost certainly the slowest part of the whole operation, so it's important that we're not blocking here. You might also want to consider using the newer HttpClient instead of WebClient.

The third parameter of DecodeByteArrayAsync is the length of the array, but you're passing it imagesBytes.Length - 1. I think you want to pass it imageBytes.Length instead.

There's no need to set imageBytes to null.

I don't really like that LoadScaledDownBitmapForDisplayAsync modifies the options parameter. Since the method is private it's not that important, but it is, to me, surprising behaviour. To avoid this, I would consider merging GetBitmapOptionsOfImageAsync and LoadScaledDownBitmapForDisplayAsync into one method, e.g:

public static async Task<Bitmap> DecodeByteArrayAsync(byte[] imageBytes, int requiredWidth, int requiredHeight)
{
    var options = new Options { InJustDecodeBounds = true };
    await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length, options);

    options.InSampleSize = CalculateInSampleSize(options, requiredWidth, requiredHeight);
    options.InJustDecodeBounds = false;

    return await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length, options);
}


(codefights) check for almost increasing subsequence (This problem is from CodeFights, so I'm not entirely sure that I should be posting a solution here, but given that some people posted a solution to this problem in the comments I think I should be OK.)

The input to the code is an array of integers, and an almost increasing sequence is such an array that can be turned into a strictly increasing sequence of integers by removing 0 or 1 elements.  The output should be true if the array is an almost increasing sequence, and false otherwise.

boolean almostIncreasingSequence(int[] sequence) {
    boolean noFailuresYet = true;
    for(int i = 0; i < sequence.length-1; i++) {
        if(sequence[i] >= sequence[i+1]) {
            if(noFailuresYet) {
                if(i != 0 && i != sequence.length-2) {
                    if(sequence[i+1] <= sequence[i-1]) {
                        //Here we run the next iteration of the loop manually
                        //Alternatively we could set sequence[i] = sequence[i-1]
                        //but I don't want to modify the input array
                        //in case this function were to get used to check something elsewhere
                        if(sequence[i+2] <= sequence[i]) {
                            return false;
                        }
                        i++;
                    }
                }
                noFailuresYet = false;
            } else {
                return false;
            }
        }
    }
    return true;
    }

What I don't like about this code is that it has a bunch of nested if statements.

After looking at a solution code, I saw that the condition in the 2 innermost if statements could be replaced by a local check that returns false immediately if there is a certain local pattern, but I would like to know if I can reduce the nested if statements without using that (unless there is a natural way to come up with that idea by thinking about improving the code).

Break the problem into parts.

public static int findDecreasingElement(int[] sequence) {
    for (int i = 1; i < sequence.length; i++) {
        if (sequence[i - 1] >= sequence[i]) {
            return i;
        }
    }

    return sequence.length;
}

This is mostly a simpler version of your method.  But it has a couple of differences:

If we change the i to start at 1, we don't need to subtract from sequence.length.  And while we have to subtract from i, we don't need to add to i.

This returns the number of increasing elements that were found.  Now we can

    int increasingCount = findDecreasingElement(sequence);
    if (increasingCount == sequence.length) {
        // the whole sequence is increasing
        return true;
    }

    // if increasingCount is 1, then we can't check index -1
    // but the desired relationship is true
    if (increasingCount == 1 || sequence[increasingCount - 2] < sequence[increasingCount]) {
        // the element at increasingCount - 1 is exceptionally big, so remove that
        return findDecreasingElement(sequence, increasingCount) == sequence.length;
    }

    if (sequence[increasingCount - 1] < sequence[increasingCount + 1]) {
        // The element at increasingCount is exceptionally small, so remove it
        return findDecreasingElement(sequence, increasingCount + 1) == sequence.length;
    }

    // neither removing at increasingCount - 1 nor increasingCount helps
    return false;

Now we have two simple problems.  We find the longest strictly increasing sequence from the start.  If that's the whole sequence, we're done.  If not, we check to see if we can delete either of the offending elements.  If we can, check if the remainder of the sequence is increasing.

To do that, we need a new method that is almost the same as our original method.

    public static int findDecreasingElement(int[] sequence, int start) {
        for (int i = start + 1; i < sequence.length; i++) {
            if (sequence[i - 1] >= sequence[i]) {
                return i;
            }
        }

        // if there are no decreasing elements, return the index of the end
        return sequence.length;
    }

And a helper method to replace our original method.

    public static int findDecreasingElement(int[] sequence) {
        return findDecreasingElement(sequence, 0);
    }

Now we have two method signatures but only one method doing the actual work.

These smaller methods are dead simple.  Only one if and it's pretty clear why it needs to be there.  No nesting at all.

The method that calls those methods has three if statements, but they aren't nested.

In terms of performance, this does the same linear scan as the original, just in two parts.  It scans up to the first decreasing element, then it tries to scan the rest of the array.  So except for those elements right around the decreasing element, it only scans each element twice (once to compare it to the previous element and once to compare it to the succeeding element).


Retrieving an object's ID I have written the following Query to retrieve some object's ID. If there are objects in the list that have a larger numbinbatch than the saveditems number in the batch, then it should take that. If not, then it should take the first number from the lower number in batches.

I am wondering if this could be shortened. I'd also like to know if my query is bad for performance and how it can be improved.

int NextItemID = 0;
var items =
    rep.FindWhere(i => i.ID == itemID)
    .Select(i => i.Batch)
    .SelectMany(b => b.Items);

    var savedItem = items.First(i => i.ID == itemID);
    var unsavedItems = items.Where(i => i.StatusID == (short) ItemStatus.Pending);

    var higherNumInBatch = unsavedItems.Where(i => i.NumInBatch > savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
    var lowerNumInBatch = unsavedItems.Where(i => i.NumInBatch < savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);

    if (higherNumInBatch.Any())
    {
       NextItemID = (int)higherNumInBatch.Take(1).First().ID;
    }
    else
    {
       NextItemID = (int)lowerNumInBatch.Take(1).First().ID;
    }

    return NextItemID;

This will be shorter, it takes less selects, and may runs at SQL server side

return rep.FindWhere(i => i.ID == itemID)
          .SelectMany(i => i.Batch.Items)
          .Where(i => i.StatusID == (short) ItemStatus.Pending)
          .MaxBy(i => i.NumInBatch).ID;


Calculating daily project drilling hours I've got this method, and it's quite a big method. I look at it, and I feel... dirty. I feel that it's doing too much, and that there might be a better way to accomplish what I'm trying to.

/// <summary>
/// Calculates daily project drilling hours
/// </summary>
/// <param name="daily">Bool: True for daily, false for total project</param>
/// <param name="timeFrame">Bool: True for specific time frame, false for whole day </param>
/// <returns>Double:  Drilling hours for time frame</returns>
public double CalculateDrillingHours(bool daily = false, bool timeFrame = false)
{
    Logger.Info("Calculating Drilling Hours");

    var query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0";

    query = BuildQuery(query, daily, timeFrame);

    var tempList = ExecuteQuery(query);

    // The user needs to know if there was no data for the time frame chosen
    var noData = new Exception("There was no data for the selected time frame.  Please select another. (Drilling Hours)");

    if (tempList.Count < 1)
    {
        throw noData;
    }

    if(!daily)
    {
        TotalProjectDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero));

        Logger.Info("Total Drilling Hours calculated");

        return TotalProjectDrillingHours;
    }

    DailyDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero));

    Logger.Info("Daily Drilling Hours calculated");

    return DailyDrillingHours;
}

This method returns 1 of 2 items: Either Daily Drilling Hours, or Total Project Drilling Hours. This was originally two methods, but I combined them because a lot of the code was being duplicated, and it made sense at the time (about 6 months ago). But now, looking at it, I'd like to improve this. Is there a better way?

Yes, I know about parameterized queries. I've already incorporated those in the final query, which would look something like this:

query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0 AND date = @Date AND timestamp BETWEEN @StartTime AND @EndTime";

I would consider first splitting the method into smaller methods as other people have mentioned.  The only suggestion for now is I might suggest changing your bool daily to a enumeration. This in theory means it might be easier to add a Hourly,Monthly etc reporting option.  Although this is only slightly better in my opinion and I'm sure there are better approaches  (maybe using interfaces?).

Something like this as an exercise in splitting things out into various methods keeping most of your code but just re-arranging it slightly.

public double CalculateDrillingHours(DrillingPeriod period = DrillingPeriod.Daily, bool timeFrame = false)
{
    Logger.Info("Calculating Drilling Hours");
    var tempList = GetDrillingTimes(period, timeFrame);

    var drillingHours = CalculateDrillingHours(tempList);
    SetDrillingTimes(period, drillingHours);

    return drillingHours;
}

private void SetDrillingTimes(DrillingPeriod period, double drillingHours)
{
    switch (period)
    {
        case DrillingPeriod.Daily:
            Logger.Info("Total Drilling Hours calculated");
            DailyDrillingHours = drillingHours;
            break;
        case DrillingPeriod.Total:
            Logger.Info("Daily Drilling Hours calculated");
            TotalProjectDrillingHours = drillingHours;
            break;
        default:
            throw new NotImplementedException("Drilling period not supported");
    }
}

private List<DateTime> GetDrillingTimes(DrillingPeriod period, bool timeFrame)
{
    var query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0";

    var daily = period == DrillingPeriod.Daily;
    query = BuildQuery(query, daily, timeFrame);

    var tempList = ExecuteQuery(query);

    if (tempList.Any())
    {
        return tempList;
    }

    // I would look at possibly using a custom exception here i.e. NoDataException
    throw new NoDataException("There was no data for the selected time frame.  Please select another. (Drilling Hours)");
}

private double CalculateDrillingHours(List<DateTime> projectHours)
{
    return Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(projectHours)).TotalHours, 2, MidpointRounding.AwayFromZero));
}


MySQL natural search and like search I have written two queries for searching, but I want to simplify them as it seems needed.

def searching(term: String): List[String] = {
    DB.withConnection { implicit c =>
      var list = List[String]()
      val pinfo = SQL("SELECT body FROM tableName WHERE body like {term} limit 0,14 ").on("term" -> ("%" + term + "%"))()
      pinfo.map {
        row =>
          list ::= row[String]("body")
      }
      val res = SQL("SELECT body FROM tableName WHERE MATCH (body) AGAINST ({term} IN BOOLEAN MODE) limit 0,14 ").on("term" -> term)()
      res.map {
        row =>
          list ::= row[String]("body")
      }
      return list.distinct
    }
  }

Since the two queries don't depend on each other,
and they both return the same column,
it seems you can UNION them.

I cannot test this, but it seems this should work:

  def searching(term: String): List[String] = {
    DB.withConnection { implicit c =>
      val result = SQL(
        "SELECT body FROM tableName WHERE body like {liketerm} limit 0,14 " +
        "UNION " +
        "SELECT body FROM tableName WHERE " +
        "MATCH (body) AGAINST ({term} IN BOOLEAN MODE) limit 0,14 ").on(
          "liketerm" -> ("%" + term + "%"),
          "term" -> term
        )()
      result.map(row => row[String]("body")).distinct
    }
  }

Not only this is simpler,
running one query instead of two is more efficient.


Local Storage accessor and modifier helper I have created a module/factory/directive for AngularJS which allows to save user input to localStorage and restore it if needed.

Although it works quite good, I am sure that I could improve its code base and am looking for advice to do so.

It can be found on github: https://github.com/sprottenwels/saintAnthony.js

Code :

;var saintAnthony = angular.module('saintAnthony',[]);

saintAnthony.directive('savior',function(blackbox){
return{
    restrict: 'A',
    scope: true,
    link: function(scope,element,attrs){

        var elementData = {};

        var _getElementData = function(el){
            var data = {};
            var dotIndex = 0;

            el = el.isString ? el : el.toString();
            dotIndex = el.indexOf('.');

            data.container = attrs.savior !== "" ? attrs.savior : false;
            data.index = attrs.saviorindex !== undefined ? parseInt(attrs.saviorindex) : 0 ;
            data.mainGroup = dotIndex !== -1 ? el.substr(0,dotIndex) : el;
            data.key = el.substr(dotIndex +1,el.length);
            data.value = element[0].value;

            return data;
        };

        scope.saveSingleElement = function(){

            var obj = {};

            if (!blackbox.hasGroup(elementData.mainGroup)){
                blackbox.addGroup(elementData.mainGroup);
            }

            obj[elementData.key] = elementData.value;
            blackbox.updateGroup(elementData.mainGroup,obj);

        };

        scope.saveRepeatedElement = function(){
            var obj = {};

            if (!blackbox.hasGroup(elementData.container)){
                blackbox.addGroup(elementData.container,true);
            }

            obj[elementData.key] = elementData.value;
            blackbox.updateRepeatGroup(elementData.container,obj,elementData.index);
            console.dir(blackbox.groups);
        };

        element.bind('input',function(){

            elementData = _getElementData(attrs.ngModel);

            scope.$apply(function(){

                if(!elementData.container){scope.saveSingleElement();}
                else{scope.saveRepeatedElement();}

            });
        });

    }
}
});

my two cents :

add .idea to your .gitignore. If someone else uses the same IDE as you and works on this code, it could get very frustrating.
your code is not minification-proof, which can be annoying for someone who plans to use it. See angular's doc (section "a note on minification") for directions on how to fix this.
you dynamically extend String.prototype - this kind of monkey-patching can create conflicts with other libs, and lead to unexpected behaviors. If you want people to use your code, you should avoid this, especially for such simple code that you only use once.
you have two different entities defined in the same file, but that's ok as the whole lib is very lightweight. For more complex projects, split up your code, one entity per file.
your code lacks tests, which is a major no-go for many people.
instead of the quirky ng-change directive, you can directly set a change handler during the linking phase using $scope.$watch('something', function(){...}).


Overriding the mouseout handler for an image when a button is clicked I had posted this question in Stack Overflow and they told me it would be better served on Code Review.

Is there a more effecient way of changing the mouseout state when a button is clicked? When a button is clicked I want the image in the click event to take precedence over the image in the mouseout event. The following code works but I'm not sure if nesting events is a good practice.

$("#targetBtn").on({
  "mouseover" : function() {
    $(this).find('img').attr('src', 'images/_hover.png');
  },
 "mouseout" : function() {
    $(this).find('img').attr('src', 'images/_mouseout.png');
 },
 "click" : function() {
   $(this).find('img').attr('src', 'images/_selected.png');
   $(this).mouseout(function() {
      $(this).find('img').attr('src', 'images/_selected.png');
   });
  }
});

If anyone could refactor this code and show me a better way of doing this it would be greatly appreciated. Also if someone could explain why nesting events is bad (if indeed it is) I would appreciate that as well.

It is bad practice as you add a new handler each time your event is fired.

To better understand this, try this:

$('p')
  .on('click', function(e) {
    console.log('1');
    $(this).on('click', function(e) {
      console.log('2');
    });
  });

  click me

Each time you click "click me", it should log one more "2".

A better way is to refactor your code to use a flag

(function() {
    var flag = true;

    $('#targetBtn')
        .on('mouseover', function(e) {
            $(this).find('img').attr('src', 'images/_hover.png');
        })
        .on('mouseout', function(e) {
            if(flag)
                $(this).find('img').attr('src', 'images/_mouseout.png');
            else
                $(this).find('img').attr('src', 'images/_selected.png');

            // or
            // $(this).find('img').attr('src', (flag ? 'images/_mouseout.png' : 'images/_selected.png'));
        })
        .on('click', function(e) {
            flag = false;
            $(this).find('img').attr('src', 'images/_selected.png');
        });
})();

See this demonstration to grasp the result:

(function() {
  var flag = true;

  $('#targetBtn')
    .on('mouseover', function(e) {
      console.log('src', 'images/_hover.png');
    })
    .on('mouseout', function(e) {
      if (flag)
        console.log('src', 'images/_mouseout.png');
      else
        console.log('src', 'images/_selected.png');

      // or
      //console.log('src', (flag ? 'images/_mouseout.png' : 'images/_selected.png'));
    })
    .on('click', function(e) {
      flag = false;
      console.log('src', 'images/_selected.png');
    });
})();

btn