Getting a substring of a delimited string I have some underscore-delimited strings like abc_def_ghi.  I would like to get a substring out of the string made of one or more delimited substrings, so that if I call:

getUnderscoreSubstring("abc_def_ghi",2)

then I get:

abc_def

This is the C# code I'm using:

public string getUnderscoreSubstring(string fullStr,int substringCount)
{
    string[] splitArray = fullStr.Split('_');
    if (substringCount>splitArray.Count())
    {
        return null;
    }
    else
    {
        string output = "";
        for(int c=0;c<substringCount;c++)
        {
            output += splitArray[c];
            if (c<substringCount-1)
            {
                output += "_";
            }
        }
        return output;
    }
}

I'm wondering if there's a simpler way to rewrite this, possibly using extension methods.

Yes, you can definitely simplify this.

public string GetSubstring(string input, int count, char delimiter)
{
    return string.Join(delimiter.ToString(),
                       input.Split(delimiter).Take(count));
}

Calling it is as easy as GetSubstring(input, 2, '_')

What does it do?

Split the input string by the delimiter
Take the amount of substrings you want
Glue the selected substrings together with your delimiter

Very short and sexy!

This doesn't take the substringCount > splitArray.Count() in account but you can easily add that yourself: just split up the oneliner and add the appropriate check.

Now, some comments about your code:

Use .Length instead of .Count() when possible: the former will always be an O(1) operation, the latter sometimes an O(n). It won't make a difference here since an array implements ICollection<T> (and will use this optimization) but it's a good practice to observe.
Returning null is typically avoided for good reasons, consider an empty string or exception instead (don't go for the exception in this case).
I prefer to explicitly use string.Empty rather than an empty string to avoid confusion.
Write your variable names in full -- nobody is helped by abbreviating them.
Use a StringBuilder to concatenate in a loop to avoid unnecessary string object creating.
Leave some space in your code, it will read more fluently.


Using jquery Callbacks.fire method as a event handler So I've got a jquery project where I'm using an external class that has callback style events. Meaning, it has an "onSave" property that takes one function. However, I need to more than one other component to hook into it.

What I've settled on for now, goes like this:

var saveCallbacks = $.Callbacks();
saveCallbacks.fire.callbacks = saveCallbacks;
globalDoodad.onSave = saveCallbacks.fire;

which allows me to do this in my other components:

globalDoodad.onSave.callbacks.add( myMethod );

Is there a better, or at least more standard, way to handle this? It seems to be working ok, just has a bit of a smell to it.

I think what you need is a global pub-sub facility. Modules you have subscribe to certain events. These subscriptions (functions) get executed when that event is published, usually with data.

This allows different modules, from different parts of your program, to interact even without direct visibility with each other. The only dependency visible to your modules is the pub-sub module.

For instance this:

// ModuleA.js
PubSub.module('moduleA',function(tower){
  tower.subscribe('foo',function(data){
    // executes when somewhere else publishes a foo
    alert('foo executed in A with ' + data.join(' '));
  });
});

// ModuleB.js
PubSub.module('moduleB',function(tower){
  tower.subscribe('foo',function(data){
    // executes when somewhere else publishes a foo
    alert('foo executed in B with ' + data.join(' '));
  });
});

// ModuleC.js
PubSub.module('moduleC',function(tower){
  $(document).on('click',function(){
    // publish a foo event, passing 1 and 2, which arrives as "data" in each handler
    tower.publish('foo','1','2');
  });
});

jQuery has built-in event-handling capabilities, which also allow custom events. You can use this ability as your pub-sub facility.

var test = $(document);            // You can bind it to any object. document is handy.
test.on('sampleevent',function(){  // Add a handler
  alert('executed');
});

test.trigger('sampleevent');       // Execute

You can also implement your own, which doubles as a good programming practice. Here's my version of it, which I based on Node.js's EventEmitter.


Reorder list such that each element is followed by the value closest to it I just started playing with Python and was hoping to get some feedback regarding the quality of the following snippet. Does this look like proper Python? What would you change? Is this small script well structured?

Quick description of functional goal: reorder list such that each element is followed by the value closest to it, starting from 20 (AKA shortest-seek-first algorithm).

example:    [15, 24, 12, 13, 48, 56, 2]
becomes:    [24, 15, 13, 12, 2, 48, 56]

better example: [22, 19, 23, 18, 17, 16]
becomes: [19, 18, 17, 16, 22, 23]

fcfs_working = [15, 24, 12, 13, 48, 56, 2]
fcfs_track = []
track_number = 20
while len(fcfs_working) > 0:
    track_number = min(fcfs_working, key=lambda x:abs(x-track_number))
    fcfs_working.remove(track_number)
    fcfs_track.append(track_number)

while len(fcfs_working) > 0:

is the same as

while fcfs_working:


Undo Framework Design (Revert the changes in the collection) Requirement is to monitor the changes in a List<T>, possible changes are Add / Remove / Update, which are registered in an Audit log, which I do in the code underneath using a Dictionary. Now user can take an action to revert each of the operations, using an integrated Action delegate. Each operation runs its respective Revert operation. Please note here undo is not about notification, like ObservableCollection<T> but removal at the later time based on user discretion.
Following is my design, please suggest, what shall be done to further improvise.

public class ActionWrapper<T>
{
    public int Index {get;set;}
    public T OriginalValue {get;set;}
    public T NewValue {get;set;}
    public Action<int,T> Action {get;set;}
}

public class ChangeList<T> : List<T>
                             where T:class,IEquatable<T>
{
    public Dictionary<T,ActionWrapper<T>> ActionMap {get;set;}

    public ChangeList()
    {
        ActionMap = new Dictionary<T,ActionWrapper<T>>();
    }

    public new void Add(T item)
    {
        base.Add(item);

        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int,T>(RevertAdd),
            Index = this.FindIndex(x => x.Equals(item)),
            NewValue = item,
            OriginalValue = null
        };

        ActionMap[actionWrapper.NewValue] = actionWrapper;
    }

    public new void Remove(T item)
    {
        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int, T>(RevertRemove),
            Index = this.FindIndex(x => x.Equals(item)),
            NewValue = null,
            OriginalValue = item
        };

        if(actionWrapper.Index < 0)
           return;

        base.Remove(actionWrapper.OriginalValue);

        ActionMap[actionWrapper.OriginalValue] = actionWrapper;
    }

    public void Update(T actualValue,T newValue)
    {
        var actionWrapper = new ActionWrapper<T>
        {
            Action = new Action<int, T>(RevertUpdate),
            Index = this.FindIndex(x => x.Equals(actualValue)),
            NewValue = newValue,
            OriginalValue = actualValue
        };

        if (actionWrapper.Index < 0)
            return;

        base[actionWrapper.Index] = newValue;

        ActionMap[actionWrapper.NewValue] = actionWrapper;
    }

    public void RevertAdd(int index, T actual)
    {
        base.Remove(actual);
    }

    public void RevertRemove(int index,T actual)
    {
        base.Add(actual);
    }

    public void RevertUpdate(int index,T actual)
    {
        base[index] = actual;
    }
}

Use Case

void Main()
{
    var changeList = new ChangeList<string>();
    changeList.Add("Person1");
    changeList.Add("Person2");
    changeList.Add("Person3");
    changeList.Add("Person4");
    changeList.Add("Person5");
    changeList.Add("Person6");
    changeList.Add("Person7");
    changeList.Dump(); // Print statement

    var actionMapUpdateAdd = changeList.ActionMap["Person5"];
    actionMapUpdateAdd.Action(actionMapUpdateAdd.Index, actionMapUpdateAdd.NewValue);
    changeList.Dump(); // Print statement

    changeList.Update("Person7","Person77");
    changeList.Dump(); // Print statement

    var actionMapUpdate = changeList.ActionMap["Person77"];
    actionMapUpdate.Action(actionMapUpdate.Index,actionMapUpdate.OriginalValue);
    changeList.Dump(); // Print statement

    changeList.Remove("Person6");
    changeList.Dump(); // Print statement

    var actionMapRemove = changeList.ActionMap["Person6"];
    actionMapRemove.Action(actionMapRemove.Index, actionMapRemove.OriginalValue);
    changeList.Dump(); // Print statement
}

Edge cases

This fails to handle several edge-cases:

Undoing a remove action multiple times results in that item being added back multiple times.
Undoing an update action after other items have been inserted at a lower index causes the wrong items to be replaced.
Lists can contain duplicate items, but only the last operation for each distinct item is remembered.
Updating an item leaves the add-operation for the original item, but attempting to undo that add-operation fails unless the update action has first been undone.

As the last point demonstrates, you can't just undo an action without undoing all actions that followed it first. If you do want to support something like that, you'll have to clearly define the requirements and figure out what the desired behavior is for a variety of edge-cases. You'll also want to make this information available to those that will use this code (documentation, see below).

Implementation notes

Hiding methods with new is rarely a good idea: (changeList as IList<string>).Add("untracked item"); probably does not do what you want it to do. In this case, don't inherit from List<T>: implement the necessary interfaces manually, and use an internal List<T> for the actual storage.
List<T> (and IList<T>) provides some other methods (Insert, [int index] and Clear) that are not being 'intercepted', resulting in untracked changes.
Undoing an action is complicated. Why should the caller need to know whether to use NewValue or OriginalValue? That makes it difficult to use correctly. Why does the caller need to pass in any arguments at all? Why use a wrapper class if you can just create a closure with all the necessary state?
Try to use clear, descriptive names. UndoableAction and Undo are much clearer than ActionWrapper and Action, and Replace is a more accurate description of what the Update method does.
Those RevertAdd/Remove/Update methods don't seem to be intended for public use, so don't make them public. They only clutter the interface of your class.
Those ActionWrapper properties should probably not be public either, but if they have to be, then at least make them read-only. You don't want other code to be able to mess with the internals of your change-tracking/undo system. The same goes for that ActionMap property: it should only be exposed as a get-only IReadOnlyDictionary.
Documentation is entirely absent. That makes it even more difficult to tell how this class is meant to be used (or even what its exact purpose is), and various details such as Remove only removing the first matching item are left to the caller to figure out. It also makes it difficult for others to distinguish between intended and incorrect behavior.

Alternative design

I'd go for a different design, one that doesn't expose internal details, doesn't allow for out-of-order undoing (which means less edge-cases), and that provides a simple interface that's easy to use correctly (note how it's not possible to undo the same action multiple times):

public class ChangeTrackingList<T> // implements IList<T> and/or other interfaces
{
    private List<T> _items = new List<T>();
    private Stack<Action> _undoActions = new Stack<Action>();

    public bool UndoLastAction()
    {
        if (!_undoActions.Any())
            return false;

        var undoLastAction = _undoActions.Pop();
        undoLastAction();
        return true;
    }

    public void Add(T item)
    {
        _items.Add(item);

        // Ensure that this item gets removed, and not an identical earlier occurrence:
        var index = _items.Count - 1;
        _undoActions.Push(() => _items.RemoveAt(index));
    }

    ...
}


"Cut the sticks" Python implementation Problem Statement

  You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.

  Suppose we have six sticks of the following lengths:

  \$5, 4, 4, 2, 2, 8\$

  Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following:

  \$3, 2, 2, 6\$

  The above step is repeated until no sticks are left.

  Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations.

  Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks).

  Input Format

  The first line contains a single integer N.
  The next line contains N integers: \$ a_0, a_1,...a_{N-1}\$ separated by space, where \$a_i\$ represents the length of \$i^\textrm{th}\$ stick.

  Output Format

  For each operation, print the number of sticks that are cut, on separate lines.

  Constraints

  $$\begin{align}
1&≤N ≤ 1000,\\
1&≤a_i ≤ 1000,\\
\end{align}$$

  Sample Input #00

6
5 4 4 2 2 8

  Sample Output #00

6
4
2
1

Solution

def cut_stick(stick, cut_size):
    return stick - cut_size if stick > 0 else stick

def read_ints():
    return map(int, raw_input().strip().split())

def read_int():
    return int(raw_input().strip())

def main(sticks):
    while not all(x == 0 for x in sticks):
        min_cut_size = min(i for i in sticks if i > 0)
        sticks_cut = len(filter(lambda x: x >= min_cut_size, sticks))
        sticks = map(lambda x: cut_stick(x, min_cut_size), sticks)
        print sticks_cut

if __name__ == '__main__':
    _ = read_int()
    k = read_ints()
    main(k)

The problem seems too simple I wanted to come up with the solution containing readable code yet efficient at the same time. I am really not satisfied with the given solution (current solution seems \$O(n^2)\$). My basic concern is how to proceed with the proper Data structure and again write some readable code with efficiency at the same time since problems like these appear in the coding competitions most.

You are repeatedly extracting the smallest remaining numbers.

A data structure that is optimized for such operations is a priority queue, which is typically implemented using a heap.  A heap could be constructed in O(N log N) time, after which you would do N delete-min operations, each of which takes O(log N) time.  The total time to solve this challenge would be O(N log N).

Alternatively, you can sort the numbers in descending order (which takes O(N log N)), then repeatedly pop the smallest numbers off the end of the list (N times O(1)).

So, using a heapq would reduce the running time to O(N log N), and a simple sort would be a more efficient O(N log N).

In fact, after you perform the sort, you will see that it's just a simple counting exercise:

def cuts(sticks):
    sticks = list(reversed(sorted(sticks)))
    i = len(sticks)
    while i:
        # Avoid printing results in your algorithm; yield is more elegant.
        yield i
        shortest = sticks[i - 1]
        while i and sticks[i - 1] == shortest:
            i -= 1

raw_input()    # Discard first line, containing N
for result in cuts(int(s) for s in raw_input().split()):
    print(result)

Here's an implementation of the same idea, but using itertools.groupby to avoid keeping track of array indexes:

from itertools import groupby

def cuts(sticks):
    sticks = list(sticks)
    sticks_remaining = len(sticks)
    stick_counts_by_len = groupby(sorted(sticks))
    while sticks_remaining:
        yield sticks_remaining
        number_of_shortest_sticks = len(list(next(stick_counts_by_len)[1]))
        sticks_remaining -= number_of_shortest_sticks


Java hashCode method in VB.NET The point of this method is to emulate Java hashCode().

In order for this to work the project must have arithmetic overflow allowed under:

  project --> compiler options --> advanced.

    Public Shared Function GetHashCodeStr(value As String) As Integer
        Dim finalCode As Integer = 0

        For i As Integer = 0 To value.Length - 1
           Dim powerValue = (Convert.ToInt32(value(i)) * Math.Pow(31, value.Length - 1 - i))

        If powerValue > Integer.MaxValue Then
            Dim timesGreaterThanInt = Math.Floor(powerValue / Integer.MaxValue)
            powerValue = powerValue - timesGreaterThanInt - (timesGreaterThanInt) * Integer.MaxValue
        End If

        finalCode += CInt(powerValue)
    Next

    Return finalCode
End Function

I know little about this language, but dealing with powers of 31 is surely no good idea. Most probably, it'll overflow or lose precession and you get pure garbage.

If there's something like long (64 bit integer), you can rewrite the Java implementation easily. The only relevant part is the loop doing

h = 31*h + val[off++];

Just reduce h after every iteration to the int range, so it doesn't crash your Windows overflow.

Actually, you need no long, a double (floating point with 56 bits of mantissa) would do. Simple float (24 bits mantissa) is unusable here.


How many ways we can make the change of the amount using the coins given Given a set of coins and amount, write an algorithm to find out how
  many ways we can make the change of the amount using the coins given.

  Example:

  Amount = 5

  coins [] = {1,2,3}

  Ways to make change = 5

  {1,1,1,1,1} {1,1,1,2}, {1,2,2}, {1,1,3} {2,3}

The code I've written works flawlessly, but the time complexity is too high. If you could suggest an improvement for this code or suggest a better approach, please let me know.

public class CoinChangeProblem {
    public static void main(String[] args) {

        calculatePossibleCombinations(0, 0);
        System.out.println("Answer : "+totalCombinations);

    }

    static int[] coins = { 1, 2, 3};
    static int amount = 5;

    static int totalCombinations= 0;

    static void calculatePossibleCombinations(int pos, int sum)
    {
        if(pos< coins.length)
        {
            int coin = coins[pos];
            for(int j=0; j<=amount/coin && sum<=amount; j++)
            {
                calculatePossibleCombinations(pos+1, sum);
                sum = sum + coin;
                if(sum == amount)
                {
                    totalCombinations++; break;
                }
            }
        }
    }
}

Got it working faster! Here's my updated code. I was able to use DP and memoize.

static int calculatePossibleCombinations(int pos, int amount)
{
    if(amount == 0)
    {
        return 1;
    }

    if(pos < coins.length)
    {
        int ways = 0;
        int remainingAmount= 0;
        String key = pos + "-" + amount;

        if(memoizeMap.containsKey(key)) {
            return memoizeMap.get(key);
        }

        while(remainingAmount <= amount)
        {
            ways = ways + calculatePossibleCombinations(pos+1, amount- remainingAmount);
            remainingAmount = remainingAmount + coins[pos];
        }
        memoizeMap.put(key, ways);
        return ways;
    }
    return 0;
}


Recursive Web Scraping with Python Beautiful Soup I wrote a short program which should allow a user to specify a starting page in Discogs Wiki Style Guide, scrape the other styles listed on the page, and then output a graph (represented here as a dictionary of sets) of the relationship between subgenres.

I'm looking for guidance/critique on: (1) How to clean up the request_page function, I think there is a more elegant way both getting href attrs and filtering to only those with "/style/". (2) The general structure of the program. Self-taught and relative beginner so it's highly appreciated if anyone could point out general irregularities.

import re
import requests
from bs4 import BeautifulSoup

def get_related_styles(start):

    def request_page(start):

        response = requests.get('{0}{1}'.format(base_style_url, start))
        soup = BeautifulSoup(response.content,'lxml')

        ## these lines feel inelegant. considered solutions with
        ## soup.findAll('a', attrs = {'href': pattern.match})

        urls = [anchor.get('href') for anchor in soup.findAll('a')]
        pattern = re.compile('/style/[a-zA-Z0-9\-]*[^/]') # can use lookback regex w/ escape chars?
        style_urls = {pattern.match(url).group().replace('/style/','') for url in urls if pattern.match(url)}

        return style_urls

    def connect_styles(start , style_2):

        ## Nodes should not connect to self
        ## Note that styles are directed - e.g. (A ==> B) =/=> (B ==> A)

        if start != style_2:
            if start not in all_styles.keys():
                all_styles[start] = {style_2}

            else:
                all_styles[start].add(style_2)

        if style_2 not in do_not_visit:
            do_not_visit.add(style_2)
            get_related_styles(style_2)

    style_urls = request_page(start)

    for new_style in style_urls:
        connect_styles(start,new_style)

Example Use:

start = 'Avant-garde-Jazz'
base_style_url = 'https://reference.discogslabs.com/style/'

all_styles = {}
do_not_visit = {start}

get_related_styles(start)

print(all_styles)
{'Free-Jazz': {'Free-Improvisation', 'Free-Funk'}, 'Free-Improvisation': {'Free-Jazz', 'Avant-garde-Jazz'}, 'Avant-garde-Jazz': {'Free-Jazz'}, 'Free-Funk': {'Free-Jazz'}}

There is a simpler way to filter out the "style" links - using a CSS selector with a partial match on the href attribute:

style_urls = {anchor['href'].replace('/style/', '')
              for anchor in soup.select('a[href^="/style/"]')]

where ^= means "starts with".

Here we, of course, lose the check we had on the style name part of the href. If this check is really needed, we can also use a regular expression to match the desired style links directly:

pattern = re.compile('/style/([a-zA-Z0-9\-]*)[^/]')
style_urls = {pattern.search(anchor['href']).group(1)
              for anchor in soup('a', href=pattern)

soup() here is a short way of doing soup.find_all().


Boost multi-index based orderbook As suggested here, I'm using Boost multi-index to implement orderbook. So far my code looks like this:

"CommonsNative.h" contains typedef int64_t myDecimal; and enum Side { Buy, Sell };

#pragma once

#include "CommonsNative.h"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>

using boost::multi_index_container;
using namespace boost::multi_index;

struct OrderBookItem {
    myDecimal price;
    int32_t lots;
    OrderBookItem(myDecimal price_) :price(price_), lots(0) {

    }
};

typedef multi_index_container
    <OrderBookItem, indexed_by<

    hashed_unique<
    BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)
    >,

    ordered_unique<
    BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price),
    std::greater<myDecimal> /* sorted beginning with most frequent */
    >

    >> OrderBookContainer;

class OrderBook
{
public:
    OrderBook(void);
    ~OrderBook(void);
    void Add(Side side_, myDecimal price_, int lots_)
    {
        if (side_ == Buy) {
            // inserts or returns existent
            OrderBookContainer::iterator it = buyContainer.insert(price_).first;
            // how to add lots i.e. OrderBookItem.lots += lots_?
            // auto curLevel = buyContainer.get<name>(price);
            // curLevel.lots += Lots;
        } else if (side_ == Sell) {
            // inserts or returns existent
            OrderBookContainer::iterator it = sellContainer.insert(price_).first;
        }
    }
private:
    OrderBookContainer buyContainer;
    OrderBookContainer sellContainer;
};

I have the following questions:

For here:

OrderBookContainer::iterator it = buyContainer.insert(price_).first;

If I already have an item with price = price_ I receive it in \$O(1)\$ (from hashtable). If such a level doesn't exist, then is it added in \$O(log n)\$? If I'm wrong, then what should I write to get an item if it exists (in \$O(1)\$) otherwise add it (in \$O(log n)\$)?
Once I have an item, how can I modify lots to something like this?

OrderBookItem.lots += lots_

myDecimal is an absolutely unhelpful name overall.  I don't see any need to give int64_t a typedef here, but even if there is one, then it should still use a better name.
Empty void parameters are not needed in C++:

OrderBook(void);
~OrderBook(void);

You also don't need these defaults as the compiler will provide them for you.  They would only be necessary if you need to overload them and will still need default versions.
It's a little less-readable not having whitespace after commas:

BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)

Not only that, but you already add this whitespace in other places.  Keep it consistent.

BOOST_MULTI_INDEX_MEMBER(OrderBookItem, myDecimal, price)

You use different styles of curly braces.  C++ doesn't restrict you to a particular one, so choose one you prefer and stick with it.
Although this line has been commented out, are you still using C++11?

// auto curLevel = buyContainer.get<name>(price);

If so, then you can replace OrderBookContainer::iterator with auto:

auto it = buyContainer.insert(price_).first;

auto it = sellContainer.insert(price_).first;


Duplicate code in day of the week event handlers private static void OnSundayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        BinaryDataGrid c = sender as BinaryDataGrid;
        if (c != null)
        {

            if (_shouldCallBack)
            {
                if (c.Sunday.Length == 4)
                    return;
                Days day = (Days)c.dataGrid.Items[0];
                byte[] newArray = new byte[c.Sunday.Length + 1];
                newArray[0] = Convert.ToByte(0);
                c.Sunday.CopyTo(newArray, 1);
                day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);
                _sun = day.Value;
            }
            else
            {
                _shouldCallBack = true;
                c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray();
            }
        }
    }

    private static void OnMondayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {

        BinaryDataGrid c = sender as BinaryDataGrid;
        if (c != null)
        {
            if (_shouldCallBack)
            {
                if (c.Monday.Length == 4)
                    return;
                Days day = (Days)c.dataGrid.Items[1];
                byte[] newArray = new byte[c.Monday.Length + 1];
                newArray[0] = Convert.ToByte(0);
                c.Monday.CopyTo(newArray, 1);
                day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);
                _mon = day.Value;
            }
            else
            {
                _shouldCallBack = true;
                c.Monday = BitConverter.GetBytes(_mon).Reverse().ToArray().Skip(1).ToArray();
            }
        }
    }

I've got the same code for every week day, how can I generalize this so I don't have 6 duplicates of the code above?

What you need to do is:

Add a parameter of type System.DayOfWeek called, say, day_of_week.
Replace the fields BinaryDataGrid.Sunday, .Monday, etc. with a Dictionary<K,V> that has a key of type System.DayOfWeek and use day_of_week to access values within that dictionary.
Do the same for your _sun, _mon etc. global variables. (For which you will burn in hell, incidentally.)

If you cannot modify BinaryDataGrid, then write two helper methods, one for getting and one for setting the value of the day member of BinaryDataGrid: Each method has a switch( day_of_week ) and modifies the appropriate member of BinaryDataGrid.

Good luck and have fun.


Python function to match filenames with extension names I have written a Python function which matches all files in the current directory with a list of extension names. It is working correctly.

import os, sys, time, re, stat

def matchextname(extnames, filename):
    # Need to build the regular expression from the list
    myregstring = ""
    for index in range(len(extnames)):
        # r1 union r2 and  so on operator is pipe(|)
        # $ is to match from the end
        if index <  len(extnames) - 1:
            myregstring =  myregstring + extnames[index] + '$' + '|'
        else:
            myregstring = myregstring + extnames[index] + '$'
    # getting regexobject
    myregexobj = re.compile(myregstring)
    # Now search
    searchstat = myregexobj.search(filename)
    if searchstat:
        print 'Regex', filename

It is called like this:

if __name__ == '__main__':
    fileextensions = ['\.doc', '\.o', '\.out', '\.c', '\.h']
    try:
        currentdir = os.getcwd()
    except OSError:
        print 'Error occured while getting current directory'
        sys.exit(1)
    for myfiles in os.listdir(currentdir):
        matchextname(fileextensions, myfiles)

Could you please review the code and suggest if there is any better way of doing this, or share any other comments related to errors/exception handling which are missing - or anything else in terms of logic?

.endswith() accepts a tuple:

#!usr/bin/env python
import os

fileextensions = ('.doc', '.o', '.out', '.c', '.h')
for filename in os.listdir(os.curdir):
    if filename.endswith(fileextensions):
       print(filename)


Selecting users with biopsies in a given country for charting I have this monstrosity

    @nation_biopsy =
       User.all.where(country: @nation).group_by{ |u| [u.institute_type, u.biopsy] }
      .map{ |i, o| ["name" => i[0], "y" => User.where(id: o.map(&:id))
      .sum("biopsy")]}.flatten.to_json

What it is doing is finding all the users in my database that belong to a country (@nation) and grouping them according to their "institute_type" and then "biopsy" (both columns for users). Then it is trying to convert it to an array of JSON objects for a "Highcharts" script. It works, but as a newbie I am sure this is very database heavy. Is there a better way?

Some notes on your code:

User.all.where -> User.where.
The moment you write group_by you are not using SQL anymore, performance will suffer.
The line starting with sum is very confusing, the indentation make you think it's the continuation of map but in fact it's part of its inner expression. Indentation should reflect the structure of an expression.
map + flatten -> flat_map.
|pair, something| and then pair[0]. You can de-structure arrays using the syntax |(k, v), something|.

On a first refactor, I'd write:

@nation_biopsy = User
  .where(country: @nation)
  .group_by { |u| [u.institute_type, u.biopsy] }
  .flat_map do |(institute_type, biopsy), users|
    ["name" => institute_type, "y" => User.where(id: users.map(&:id)).sum("biopsy")]
  end.to_json

On a second refactor, I'd try to make it work with SQL. Something like this:

@nation_biopsy = User
  .where(country: @nation)
  .group(:institute_type, :biopsy)
  .select(:institute_type, "SUM(biopsy) AS biopsy_count")
  .flat_map { |group| ["name" => group.institute_type, "y" => group.biopsy_count] }
  .to_json

Now, if you want to write something fancy use Arel, it allows you to write it without SQL fragments, which looks kind of cool:

users = User.arel_table
@nation_biopsy = User
  .where(users[:country].eq(@nation))
  .group(users[:institute_type], users[:biopsy])
  .select(users[:institute_type], users[:biopsy].sum.as("biopsy_count"))
  .flat_map { ["name" => group.institute_type, "y" => group.biopsy_count] }
  .to_json


Student Attendance Record II I'm currently working on the Student Attendance Record II problem:

  Given a positive integer \$n\$, return the number of all possible
  attendance records with length \$n\$, which will be regarded as
  rewardable. The answer may be very large, return it after mod 109 + 7.

  A student attendance record is a string that only contains the
  following three characters:

'A' : Absent.
'L' : Late.
'P' : Present.

  A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

The idea is to use Dynamic Programming to use the results for smaller n to calculate the results of bigger n. I'm currently keeping two lists - one to track L and P and the other - to track A:

MODULO = 10 ** 9 + 7

class Solution(object):
    def checkRecord(self, n):
        lates = [[0, 0, 0], [1, 1, 0]] + [[0, 0, 0] for _ in xrange(2, n + 1)]
        absences = [[0, 0, 0], [1, 0, 0]] + [[0, 0, 0] for _ in xrange(2, n + 1)]

        for i in xrange(2, n + 1):
            last_late_row = lates[i - 1]
            last_late_row_sum = last_late_row[0] + last_late_row[1] + last_late_row[2]

            last_absence_row = absences[i - 1]
            last_absence_row_sum = last_absence_row[0] + last_absence_row[1] + last_absence_row[2]

            lates[i] = last_late_row_sum % MODULO, last_late_row[0], last_late_row[1]
            absences[i] = ((last_late_row_sum + last_absence_row_sum) % MODULO, last_absence_row[0], last_absence_row[1])

        return (sum(lates[n]) + sum(absences[n])) % MODULO

The code works, but it does not pass the Time Limit requirements for big n. Even though, for n = 100000 LeetCode OJ runs it for only ~220ms.

How would you recommend to improve on running time?

It's often helpful to explain the problem to someone else just to see things clearer and come up with a possible solution. Here is what I've just realized.

We don't actually need to keep the complete list during our calculations and only need a single row at a time. Let's reuse it and recalculate the cell values in the loop:

MODULO = 10 ** 9 + 7

class Solution(object):
    def checkRecord(self, n):
        lates = [1, 1, 0]
        absences = [1, 0, 0]

        for i in xrange(2, n + 1):
            sum_lates = sum(lates)
            lates = sum_lates % MODULO, lates[0], lates[1]
            absences = (sum_lates + sum(absences) % MODULO, absences[0], absences[1])

        return (sum(lates) + sum(absences)) % MODULO

I think I've seen this technique before and, if I remember correctly, it is called "Rolling Array".


Finding the length of shortest transformation sequence from start to end Please treat this as a interview at a top tech firm, and share your thoughts on how you think I did. Be honest, and leave no stone unturned.

  Problem:

  Given two words (start and end), and a dictionary, find the length of
  shortest transformation sequence from start to end, such that:

  Only one letter can be changed at a time.  Each intermediate word must
  exist in the dictionary

  For example,

  Given:

  start = "hit"
  end = "cog"
  dict = ["hot","dot","dog","lot","log"]

  As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" ->
  "cog", return its length 5.

  Note:

  Return 0 if there is no such transformation sequence.
  All words have the same length.
  All words contain only lowercase alphabetic characters.

Time Complexity: \$O(n^2)\$ (please confirm)

Space complexity: \$O(n)\$

My code:

   private static int ladderLength(String start, String end, HashSet<String> dict) {
        Deque<String> wordSearch = new ArrayDeque<>();
        Deque<Integer> lengthCount = new ArrayDeque<>();
        wordSearch.add(start);
        lengthCount.add(1);
        while(!wordSearch.isEmpty()){
            String analyzing  = wordSearch.poll();
            int curCount = lengthCount.poll();
            if(analyzing.equals(end)){
                return curCount;
            }
            for(int j = 0; j < analyzing.length(); j++){
                for(char i = 'a'; i <= 'z'; i++){
                    char[] possibleMatch = analyzing.toCharArray();
                    possibleMatch[j] = i;
                    String checkMatch = new String(possibleMatch);
                    if(dict.contains(checkMatch)){
                        dict.remove(checkMatch);
                        lengthCount.add(curCount + 1);
                        wordSearch.add(checkMatch);
                    }
                }
            }
        }
        return 0;
   }

First of all, I really liked that your logic doesn't need to compare lengths: as soon as a match is found, it must be one of the shortest lengths, nice! And when the end is unreachable, the method returns 0, an impossible answer (since a valid length must be >= 1), so that's good too.

A couple of things can be improved.

Choose the right interfaces

Your method should work with Set<String> dict, and should not limit users to HashSet<String> dict.

Choose the right classes

A Deque is a collection that supports element insertion and removal at both ends. That's more than what you need. A Stack would have been enough for your purpose.

Simplify the inner for loops

The inner for loops are a bit wasteful and can be simplified. You are basically iterating over all possible 1-letter differences and check if in the dictionary. Instead, you could iterate elements of the dictionary and see if they have 1 letter difference. For example like this:

for (String item : dict.toArray(new String[dict.size()])) {
    if (isSingleCharDiff(analyzing, item)) {
        dict.remove(item);
        lengthCount.add(curCount + 1);
        wordSearch.add(item);
    }
}

Discrepancy with the specs

The problem description says:

  dict = ["hot","dot","dog","lot","log"]

With this exact input your method returns 0 because it will never reach end. The fix is simple enough, just add it to the dictionary somewhere near the start:

dict.add(end);

A wasted operation

Before the while loop, you do this:

wordSearch.add(start);
lengthCount.add(1);

but then inside the loop you immediately pop them. You could rework the code to eliminate that wasted operation:

String analyzing = start;
int curCount = 1;
while (true) {
    if (analyzing.equals(end)) {
        return curCount;
    }
    for (String item : dict.toArray(new String[dict.size()])) {
        if (isSingleCharDiff(analyzing, item)) {
            dict.remove(item);
            lengthCount.add(curCount + 1);
            wordSearch.add(item);
        }
    }
    if (wordSearch.isEmpty()) {
        break;
    }
    analyzing = wordSearch.pop();
    curCount = lengthCount.pop();
}


Graph Creation and BFS + DFS in C# I was asked to implement a graph and BFS and DFS.

Please comment. Is it understandable? Is my algorithm correct? Are there any optimizations?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Graph
    {
        public List<Node> list;
        public Graph()
        {
            list = new List<Node>();
        }
    }

    public class Node
    {
        public int Index { get; set; }
        public List<Node> neighbors;
        public Node(int index)
        {
            Index = index;
            neighbors = new List<Node>();
        }
        public void AddNeighbor(int index)
        {
            neighbors.Add(new Node(index));
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class BFS
    {
        public BFS()
        {
              Graph graph = new Graph();
              graph.list.Add(new Node(0));
              graph.list.ElementAt<Node>(0).AddNeighbor(1);
              graph.list.ElementAt<Node>(0).AddNeighbor(2);
              graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
              GraphTraverseBFS(graph);
        }
        public void GraphTraverseBFS(Graph graph)
        {
            Queue<Node> queue = new Queue<Node>();
            queue.Enqueue(graph.list[0]);
            while(queue.Count > 0)
            {
                Node tempNode = queue.Dequeue();
                Console.WriteLine("Node number: " +tempNode.Index);
                foreach (var item in tempNode.neighbors)
                {
                    queue.Enqueue(item);
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class DFS
    {

        public Graph graph { get; set; }
        public DFS()
        {
              graph = new Graph();

              graph.list.Add(new Node(0));
              graph.list.ElementAt<Node>(0).AddNeighbor(1);
              graph.list.ElementAt<Node>(0).AddNeighbor(2);
              graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3);
              GraphTraverseDFS(graph);
        }

        public void GraphTraverseDFS(Graph graph)
        {
            Stack<Node> stack = new Stack<Node>();
            stack.Push(graph.list[0]);
            while (stack.Count != 0)
            {
                Node tempNode = stack.Pop();
                Console.WriteLine("Node number: " + tempNode.Index);
                var negibours = tempNode.neighbors;
                foreach (var item in negibours)
                {
                    stack.Push(item);
                }
            }
        }
    }
}

Let's take a step back and consider the API.

Suppose I want to test the BFS traversal on different graphs.

To call GraphTraverseBFS I need to first create a BFS object. But the BFS constructor creates its own graph and runs GraphTraverseBFS on that. There is no clean way for me to just test it on my own graph.

So let's say that's fixed. Now I want to write some unit tests for GraphTraverseBFS. I can't currently do this without redirecting where the output messages are written to, and then parsing the output. This is more work than I want to do. Ideally I would be able to write something like

CollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, BFS.Traverse(graph));

The same comments hold for DFS.

List<T> is (generally) an implementation detail.

Graph has a public field List<Node> list. The fact that you're storing nodes in a List is an implementation detail, and should not be exposed to users of this code.

The user now has full access to the methods of List, and can manipulate the list however they want. This is more power than they should have.
The user can reassign the field, e.g. graph.list = null.
It locks you in to your choice of graph representation, as the user may write code that depends on list being a List.

Similar comments hold for Node.neighbors.

One pattern I like for letting the user iterate over a collection, without exposing the choice of implementation is to

Have a private readonly field with your choice of collection type (List, HashSet, etc)
Have a public IEnumerable<T> read-only property that exposes the collection for iteration

In code, it looks like this

public class Graph
{
    private readonly List<Node> nodes = new List<Node>();

    public IEnumerable<Node> Nodes
    {
        get { return this.nodes; }
    }

    ...
}

This might not be entirely suitable for you needs, but this is the sort of API I would suggest

public class Graph
{
    // Creates a new graph with `count` vertices.
    public Graph(int count)

    public IEnumerable<int> GetNeighbors(int node);

    public void AddEdge(int n, int m);
}

public static class BFS
{
    public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);
}

public static class DFS
{
    public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);
}


Deal action with a pack of cards I have a pack of cards and I am doing a 'deal' action. I am dealing n number of cards, for now to one player.

How can I DRY up the while and unless loops to have fewer lines?

def deal(number_of_players, number_of_cards_each)

 # 1..number_of_players

  players_cards_array=[]

  (1..number_of_cards_each).each do |a_card|

    added_card=false
    while added_card==false
      new_card = choose_card()
      unless @currently_dealt_cards.include?(new_card)
        players_cards_array << new_card
        added_card= true
        @currently_dealt_cards << new_card
      end
    end
  end

  return players_cards_array

end

I agree with @mnhg: if you had the collection of cards beforehand, things would simplify dramatically:

players_cards = all_cards.sample(nplayers * ncards_each).each_slice(ncards_each).to_a


Networking library for c++ linux #include <sys/types.h>
#include <sys/socket.h>

#include <netdb.h>
#include <string.h>
#include <unistd.h>

#include <string>
class Website
{
    int status, sock;
    struct addrinfo hints;
    struct addrinfo *servinfo;
    public:
      int init(std::string url){
          memset(&hints, 0, sizeof hints);
          hints.ai_family = AF_UNSPEC;
          hints.ai_socktype = SOCK_STREAM;
      if((status = getaddrinfo(url.c_str(), "80", &hints, &servinfo)) != 0){
              return status;
          }
          if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
              return -1;
      }
          return 0;
       }
     int connectToSite(){
        return connect(sock, servinfo->ai_addr, servinfo->ai_addrlen);
     }
     int sendToSite(std::string request){
        return send(sock, request.c_str(), strlen(request.c_str()), 0);
     }
     int recvFromSite(char buf[], int maxsize){
        return recv(sock, buf, maxsize, 0);
     }
    void closeSocket(){
      close(sock);
      freeaddrinfo(servinfo);
     }
};

I have a networking class that implements low level c functions in a simple class. I am looking to make my code more efficient

Observation:
I don't like the design.
You are using a two phase initialization. You construct the object (thus constructor) and then call an init() function. Two phase initialization is a bad idea as you can't tell (or have to validate) the state of the object before it can be used.
A better technique is to simply use the constructor to initialize the object. If the constructor fails then the throw so the object never exists and can't be used incorrectly.
You also have an explicit close (closeSocket()) which is fine to an extent but you are forcing people to remember to call this function when you are done with the object. This is what a destructor is for.
You need to look up the concept of RAII.
{
    Website    site("Stuff"); // All resources allocated
}
// All resources for `site` are now released.

Design
What is the use of connectToSite(), is that not the init? Can you call read/write before calling this? If not then read/write are on the wrong object and connect should return you the appropriate object that has the read/write interface.

This is how I would want to use an object called "WebSite"
{
    // An abstract object that represents the site.
    // No actual underlying connection as connections are
    // usually to resources on the site not the actual site.
    Website    site("thorsanvil.com", 80);

    // Create a connection to a specific resource on the site.
    Connection c = site.open("Path");

    // Object was created successfully so we have
    // a valid connection to a server we can not communicate with.
    c.writeData("This is a message");
    std::string resp = c.read();
 }

From your interface. I would look to rename your class to "Connection" then the expectations for how to use the object may be more like.
 {
    // Create the socket and connect to the site.
    Connection   c("https://thorsanvil.com/MyResource");

    // Object was created successfully so we have
    // a valid connection to a server we can not communicate with.
    c.writeData("This is a message");
    std::string response = c.readData();
 }

Code Review:
You don't want to use C++ strings?
#include <string.h>

A URL?
  int init(std::string url)

Sure but the name of the class is "Website". A url is a lot more than just a website. There is a schema/host(hostname/port/user/password)/path/query/fragment. Would you not just pass a host and for the connection maybe a port.
Or you could pass the whole url but each new connection needs a new URL not just the website.

You are returning the status code here (on error):
  if((status = getaddrinfo(url.c_str(), "80", &hints, &servinfo)) != 0){
          return status;
      }

But here you are retuning -1
      if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
          return -1;
      }

Are you sure those error ranges do not overlap?
I think a better interface would be to throw an exception if something goes wrong.

This is not going to work for the generic URL.
  status = getaddrinfo(url.c_str(), "80" ....

The port is not always 80.
The default port is defined by the schema "http/https ..."
The default can be overridden by the url itself.

Example:
  https://thorsanvil.com:1222/Work

  Schema:   https
  Site:     thorsanvil.com
  Port:     1222             overrides default 443 for https
  Path:     /Work
  Query:    Empty
  Fragment: Empty

Really the above code should be:
  status = getaddrinfo(getHost(url), getPort(url), ....

What happens of connect() fails? Are you expecting the user to check the error code?
 int connectToSite(){
    return connect(sock, servinfo->ai_addr, servinfo->ai_addrlen);
 }

That's very C like interface and very error prone to use. We know that users of API don't always check error codes. Don't leak this ingormation. Make it explicit with an exception.

This is not how you use send() and recv() the return value indicates how much of the message was sent/recved. You need to repeatedly call this functions until the message is sent or there is an error.
 int sendToSite(std::string request){
    return send(sock, request.c_str(), strlen(request.c_str()), 0);
 }
 int recvFromSite(char buf[], int maxsize){
    return recv(sock, buf, maxsize, 0);
 }

Research
Have a look at this class:
https://github.com/Loki-Astari/ThorsSocket/blob/master/src/ThorsSocket/Socket.h


A basic calculator in C that uses a loop I have created a program that forms a basic calculator in C which includes the basic operations like addition, subtraction, multiplication and division. But in this case I decided to use a Do-While loop. It is working.

I would appreciate to be pointed out some mistakes and opinions to make the code more presentable.

I have only one question which is:

instead of using a single character like:

while( choice == 'y' || choice == 'Y' );

why can't I use a string? ie.

printf("would you like to try again? \"yes or no\"\n");
scanf(" %s", &choice);
}
while ( choice == 'yes' || choice == 'YES' );

My code is as given as below...

 #include <stdio.h>
 #include <stdlib.h>

 int main()
 {
     float a, b, c;
     int n;
     char choice = 'y' ;

     do
     {
         printf("Please enter any number:\n");
             if (scanf("%f", &a)!=1){
                 fprintf(stderr, "error: first input must be a number\n");
                     return EXIT_FAILURE;}

         printf("Please choose any of the operator:\n");
         printf(" 1.addition\n 2.subtraction\n 3.multiplication\n 4.division\n");
             scanf(" %d", &n);

         printf("Please enter any number:\n");
             if (scanf("%f", &b)!=1){
                 fprintf(stderr, "error: second input must be a number\n");
                     return EXIT_FAILURE;}

         switch(n)
         {
             case 1 :
                 c = a + b;
                     printf("The answer is:%f\n", c);
             break ;

             case 2 :
                 c = a - b;
                     printf("The answer is:%f\n", c);
             break;

             case 3 :
                 c = a * b;
                     printf("The answer is:%f\n", c);
             break;

             case 4 :
                 c = a / b;
                     printf("The answer is:%f\n", c);
             break;

             default :
                     printf("You have not chosen the given operators\n");
             }

                     printf("would you like to try again? (y/n)\n");
                         scanf(" %c", &choice);
     }

     while( choice == 'y' || choice == 'Y');
         getch();

     return 0;
 }

Indentation

Frankly, your indentation is all over the place!

The basic idea of indentation is that you indent based on scope. A scope begins with { and ends with } (you can omit the { } sometimes but you shouldn't). I'll indent a few snippets of your code and you can do the rest. You seem to put { on the next line more often than you put { on the same line so that's the convention I've used. Using this convention, the { should be indented to the same depth as the matching }.

printf("Please enter any number:\n");
if (scanf("%f", &a) != 1)
{
    fprintf(stderr, "error: first input must be a number\n");
    return EXIT_FAILURE;
}

// ...

switch(n)
{
    case 1:
        c = a + b;
        printf("The answer is:%f\n", c);
        break;
}
printf("would you like to try again? (y/n)\n");
scanf(" %c", &choice);

Indentation is really the only major problem with this code.

Extensibility

You could use doubles instead of floats to gain a little bit of extra precision. If you want to make this program really easy to extend (after you've learnt about a bunch of new stuff) then you could store the operations in an array. Then the user will type add you'll look up a function pointer in an array. Something like this:

typedef struct {
    const char *name;
    double (*func)(double, double);
} Operation;

const Operation ops[] = {
    {"add", add},
    {"sub", sub}
    // ...
};

I'll let you figure out the details. Some things you'll need to look up are arrays, structs, function pointers and string comparison (strcmp).

Unary operations

You could complicate things further by allowing unary operations (e.g. sin, sqrt). You'll need separate arrays for unary and binary operations.

typedef struct {
    const char *name;
    double (*func)(double);
} UnaryOperation;

typedef struct {
    const char *name;
    double (*func)(double, double);
} BinaryOperation;

Parsing

If you're up for a real challenge you could allow the user to enter an expression like 14 + 2 * sin(0.8) and evaluate the expression. This sort of thing is quite tricky indeed! You'll need to learn about recursive descent parsing (there are other types of parsing but this is probably the easiest), memory management and pointers. The last time I did something like that, the resulting program was 700 lines so it's quite a step up from the code in your question.


Fibonacci using OOP methods in Java I made a simple program that uses OOP methods. Please tell me if I used the 4 methods right. And if not, please show me how.

class Encap{
    private String name;
    public void setName(String newValue){
        name = "Hello, "+newValue+"!";
    }

    public String getName(){
        return name;
    }
}

abstract class Abstraction {
    int fibCount, flag=0, y;
    String inputName;
    String names[] = new String [] {"Anna","Joe","Carl"};
    Scanner x = new Scanner(System.in);
abstract void abscompute();
}

class abs2 extends Abstraction{
    @Override
    void abscompute()
    {
         System.out.print("Enter number of fibonacci: ");
         fibCount = x.nextInt();
         int[] fib = new int[fibCount];
         fib[0] = 0;
         fib[1] = 1;
         for(int i=2; i < fibCount; i++){
             fib[i] = fib[i-1] + fib[i-2];
         }

         for(int i=0; i< fibCount; i++){
                 System.out.print(fib[i] + " ");

                }

    }
}
public class Fibonacci {

    public static void main(String[] args) {
        Abstraction abs = new abs2();
        Encap encap = new Encap();
        System.out.print("Enter your name: ");
        abs.inputName = abs.x.next();
        for (String name : abs.names) {
            if(abs.inputName.equals(name)){
                encap.setName(abs.inputName);
                System.out.println(""+encap.getName());
                abs.flag = 1;
            }
        }
        if(abs.flag!=1){
            System.out.println("Name doesn't exist..");
        }
        else{
            abs.abscompute();
        }
    }
}

class Encap{

I find all your class names confusing.  You seem to be describing the code, not what it does.  Maybe something like

class Greeter {

would be more understandable.

    private String name;
    public void setName(String newValue){
        name = "Hello, "+newValue+"!";
    }

The name variable isn't a name, but a greeting.  Why not call it that?

Also, newValue isn't very descriptive.  That actually is a name, so

    private String greeting;

    public void setGreeting(String name) {
        greeting = "Hello, " + name + "!";
    }

Now I can easily see that setGreeting takes a name as an input.

Some people might argue that setGreeting should only set the greeting, not determine what it is.  You could either create a constructor to handle this with an immutable variable, or you could change the name to changeGreeting.  Or you can ignore that convention, but you may get negative feedback.

abstract class Abstraction {

This could be

abstract class Sequence {

    private int[] sequence;

    Sequence(int length) {
        sequence = new int[length];
    }

    int getLength() {
        return sequence.length;
    }

    abstract void generate();
}

This seems a clearer set of names.

You also may want to look into how to use constructors

    int fibCount, flag=0, y;

It's generally preferable to have one variable per declaration, particularly if you are initializing as well.

    int fibCount;
    int flag = 0;
    int y;

Now you can easily see that only flag is initialized.

Why declare y?  You never use it.

Why make fibCount and flag object fields?  You only use them in one method.  They could be local variables instead.

    String names[] = new String [] {"Anna","Joe","Carl"};

This doesn't seem to have anything to do with the rest of this.  Why declare that variable in this class?

    Scanner x = new Scanner(System.in);

Why name your Scanner x?  Is it a secret that it is a scanner?  More common names would be scan or scanner.  You could also name it something like input or stdin.

I'd move the input and output out of the class and into main.  Then you can make scanner a local variable as well.

class abs2 extends Abstraction{

Again, this would be clearer as

class FibonacciSequence extends Sequence {

Now I know what I expect to find here.

        for (String name : abs.names) {
            if(abs.inputName.equals(name)){
                encap.setName(abs.inputName);
                System.out.println(""+encap.getName());
                abs.flag = 1;
            }
        }
        if(abs.flag!=1){
            System.out.println("Name doesn't exist..");
        }
        else{
            abs.abscompute();
        }

This would be easier to read as a method call:

        if (validName(inputName)) {
            greeting.setGreeting(inputName);
            sequence.generate();
        }
        else {
            System.out.println("Name doesn't exist..");
        }

Then instead of

                abs.flag = 1;
            }
        }

You could say

                return true;
            }
        }

        return false;

There are other places with similar feedback, but perhaps you should take a try at it yourself.


Displaying records from a MySQL database I've started learning .NET with MVC 4 in C# and I built a basic application to display records from a MySQL database. It's incredibly basic, but it's the best I could come up with being a complete beginner to C# and all.

Most of the programming I do is with Ruby on Rails and I tried to carry over some of the design patterns that I use there. I don't know the .NET conventions so if you see anything that should be changed please let me know.

Also, I don't fully understand how to find records with LINQ and pass them to the view. I ended up getting lucky and finding an article that somewhat explained it, but I don't have a firm grasp on the subject.

The naming conventions for my entities and models are wrong. It's a long story, basically it took me a while to connect to my MySQL database and when I generated them I didn't care how they were named.

RouteConfig.cs

routes.MapRoute(
    name: "root",
    url: "",
    defaults: new { controller = "Authors", action = "Index" }
);

routes.MapRoute(
    name: "author_books",
    url: "authors/{author_id}/books",
    defaults: new { controller = "Authors", action = "Books" }
);

AuthorsController.cs

public class AuthorsController : Controller {

    bookisticsEntities be = new bookisticsEntities();
    //
    // GET: /Authors/

    public ActionResult Index() {
       return View(be.authors.ToList());
    }

    public ActionResult Books(int author_id = 0) {
        author aut = be.authors.Find(author_id);

        var books = from b in be.books
                    join a in be.authors
                    on b.author_id equals a.id
                    where b.author_id == author_id
                    select b;

        ViewBag.author_name = aut.name;
        return View(books.ToList());
    }
}

I've omitted the view files because I pretty much left them at default after they were generated.

Dependency injection

Use dependency injection everywhere you can

public class AuthorsController : Controller
{
    private readonly bookisticsEntities _booksEntities;

    public AuthorsController(bookisticsEntities entities)
    {
        _booksEntities = entities;
    }

    public ActionResult Index()
    {
        //all authors on one page can be slow, paging?
        //.ToList() is useless here
       return View(be.authors);
    }

    //default value is not neccessary becouse 0 is an invalid value
    public ActionResult Books(int author_id)
    {
        var author = _booksEntities.authors.SingleOrDefault(a => a.id == author_id);

        if (author == null)
        {
            return HttpNotFound();
        }

        /*var books = from b in be.books
                    join a in be.authors
                    on b.author_id equals a.id
                    where b.author_id == author_id
                    select b;

        ViewBag.author_name = aut.name;*/

        //pass the author to the view and in the view you can iterate on the author.Books collection
        //if the foreign keys are correct in the database
        //or you setted everything correctly in code first approach
        return View(author);
    }
}

Now the controller expects a bookisticsEntities instance as constructor parameter but the default controller factory in the MVC framework only can use a parameterless constructor so you need a solution for this; use a dependency injection container like Ninject! It's easy to use available through Nuget.

N-tier

It seams to me your application missing one or two (maybe three) application level becouse currently you managing the database directly which is not a best practise. You have to build at leas one level between the MVC and the dataaccess tier which is called business layer (or two: a service layer and under that a business layer). In this way you controller will expect one or more different type of object instances but not your database model!

If you are done whith this you can use simplified models in your application, for example in the Books action method you can use a model which can contain the author's name, identifier and the books also (books can be simplified also).

Learn Entity Framework

Read a lot about how EF works. :)


Parsing Placeholders as SQL Arguments in PHP I am trying to find a good way of parsing SQL arguments, the way I am accomplishing it now seems like it can use a lot of improvement. I am trying to convert arguments that are split apart by ', & <= =>' from a string into SQL arguments like name = 'ABC' OR name ='John Doe'.

So

parseSQLOperators('dan,john&steven', 'username');

Will create

WHERE username= 'dan' OR username = 'john' AND username ='steven'

I have an example how this is being accomplished below but I am wondering if there is a better way for this. I know this code is ugly and I've been trying things like preg_splits but to no avail.

public static function parseSQLOperators($string, $content_term, $encapsulate = TRUE) {

        $string = trim($string);
        $length = strlen($string);

        $ADD_PREFIX = true;
        $output = '';
        for ($i = 0; $i < $length; $i++) {

            if ($string[$i] == '!') {

                $output .= ' ' . $content_term . '!=\'';

                if ($i == 0) {
                    $ADD_PREFIX = false;
                }
            } else if ($string[$i] == '+') {
                if (@$string[$i + 1] != '!') {
                    $output .= ' AND ' . $content_term . '=\'';
                } else {
                    $output .= ' AND ';
                }
            } else if ($string[$i] == ',') {
                if (@$string[$i + 1] != '!') {
                    $output .= ' OR ' . $content_term . '=\'';

                } else {
                    $output .= ' OR ';
                }

            }

            if ($string[$i] != '!' && $string[$i] != '+' && $string[$i] != ',') {

                $output .= $string[$i];

                if (@$string[$i + 1] == ',' || @$string[$i + 1] == '+' || @$string[$i + 1] == '!' || $i == $length || $i == $length - 1) {
                    $output .= '\'';
                }
            }
        }//end for

        if ($ADD_PREFIX == true) {
            $output = $content_term . '=\'' . $output;
        }

        if ($encapsulate) {
            $output = '(' . $output . ')';
        }

        return $output;
    }//end parseSQLOperator

If this is a whole SQL class of sorts, then I think you can improve your design a bit.  What if you want people who aren't archived and names match certain things? 'dan,john&steven', 'username' doesn't really work.  You need something more like:

$sql
    ->select(...)
    ->from(...)
    ->where('=dan|=john&=steven', 'username')
    ->andWhere('>0', 'archived')
    ->execute();

Notice that I didn't use your grammar.  I'd recommend the following shorthand grammar notation:

//& means AND
//| means OR
//~ means LIKE

//operator means &, |
//comparator means things like !=, =, <>, <, >, <=, >=, ~
//identifier means things like dan, john, or jo%

//The pseudo regular expession:
//{comparator} {identifier} ({operator} {comparator} {identifier})*

Doing that, you can turn: '=john | !=jamison & =james | ~%jo_n' into name = 'john' OR name != 'jamison' AND name = 'james' OR name LIKE '%jo_n' quite easily:

    function parse($string, $name) {
            //add in quote marks
            $string = preg_replace('/[A-Za-z0-9%_-]+/', "'$0'", $string);

            //add in name:
            $string = preg_replace('/\=|\!\=|<>|<|<=|>|>=|~/', "$name $0 ", $string);

            //replace ~ with LIKE
            $string = str_replace('~', 'LIKE', $string);

            //expand '&' and ',' to ' AND '
            $string = preg_replace('/\&|\,/', ' AND ', $string);

            //expand '|' to ' OR '
            $string = str_replace('|', ' OR ', $string);

            return $string;

    }

Also note that you should be able to escape things properly.  We don't want SQL injection going on 'round here!  I'd recommend a syntax like:

where('=? | =? & =?', array('dan', 'john', 'steven'), 'username')

The function I provided could easily be modified to do that.  You simply use the mysqli or PDO engine to do the replacing.  You  just have to store the arguments in your structure so you can do it proper.


Longest palindromes in a string Honestly, I'm doing a practice and get blocked. Problem link.

The problem is simple, given a string, calculate the number of max length palindromes (Any substring is valid, which means you can take any chars you want and reorder them as you want). Return the result modulo 1000000007.

For example, given amim, the answer is 2 (mim and mam).

Full Code

#!/bin/python3

import math
import os
import random
import re
import sys
from itertools import permutations
from functools import lru_cache

# Complete the initialize function below.
def initialize(s):
    # This function is called once before all queries.
    s = [ord(i) - 97 for i in s]
    results = [[0] * 26]
    for i, v in enumerate(s):
        result = results[i].copy()
        result[v] += 1
        results.append(result)
    return results

def count(s):
    result = [0] * 26
    for i in s:
        result[i] += 1
    return result

factorial = lru_cache(None)(math.factorial)

p = 1000000007

pow = lru_cache(None)(pow)

# Complete the answerQuery function below.
def answerQuery(l, r):
    # Return the answer for this query modulo 1000000007.
    counted1 = counted_list[l - 1]
    counted2 = counted_list[r]
    counted = [counted2[i] - counted1[i] for i in range(26)]
    left = 0
    total = 0
    divide = []
    for temp in counted:
        left += temp & 1
        total += temp >> 1
        divide.append(temp >> 1)
    total = factorial(total)
    total = total % p
    for i in divide:
        temp = factorial(i)
        temp = pow(temp, p - 2, p)
        total = total * temp
    result = total * (left or 1)
    return result % p

if __name__ == '__main__':
    s = input()

    counted_list = initialize(s)
    q = int(input())

    for q_itr in range(q):
        lr = input().split()

        l = int(lr[0])

        r = int(lr[1])

        result = answerQuery(l, r)

        print(result)

The code above can pass #0~#21 testcases and will fail in #22 due to timeout. (Just copy it to Problem link page given at the top)

As #22 testcase is very huge, I cannot post it here. So here is the link:

https://files.fm/u/mekwpf8u

If I can use numpy to rewrite this function, I think it will be better. But I cannot, I can only use the standard libs.

update

I use another customized factorial function but exceed memory usage limitation :/ But it really reduces the total time cost.

factorial_table = [1, 1]
def factorial(n):
    if n < len(factorial_table):
        return factorial_table[n]

    last = len(factorial_table) - 1
    total = factorial_table[last]
    for i in range(last + 1, n + 1):
        total *= i
        factorial_table.append(total)

    return total

Do % p early.

Since the test case is huge, I expect intermediate values you compute to be huge as well. Multiplication of large numbers is a very expensive operation. Try to keep your results in a native range. Consider e.g.

def modulo_factorial(n, mod):
    result = 1
    for i in range(1, n + 1):
        result = (result * i) % mod
    return result

Ditto for pow.
Do not recompute factorials from scratch. Instead of

for i in divide:
    temp = factorial(i)
    temp = pow(temp, p - 2, p)
    total = total * temp

sort divide first. Then computation of each factorial can be started where the previous one ended.

Also notice that since total is greater than any element of divide, you should compute factorial(total) after the this loop, using the same technique.

And don't forget to % p early.
Most of your imports are never used.


Encrypt string using One Time Pad I'm trying to make it so that a string generates n keys, and all of those are required to recover the original string. For this, I generate n-1 random strings, XOR them all together with the original string to get the nth one. XORing these n strings reproduces the original strings

How secure is this? Is there any better method?

Also, is the code itself good enough? What can I do to improve it in terms of security/speed/readability/best practices?

package crypto;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/**
 * Created by hooda on 2/3/2015.
 */
public class XOR {

    //Testing the functionality.
    public static void main(String[] args) throws Exception {
        XOR xor = new XOR();

        String text = "Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.";
        String[] pieces = xor.encrypt(text, 5);
        System.out.println(pieces[0]);
        System.out.println(pieces[1]);
        System.out.println(pieces[2]);
        System.out.println(pieces[3]);
        System.out.println(pieces[4]);
        String test = xor.decrypt(pieces);
        System.out.println(test);

    }

    public String[] encrypt(String s, int n) throws Exception {
        int length = s.length();
        String[] pieces = new String[n];

        for (int i = 0; i < n - 1; i++) {
            pieces[i] = keyGen(length);
        }

        String nth = s;
        for (int i = 0; i < n - 1; i++) {
            nth = doXOR(pieces[i], nth);
        }

        pieces[n - 1] = nth;
        return pieces;
    }

    public String decrypt(String[] pieces) {

        String decrypted = new String(new char[pieces[0].length()]).replace("\0", Character.toString((char) 0));
        for (String piece : pieces) {
            decrypted = doXOR(piece, decrypted);
        }
        return decrypted;
    }

    public String toBinary(String s) throws Exception {
        byte[] bytes = s.getBytes("ASCII");
        StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
        }
        return binary.toString();
    }

    public String keyGen(int length) throws UnsupportedEncodingException {
        SecureRandom srand = new SecureRandom();
        byte[] bytes = new byte[length];
        srand.nextBytes(bytes);
        return new String(bytes, "ASCII");
    }

    public String doXOR(String s1, String s2) throws IllegalArgumentException {

        String ret;
        if (s1.length() != s2.length()) {
            throw new IllegalArgumentException("The bit strings must have equal length!");
        } else {
            ret = "";
            for (int i = 0; i < s1.length(); i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                int i1 = (int) c1;
                int i2 = (int) c2;
                int i3 = i1 ^ i2;
                char c3 = (char) i3;
                ret += c3;
            }
        }
        return ret;
    }
}

Security. xor is an associative operation.

    nth ^= pieces[0];
    nth ^= pieces[1];
    ...
    nth ^= pieces[n-2]

like your code does is as good as

    nth ^= (pieces[0] ^ pieces[1] ^ ... ^ pieces[n-2]

doXOR is way too verbose to my taste.
toBinary doesn't belong here (and is never called indeed, unless I am missing something).
Obviously all the keys you have generated collapse into a single one. The bad guy doesn't have to recover all the keys - he only needs their accumulated xor. There is no additional security.


Checking if an event is not null before firing it in C# I often see this for custom events:

void InvokeCustomEvent(EventArgs e)
{
    var handler = CustomEvent;
    if (handler != null) handler(this, e);
}

But is creating the handler variable required, best practice, or superfluous, when compared to:

void InvokeCustomEvent(EventArgs e)
{
    if (CustomEvent != null) CustomEvent(this, e);
}

?

But is creating the handler variable required, best practice, or superfluous, when compared to:

Yes, it is needed. Otherwise, CustomEvent could be set to null after you've checked for null, but before you've invoked it. This can happen if it gets set in another thread, or if one of the event handlers unregisters itself or another one.

I usually have this declared somewhere in my codebase:

public static class EventExtensions
{
    public static void Raise<T>(this EventHandler<T> handler, T args) {
        if (handler != null) handler(args);
    }
}

Now, with any event handler, you can just do:

handler.Raise(args);

You can call an extension method with a null this, so it will do the right thing even if handler is null. Furthermore, by copying handler into the local variable used by Raise, you automatically get the copy you need to make sure the handler won't disappear under you. Works like a charm.


Benchmarking our LAMP servers with this php script I've written a small script to benchmark our LAMP hosted servers that assess the performance based on three factors:

Disk I/O
Database I/O (mysql)
Database I/O (sqlite)

The logic is as follows:

get the type of test performed using a querystring value.
generate a big random string of 100KB.
If (disk-i/o)
write this line to a random file 500 times.
else if (mysql i/o)
insert this as record in a mysql table 500 times.
else if (sqlite i/o)
insert this as record in a sqlite table 500 times.
Write back to response all variables such as the big string ($payload), time taken to write ($wtime), etc..

The program is working fine, but the database i/o is taking way more time than the file i/o. In one test instance, file i/o took only 1.5 seconds, whilst db i/o took 43 seconds! Can you help me with streamlining this code?

<?php
//index.php
$mysqlserver = 'localhost';
$mysqlusername = 'test';
$mysqlpassword='test';
$mysqldatabase='test';

$iterations=500;
$payload=""; //generate a random string of 108KB and a random filename
$fname='';
$rtime=0; //in milliseconds
$wtime=0;
$gentime=0;
$type='';

$db = null;
$mysqli = null;

if (isset($_REQUEST['type'])) $type=$_REQUEST['type'];

//generate:
$start = microtime(true);
for($i=0;$i<108000;$i++) //generate a big string
{
    $n=rand(0,57)+65;
    $payload = $payload.chr($n);
}
$gentime=round((microtime(true) - $start)*1000);

//write test:
$start = microtime(true);
    if ($type=='sqlite') //sqlite test
    {
        $db = new SQLite3("benchmark.db");
        $db->exec('create table temp(t text)');
        $db->exec("begin");
        $stmt = $db->prepare("insert into temp values(:id)");
        for($i=0;$i<$iterations;$i++) {
            $stmt->bindValue(':id', $payload, SQLITE3_TEXT);
            $stmt->execute();
            //$db->exec("delete from temp");
            };
        $db->exec("commit");

    }
    else if ($type=='mysql') //mysql test
    {
        $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase);
        $mysqli->query('create table temp(t varchar(108000))');
        $mysqli->query('begin transaction');
        for($i=0;$i<$iterations;$i++)
            $mysqli->query("insert into temp values('{$payload}')");
        $mysqli->query('commit');
    }
    else // Disk I/O
    {
        $fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt';
        for($i=0;$i<$iterations;$i++) file_put_contents($fname,$payload);
    }
$wtime=round((microtime(true) - $start)*1000);

//read test:
$start = microtime(true);
$result = '';
if ($type=='sqlite'){
    for($i=0;$i<$iterations;$i++) {
        $result = $db->query("select t from temp limit 1");
        $result = $result->fetchArray()['t'];
        //$db->exec("delete from temp");
    };
        //var_dump($result);
}
else if ($type=='mysql'){
    $stmt = $mysqli->prepare('select t from temp limit 1');
    if ($stmt)
    {
        for($i=0;$i<$iterations;$i++) {
            $stmt->execute();
            $stmt->bind_result($result);
            $stmt->fetch();
        };
    }
}
else
{
    for($i=0;$i<$iterations;$i++) $result = file_get_contents($fname);
}
$rtime=round((microtime(true) - $start)*1000);

//cleanup:
if ($type=='sqlite')
{
        $db->exec("drop table temp");
        $db->close();
}
else if ($type=='mysql')
{
    $mysqli->query('drop table temp');
}
else
{
    unlink($fname);
}

//return:
$result =  array(
    'type'=>($type==''?'disk':$type),
    'iterations'=>$iterations,
    'generate_time'=>$gentime,
    'write_time'=>$wtime,
    'read_time'=>$rtime,
    'server_software'=>$_SERVER["SERVER_SOFTWARE"],
    'payload'=>$result,
);

echo json_encode($result);

I'm not to good at optimizing, so I don't think I'm qualified to touch on that aspect.
So, formatting I guess,
One thing I can say though, is that your code is seriously lacking consistency. Some assignments ($mysqlserver = 'localhost';) you place spaces around operators and use single quotes, on some ($payload="";) it's the exact opposite! I suggest you choose a style, or a beautifier for that matter, and apply it to the whole script. It makes reading it, a lot easier. Also, please fix your indentation. Knowing which functions and clauses your closing brackets end is pretty important.
Now the code,
Why $_REQUEST? Are you expecting to receive input from the URL, other pages, and cookies? If so, you may skip this. If not, I suggest you choose between $_GET or $_POST to keep things specific.
How about this:
$n=rand(0,57)+65;
$payload = $payload.chr($n);

It really could be reduced to:
$c = rand(65, 122);
$payload .= chr($c);

I felt a "c" would be better than an "n", but really, variables should have some sort of context in them. So "$charCode" would be excellent. Hold off on fixing this though!
Now I don't feel qualified to critique the actual I/O code, so I'll leave that up to someone with more knowledge. From what I do know though, I can't see any glaring problems with your database queries that would cause it to be so slow. Hopefully some one with an eye keener than mine can help.

Now this:
$fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt'

is very wet. What I mean by that is, we need to DRY it out a bit!
Head back up to the top, and let's make a nifty function:
function rand_char_str($length) {
    $returnString = "";
    for ($i = 0; $i < $length; $i++) {
        $returnString .= chr(rand(65, 122));
    }
    return $returnString;
}

Great! Now we can replace
for($i=0;$i<108000;$i++) //generate a big string
{
    $n=rand(0,57)+65;
    $payload = $payload.chr($n);
}

with
$payload = rand_char_str(108000);

We can also replace that $fname assignment with
$fname = rand_char_str(4) . ".txt";

Towards the end there, you have
$stmt = $mysqli->prepare('select t from temp limit 1');

and then a conditions checking the value of $stmt. You can just place the method call inside the conditional. This one's just nit-picking though!


Extracting the classpath entries from a jar file's manifest Sometimes I need to search for dependencies in the classpath entries in the manifest of jar files. A jar manifest with classpaths looks like this:

Manifest-Version: 1.0
Created-By: 1.6.0_29 (Sun Microsystems Inc.)
Class-Path: spring-aop-3.2.0.jar spring-aspects-3.2.0.jar spring-beans
 -3.2.0.jar spring-context-3.2.0.jar spring-context-support-3.2.0.jar
 spring-core-3.2.0.jar spring-expression-3.2.0.jar spring-instrument-3
 .2.0.jar spring-instrument-tomcat-3.2.0.jar spring-jdbc-3.2.0.jar spr
 ing-jms-3.2.0.jar spring-orm-3.2.0.jar spring-oxm-3.2.0.jar spring-st
 ruts-3.2.0.jar spring-test-3.2.0.jar spring-tx-3.2.0.jar spring-web-3
 .2.0.jar spring-webmvc-3.2.0.jar spring-webmvc-portlet-3.2.0.jar

Searching for jars in a manifest is troublesome:

Extract the META-INF/MANIFEST.MF file from the jar
Re-join the split lines to make searching humanely possible

Step 2 is necessary, because of the line breaks. For example, I won't find "struts" in the above, because the word is broken in the middle.

I use this shell script to make this process easier, I call it jar-manifest-classpath.sh:

#!/bin/bash

if test -d "$TMPDIR"; then
    :
elif test -d "$TMP"; then
    TMPDIR=$TMP
elif test -d /var/tmp; then
    TMPDIR=/var/tmp
else
    TMPDIR=/tmp
fi
workdir=$TMPDIR/$(basename "$0")-work-$$

cleanup() {
    rm -fr "$workdir"
}

mkdir -p "$workdir"
trap 'cleanup' 1 2 3 15

for jar; do
    if ! test -f $jar; then
        echo warning: not a file: $jar
        continue
    fi
    [[ $jar = /* ]] || jar=$PWD/$jar
    (
        cd "$workdir" || exit 1
        jar xf "$jar"
        sed -ne '/^Class-Path:/,$p' META-INF/MANIFEST.MF | sed -e 's/^Class-Path: //' -e 's/^ //' | tr -d '\n' | tr ' ' '\n'
    )
done

cleanup

For a jar file with the manifest as above, this will output:

spring-aop-3.2.0.jar
spring-aspects-3.2.0.jar
spring-beans-3.2.0.jar
spring-context-3.2.0.jar
spring-context-support-3.2.0.jar
spring-core-3.2.0.jar
spring-expression-3.2.0.jar
spring-instrument-3.2.0.jar
spring-instrument-tomcat-3.2.0.jar
spring-jdbc-3.2.0.jar
spring-jms-3.2.0.jar
spring-orm-3.2.0.jar
spring-oxm-3.2.0.jar
spring-struts-3.2.0.jar
spring-test-3.2.0.jar
spring-tx-3.2.0.jar
spring-web-3.2.0.jar
spring-webmvc-3.2.0.jar
spring-webmvc-portlet-3.2.0.jar

This is much more pleasent, and perfectly grep-able.

Let me know if you have any ideas to improve or simplify!
(The script is part of my collection on GitHub)

I would create the trap for cleanup before an action is done that needs cleanup, so change the sequence of commands. Also I would prefer signal names instead of numbers. If you add EXIT to the signal list then cleanup is called when the shell is exited, so you can remove the last line of your script (cleanup)

trap 'cleanup' EXIT SIGHUP SIGINT SIGQUIT SIGTERM
mkdir -p "$workdir"

If the script is called without argument or with-? a usage message should be displayed.

Warnings and error messages should be written to stderr(2) and not to stdout(1). This is Unix standard behaviour for a program. Otherwise you will not see the error message if you pipe the output through a grep command.


Calculating elapsed time The code below compares recv.rcpt_dtim (which is a datetime type) against the current date/time. It calculates an elapsed time resulting in hours and minutes formatted like: "04:22". It took me a while to get it functional, which it is, but it just seems sloppy. Does anyone have any tips to clean it up?

TRIM((((CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL SECOND(9) to
SECOND)/3600)::VARCHAR(12) || ':' || CASE WHEN (MOD(MOD(((CURRENT YEAR TO
MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9) to
MINUTE)::VARCHAR(12)::INT,60),60))<10 THEN "0" ELSE "" END ||
(MOD(MOD(((CURRENT YEAR TO MINUTE - recv.rcpt_dtim)::INTERVAL MINUTE(9)
to MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12))

When I use your complex expression, I don't get the leading zeros on the hour field that your code suggests that you want.  AFAICS, the expression that tries to add a leading zero is fiddling with the minutes field.  I'm not sure why you're doing the double MOD operations, either.

I think it is sufficient to use the vastly simpler CAST expression shown in the following SELECT statement.  Here, instead of using CURRENT YEAR TO SECOND (or minor variants thereupon), I've created a second table, reference_times, with a single column reftime of type DATETIME YEAR TO SECOND.  That allows me to test many different reference times reliably, in a way that using CURRENT simple does not.  I use an explicit CROSS JOIN between the reference times and the recv table to compare every row in each table with each of the rows in the other.

SELECT reft.reftime,
       recv.rcpt_dtim,
       (reft.reftime - recv.rcpt_dtim) AS delta_t_1,
       CAST(reft.reftime - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE) AS delta_t_2,
       TRIM((((reft.reftime - recv.rcpt_dtim)::INTERVAL SECOND(9) TO SECOND)/3600)::VARCHAR(12) ||
           ':' ||
           CASE WHEN (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))<10
           THEN "0"
           ELSE "" END ||
           (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12)) AS delta_t_3
  FROM reference_times AS reft JOIN recv ON 1 = 1
 ORDER BY reft.reftime, recv.rcpt_dtim;

Given the setup code:

CREATE TEMP TABLE reference_times
(
    reftime     DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY
);
INSERT INTO reference_times VALUES('2019-05-01 03:01:03');
INSERT INTO reference_times VALUES('2019-05-01 05:32:27');
INSERT INTO reference_times VALUES('2019-05-01 10:22:44');
INSERT INTO reference_times VALUES('2019-05-01 12:49:00');
INSERT INTO reference_times VALUES('2019-05-01 14:59:59');
INSERT INTO reference_times VALUES('2019-05-01 23:59:58');

CREATE TEMP TABLE recv
(
    rcpt_dtim   DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY
);
INSERT INTO recv VALUES('2019-05-01 01:10:11');
INSERT INTO recv VALUES('2019-05-01 02:00:00');
INSERT INTO recv VALUES('2019-04-30 22:19:45');
INSERT INTO recv VALUES('2019-04-30 18:37:21');
INSERT INTO recv VALUES('2019-04-30 03:31:00');
INSERT INTO recv VALUES('2019-04-30 01:19:45');
INSERT INTO recv VALUES('2019-04-30 00:00:00');
INSERT INTO recv VALUES('2019-04-29 20:10:58');
INSERT INTO recv VALUES('2019-04-10 22:09:00');
INSERT INTO recv VALUES('2019-04-01 22:09:00');

I get output such as:

reftime              rcpt_dtim               delta_t_1 delta_t_2  delta_t_3
2019-05-01 03:01:03  2019-04-01 22:09:00   29 04:52:03    700:52  700:52
2019-05-01 03:01:03  2019-04-10 22:09:00   20 04:52:03    484:52  484:52
2019-05-01 03:01:03  2019-04-29 20:10:58    1 06:50:05     30:50  30:50
2019-05-01 03:01:03  2019-04-30 00:00:00    1 03:01:03     27:01  27:01
2019-05-01 03:01:03  2019-04-30 01:19:45    1 01:41:18     25:41  25:41
2019-05-01 03:01:03  2019-04-30 03:31:00    0 23:30:03     23:30  23:30
2019-05-01 03:01:03  2019-04-30 18:37:21    0 08:23:42      8:23  8:23
2019-05-01 03:01:03  2019-04-30 22:19:45    0 04:41:18      4:41  4:41
2019-05-01 03:01:03  2019-05-01 01:10:11    0 01:50:52      1:50  1:50
2019-05-01 03:01:03  2019-05-01 02:00:00    0 01:01:03      1:01  1:01
2019-05-01 05:32:27  2019-04-01 22:09:00   29 07:23:27    703:23  703:23
2019-05-01 05:32:27  2019-04-10 22:09:00   20 07:23:27    487:23  487:23
2019-05-01 05:32:27  2019-04-29 20:10:58    1 09:21:29     33:21  33:21
2019-05-01 05:32:27  2019-04-30 00:00:00    1 05:32:27     29:32  29:32
2019-05-01 05:32:27  2019-04-30 01:19:45    1 04:12:42     28:12  28:12
2019-05-01 05:32:27  2019-04-30 03:31:00    1 02:01:27     26:01  26:01
2019-05-01 05:32:27  2019-04-30 18:37:21    0 10:55:06     10:55  10:55
2019-05-01 05:32:27  2019-04-30 22:19:45    0 07:12:42      7:12  7:12
2019-05-01 05:32:27  2019-05-01 01:10:11    0 04:22:16      4:22  4:22
2019-05-01 05:32:27  2019-05-01 02:00:00    0 03:32:27      3:32  3:32
2019-05-01 10:22:44  2019-04-01 22:09:00   29 12:13:44    708:13  708:13
2019-05-01 10:22:44  2019-04-10 22:09:00   20 12:13:44    492:13  492:13
2019-05-01 10:22:44  2019-04-29 20:10:58    1 14:11:46     38:11  38:11
2019-05-01 10:22:44  2019-04-30 00:00:00    1 10:22:44     34:22  34:22
2019-05-01 10:22:44  2019-04-30 01:19:45    1 09:02:59     33:02  33:02
2019-05-01 10:22:44  2019-04-30 03:31:00    1 06:51:44     30:51  30:51
2019-05-01 10:22:44  2019-04-30 18:37:21    0 15:45:23     15:45  15:45
2019-05-01 10:22:44  2019-04-30 22:19:45    0 12:02:59     12:02  12:02
2019-05-01 10:22:44  2019-05-01 01:10:11    0 09:12:33      9:12  9:12
2019-05-01 10:22:44  2019-05-01 02:00:00    0 08:22:44      8:22  8:22
2019-05-01 12:49:00  2019-04-01 22:09:00   29 14:40:00    710:40  710:40
2019-05-01 12:49:00  2019-04-10 22:09:00   20 14:40:00    494:40  494:40
2019-05-01 12:49:00  2019-04-29 20:10:58    1 16:38:02     40:38  40:38
2019-05-01 12:49:00  2019-04-30 00:00:00    1 12:49:00     36:49  36:49
2019-05-01 12:49:00  2019-04-30 01:19:45    1 11:29:15     35:29  35:29
2019-05-01 12:49:00  2019-04-30 03:31:00    1 09:18:00     33:18  33:18
2019-05-01 12:49:00  2019-04-30 18:37:21    0 18:11:39     18:11  18:11
2019-05-01 12:49:00  2019-04-30 22:19:45    0 14:29:15     14:29  14:29
2019-05-01 12:49:00  2019-05-01 01:10:11    0 11:38:49     11:38  11:38
2019-05-01 12:49:00  2019-05-01 02:00:00    0 10:49:00     10:49  10:49
2019-05-01 14:59:59  2019-04-01 22:09:00   29 16:50:59    712:50  712:50
2019-05-01 14:59:59  2019-04-10 22:09:00   20 16:50:59    496:50  496:50
2019-05-01 14:59:59  2019-04-29 20:10:58    1 18:49:01     42:49  42:49
2019-05-01 14:59:59  2019-04-30 00:00:00    1 14:59:59     38:59  38:59
2019-05-01 14:59:59  2019-04-30 01:19:45    1 13:40:14     37:40  37:40
2019-05-01 14:59:59  2019-04-30 03:31:00    1 11:28:59     35:28  35:28
2019-05-01 14:59:59  2019-04-30 18:37:21    0 20:22:38     20:22  20:22
2019-05-01 14:59:59  2019-04-30 22:19:45    0 16:40:14     16:40  16:40
2019-05-01 14:59:59  2019-05-01 01:10:11    0 13:49:48     13:49  13:49
2019-05-01 14:59:59  2019-05-01 02:00:00    0 12:59:59     12:59  12:59
2019-05-01 23:59:58  2019-04-01 22:09:00   30 01:50:58    721:50  721:50
2019-05-01 23:59:58  2019-04-10 22:09:00   21 01:50:58    505:50  505:50
2019-05-01 23:59:58  2019-04-29 20:10:58    2 03:49:00     51:49  51:49
2019-05-01 23:59:58  2019-04-30 00:00:00    1 23:59:58     47:59  47:59
2019-05-01 23:59:58  2019-04-30 01:19:45    1 22:40:13     46:40  46:40
2019-05-01 23:59:58  2019-04-30 03:31:00    1 20:28:58     44:28  44:28
2019-05-01 23:59:58  2019-04-30 18:37:21    1 05:22:37     29:22  29:22
2019-05-01 23:59:58  2019-04-30 22:19:45    1 01:40:13     25:40  25:40
2019-05-01 23:59:58  2019-05-01 01:10:11    0 22:49:47     22:49  22:49
2019-05-01 23:59:58  2019-05-01 02:00:00    0 21:59:58     21:59  21:59

Column names/types:

reftime      DATETIME YEAR TO SECOND
rcpt_dtim    DATETIME YEAR TO SECOND
delta_t_1    INTERVAL DAY(8) TO SECOND
delta_t_2    INTERVAL HOUR(4) TO MINUTE
delta_t_3    VARCHAR(26)

Observe that the delta_t_2 column produces the same output as the delta_t_3 column — apart from type (interval vs string); the left vs right adjustment is mostly an artefact of the way the program that generated the data futzes with the formatting.

Consequently, your elaborate expression can be simplified to:

CAST(CURRENT YEAR TO SECOND - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE)

or:

(CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL HOUR(4) TO MINUTE

And if your time gaps are small enough, you can change the 4 to 2.


Two circles intersect Do two circles in a 2D plane disjoint?

$$(r_1 + r_2) \cdot (r_1 + r_2) \gt \Delta{X} \cdot \Delta{X} + \Delta{Y} \cdot \Delta{Y}$$

Any comments / corrections on this code?

internal struct HoleInfo
{
    public float Diameter { get; internal set; }
    public float X { get; internal set; }
    public float Y { get; internal set; }
    public HoleInfo(float x, float y, float diameter)
    {
        X = x;
        Y = y;
        Diameter = diameter;
    }
}
static bool HoleOverlap(HoleInfo hole1, HoleInfo hole2)
{
    float holeSize = (hole1.Diameter + hole2.Diameter) / 2;
    float deltaX = hole1.X - hole2.X;
    float deltaY = hole1.Y - hole2.Y;
    return (holeSize * holeSize > deltaX * deltaX + deltaY * deltaY);
}

It is called HoleInfo because the app is concerned if holes drilled in a board will overlap.

You're breaking some rules for good struct design - see them here.

X DO NOT define mutable value types.
✓ DO implement IEquatable on value types.

I'm going to disagree with everyone else and say that calling your struct a Hole is fine as it's a domain specific concept.
I think your method naturally belongs on the type itself. I'd call it Intersects to avoid the disjoint/overlap debate.
// using static System.Math; // Easy access to Pow.

public struct Hole : IEquatable<Hole>
{
    public float Radius => Diameter / 2;
    public float Diameter { get; }
    public float X { get; }
    public float Y { get; }

    public Hole(float x, float y, float diameter)
    {
        X = x;
        Y = y;
        Diameter = diameter;
    }

    public bool Intersects(Hole other)
    {
        var sumR = Radius + other.Radius;
        var deltaX = X - other.X;
        var deltaY = Y - other.Y;
        return Pow(sumR, 2) > Pow(deltaX, 2) + Pow(deltaY, 2);
    }

    public bool Equals(Hole other)
    {
        return Diameter.Equals(other.Diameter) && X.Equals(other.X) && Y.Equals(other.Y);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        return obj is Hole && Equals((Hole)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = Diameter.GetHashCode();
            hashCode = (hashCode * 397) ^ X.GetHashCode();
            hashCode = (hashCode * 397) ^ Y.GetHashCode();
            return hashCode;
        }
    }

    public static bool operator ==(Hole left, Hole right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(Hole left, Hole right)
    {
        return !left.Equals(right);
    }
}