Concat strings from Object or Array How would you merge these two functions into a single more generic function?

// concatStringsFromObject :: Object, Array, String -> Strings
const concatStringsFromObject = (o = {}, a = [], j = ' ') => {
    return a.filter( x => o.hasOwnProperty(x) )
            .map( x => o[x] )
            .join(j);
};

// concatStringsFromArrayOfObject :: Array, String, String -> Strings
const concatStringsFromArrayOfObject = (a = [], s = '', j = ', ') => {
    return a.filter( x => x.hasOwnProperty(s) )
            .map( x => x[s] )
            .join(j);
};

The best functions have functional cohesion,
meaning they do one thing, and do it well.
I don't see a reason to merge these functions, and I don't see how that would be an improvement.

The first function takes Object, Array, String arguments,
the second one takes Array, String, String.
If you need something that works with both Object and Array,
then you can make it check the underlying type of its parameter,
and delegate to the appropriate method.
So it will be a 3rd function, using the other two under the hood.

  I need to be easy to test.

There's nothing special here to make testing hard.
You can either test the two main worker methods directly,
or test everything through the 3rd method.


Rotating background using Swing: performance issues In a jPanel, I'm displaying a 1203x1203 background that I rotate every 30ms. Problem is, Swing is known to be a slow library, and I assume rotating a huge picture at a quick rate would be quite resources demanding. But I've a powerful PC, and even if on mine it runs fine, I wonder if on slower machines it will be as fluid.

public static BufferedImage createRotatedCopy(BufferedImage img, double rotation) {
    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage rot = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    double theta = 2 * Math.PI * rotation;
    AffineTransform xform = new AffineTransform();

    xform.translate(0.5 * h, 0.5 * w);
    xform.rotate(theta);
    xform.translate(-0.5 * w, -0.5 * h);
    Graphics2D g = (Graphics2D) rot.createGraphics();
    g.drawImage(img, xform, null);
    g.dispose();
    return rot;
}

I wonder first if there is any way to optimize it. What I can do, is to use a smaller picture, apply the rotation and resize it. But I don't know if it would be more efficient.

And the rotation callback is:

    exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            bgAngle += 0.001;
            bgAngle = (bgAngle >= 1) ? 0 : bgAngle;
            rotBg = Menu.createRotatedCopy(toBufferedImage(bg.getImage()),
                    bgAngle);
            repaint();
        }
    }, 0, 30, TimeUnit.MILLISECONDS);

Do you see anything that could be optimized? Or outright another way to do what I want?

Here is something you could do which would work for computers not fast enough to rotate the image every 30 ms.  Instead of requesting a repaint every 30ms, define the angularVelocity (rads / second) and call a repaint every 30 ms or as fast as possible, if it can't make 30 ms.  Then compute angleRad = angularVelocity * (System.currentTimeMillis() - startTime).

Swing efficiency is not the problem. The image manipulation library is the bottleneck. I don't think you can do anything to make it faster. There are probably some (non-Java) libraries that can rotate images much faster using the GPU, but mixing those with Java would make the installation a nightmare.

Another solution would be to store all rotated images in memory.  That might work if you were rotating the image by 90 degrees increments, but you would need an awful lot of RAM for all images incremented by 0.001 rads.

As an aside, I believe repaint() now has to be called on the Swing event thread, which was not the case before Java 7.  I'm not quite sure and I could not find about this on the web, so I would be grateful if someone could comment.  You could use a SwingWorker if that is the case. Actually, for cleanness, you should probably stick to a SwingWorker.  It does exactly want you are doing, and is made especially for that.


Cleaner Code for custom query Is there a cleaner way to do the following?

friend_ids = [1,2,3,4,5]
friendIDsQuery = ""
friend_ids.each_with_index do |friend_id, index|
  friendIDsQuery += "SELECT id FROM test WHERE user_id = #{friend_id}"

  if index != friend_ids.size - 1
    friendIDsQuery += " INTERSECT "
  end
end

Basically I'm passing in an array of IDs, and building a custom INTERSECT query.

query = friend_ids.map {|id| "SELECT id FROM test WHERE user_id=#{id}"}.join " INTERSECT "

Bam.

Edit: Ok, well, not just bam. First of all, if you're using Rails, go with something like NewAlexandria's answer, because it doesn't involve raw string interpolation (which quickly leads to SQL injection vulnerabilities). To make the above a little more safe (and assuming the IDs are integers), you should probably do

query = friend_ids.map { |id|
  "SELECT id FROM test WHERE user_id = #{id.to_i}"
}.join " INTERSECT "


Inserting nodes into a singly linked list based on size of number Given a set of numbers insert them so that they are ordered ie.

add(5)
add(3)
add(6)
add(2)

Output: 6 5 3 2

GetNumber() returns the number of that term
insertAfter() inserts that node after the pointer
insertAtHead() inserts as the head node
Term is the Node which holds the number

How can I refactor this working code?

        boolean inserted = false;
        Node pointer = head;
    if (pointer == null || term.getNumber() > pointer.data.getNumber()) {
        // If head is empty insert there or if term is larger than head.
        insertAtHead(term);
    } else if(pointer.next == null) {
        insertAfter(term, head);
    } else {
        while (pointer.next != null) {
            //Insert at end.
            if (term.getNumber() > pointer.next.data.getNumber()) {
                insertAfter(term, pointer);
                inserted = true;
                break;
            }
            pointer = pointer.next;
        }
        if (!inserted) {
            //If not inserted it must be the smallest so add to the end.
            insertAfter(term, pointer);
        }
    }
    printList();

You don't need the else if(pointer.next == null) case, it's covered by if (!inserted).
Declare variables in as small a scope as possible to increase readability. inserted and pointer aren't needed until the while loop.
You can save a nesting level if you put your code into a insertSorted method, and then call printList afterwards in the calling method. That way, you can write the initial head insert as a guard clause and thus save the else.
You could also save the break by adding && !inserted to the while clause.
many of your comments just repeat the code they comment on, and are thus not really needed.
// Insert at end. is quite misleading, as the insert doesn't happen at the end of the list.

With all these changes, your code already looks a bit cleaner:

if (head == null || term.getNumber() > head.data.getNumber()) {
    insertAtHead(term);
    return;
}

Node pointer = head;
boolean inserted = false;
while (pointer.next != null && !inserted) {
    if (term.getNumber() > pointer.next.data.getNumber()) {
        insertAfter(term, pointer);
        inserted = true;
    }
    pointer = pointer.next;
}

if (!inserted) {
    //If not inserted it must be the smallest so add to the end.
    insertAfter(term, pointer);
}

You could also return early after inserting, and thus get rid of the inserted variable:

// guard clause for head insert

Node pointer = head;
while (pointer.next != null) {
    if (term.getNumber() > pointer.next.data.getNumber()) {
        insertAfter(term, pointer);
        return;
    }
    pointer = pointer.next;
}

//If not inserted it must be the smallest so add to the end.
insertAfter(term, pointer);

But you still have a separate case for the last insert which is a bit ugly. You should be able to get rid of it with something like this:

// guard clause for head insert

Node pointer = head;
while (pointer.next != null && term.getNumber() < pointer.next.data.getNumber()) {
    pointer = pointer.next;
}
insertAfter(term, pointer);


Perl file sorting script This is my first ever real 100% self made perl script, I'd like to know how I can improve it.

#!/usr/bin/env perl
#this script takes a directory and sorts the files into folders by file ending

use strict;
use warnings;
use File::Copy;

sub sort_files {
    my $dir = shift || '.';     #cwd if no directory given
    $dir =~ s/\/$//;            #remove trailing /

    opendir(DIR, $dir) or die $!;
    my @files = grep {
        !/^\./      #does not start with .
        && -f "$dir/$_" #is file
        } readdir DIR;

    my $len = @files;
    print "sorting $len files\n";
    foreach my $file (@files){
        my ($ext) = $file =~ /([^.]*$)/;#grabs file extension

        my $dest = "$dir/$ext/";
        if (not -d "dest"){     #create folder if it does not exist
            mkdir $dest;
            print "\tcreated directory $dest\n";
        }
        move "$dir/$file", $dest or die "$!";
        print "\t$file moved to $dest\n"
    }
}

sort_files @ARGV;
exit 0;

ninja edit: I just noticed that this script runs into problems if there is no file ending specified. Elegant solutions apreciated! (checking the file for !/\./ would work, but that's not elegant in my book)

I've added a few comments in your source,

#!/usr/bin/env perl

use strict;
use warnings;
use autodie; # automatic die/checks for http://search.cpan.org/~pjf/autodie/lib/autodie.pm#CATEGORIES
use File::Copy;

sub sort_files {
    # my $dir = shift || '.';
    my $dir = shift // '.'; # defined short circuit to allow '0' as argument
    $dir =~ s/\/$//;

    # opendir(DIR, $dir) or die $!;
    opendir(my $DIR, $dir);  # use lexical variable instead of glob
    my @files = grep {
        !/^\./      # not needed if you only want to skip '.' and '..'
        && -f "$dir/$_"
        } readdir $DIR;

    my $len = @files;
    print "sorting $len files\n";

    foreach my $file (@files){
        my ($ext) = $file =~ /([^.]*$)/;

           #
           # what do you want to do when $ext is undefined?
           # my ($ext) = $file =~ /([^.]*$)/ or next; # to skip such files

        my $dest = "$dir/$ext/";
        # if (not -d "dest"){  # typo?
        if (not -d $dest){
            mkdir $dest;       # added autodie to check on mkdir
            print "\tcreated directory $dest\n";
        }
        move("$dir/$file", $dest) or die $!;   # autodie doesn't handle File::Copy
        print "\t$file moved to $dest\n"
    }
}

sort_files(@ARGV); # parentheses around arguments for non core functions are good idea https://eval.in/139428 vs https://eval.in/139430
# exit 0; # not needed


Call method if child implements interface vs override I have a hierarchy like next:

 AbstractRequestWs
   |- CreatorRequestWs
   |- CheckRequestWs
   |- GetRequestWs
   |- DeleteRequestWs

In this implementation I process ws calls with common code. So I've created an Abstract class which contains some common logic and structure.

So I've created a class like next:

public abstract class AbstractRequestWs {

    protected Entity itemMapped;
    protected final EntityToMap entityToMap;

    public AbstractRequestWs(EntityToMap entityToMap) {
        this.entityToMap = entityToMap;
    }

    public Entity map() {
        doSometing();
        //Do this?? or instead override this method on childs
        if (this instanceof StatusUpdatable) {
            ((StatusUpdatable) this).calcualteStatus();
        }
        return mapToEntity();
    }

    protected abstract void doSometing();

    private Entity mapToEntity() {
       //common impl
    }

}

Then some childs need to update a status (which has a large calculation) and some others not, and I've got the idea to create an Interface StatusUpdatable whith a calcualteStatus method so if a child implements this interface the calculateStatus will be called in the Abstract parent class.

For example creator implements StatusUpdatable, so the method calculateStatus will be called.

 public CreatorRequestWs implements StatusUpdatable {
   //....
     public void calculateStatus() {
        //
     }
 }

Otherwise GetRequestWs doesn't implements StatusUpdatable, so the method calculateStatus won't be called.

public GetRequestWs {
   //....
}

So is this a good idea? Check if a child implements some interface and call a method of this interface, or otherwise override the public method and do it directly?

Otherwise I would have to override the map() method in the classes which is need to calculate status:

public CreatorRequestWs  {

   //....

   @Override
   public Entity map() {
       doSometing();
       calcualteStatus();
       return mapToEntity();
   }

   public void calculateStatus() {
      //...
   }
}

I see is more difficult to read than override the map because how the method calculateStatus is call is hide by the parent classes, but otherwise I don't repeat code.

What do you think?

I think the classes that have a calculateStatus method should have it called in the end of their doSomeThing()

Or, if you wish to reuse more code, create a  AbstractRequestStatusUpdatableWs, like this:

abstract class AbstractRequestStatusUpdatableWs implements StatusUpdatable
{
     abstract void calculateStatus();
     abstract void doSomeRealWork();

     public final void doSomeThing()
     {
           doSomeRealWork();
           calculateStatus();
     }
}


Monitoring the clipboard The following class monitors the clipboard and raises an event whenever the contents change. The monitoring starts when the class is created and ends when Dispose is called.

To achieve this a message-only window (a term that comes from the Win32 API) is created using an instance of HwndSource class (since I am using WPF). The window's handle is then registered via AddClipboardFormatListener to receive a message whenever the clipboard changes. The window's messages are processed by WndProc which raises the event when the WM_CLIPBOARDUPDATE message comes.

In other solutions for monitoring the clipboard I saw this was done on the actual main window of the application, but I wanted to separate the logic of monitoring the clipboard form the View and keep a clean MVVM. In an application I would instantiate the ClipboardMonitor in the ViewModel.

I am interested if there may be any hidden pitfalls where this approach may go wrong.

public sealed class ClipboardMonitor : IDisposable
{
    private static class NativeMethods
    {
        /// <summary>
        /// Places the given window in the system-maintained clipboard format listener list.
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);

        /// <summary>
        /// Removes the given window from the system-maintained clipboard format listener list.
        /// </summary>
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

        /// <summary>
        /// Sent when the contents of the clipboard have changed.
        /// </summary>
        public const int WM_CLIPBOARDUPDATE = 0x031D;

        /// <summary>
        /// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function.
        /// </summary>
        public static IntPtr HWND_MESSAGE = new IntPtr(-3);
    }

    private HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE);

    public ClipboardMonitor()
    {
        hwndSource.AddHook(WndProc);
        NativeMethods.AddClipboardFormatListener(hwndSource.Handle);
    }

    public void Dispose()
    {
        NativeMethods.RemoveClipboardFormatListener(hwndSource.Handle);
        hwndSource.RemoveHook(WndProc);
        hwndSource.Dispose();
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == NativeMethods.WM_CLIPBOARDUPDATE)
        {
            OnClipboardContentChanged?.Invoke(this, EventArgs.Empty);
        }

        return IntPtr.Zero;
    }

    /// <summary>
    /// Occurs when the clipboard content changes.
    /// </summary>
    public event EventHandler OnClipboardContentChanged;
}

Your code looks fine except for two points:

a Dispose() method should never throw an exception but yours will likely throw one if it is called twice. This can be avoided by having a private bool disposed variable which is checked by an if condition.
an event based method OnXXX is usually either private or protected and used to actually raise the event. A simple rename to ClipboardChanged will be sufficient to handle that issue.


Implement data structure overflow queue Implement data structure overflow queue. Overflow queue is a normal queue with one extra property. It never throw Stack overflow exception. So whenever queue becomes full, it replaces the oldest element present in the queue and front pointer simply shifted one step ahead. Constraint:- it should have public void enQueue(int n) and public int deQueue() methods of time complexity O(1) The implementation should be optimum and clean.

Here is my version of implementation. You review is highly appreciated.

public class OverflowQueue {
    private int[] queue;
    private int front = -1, rear = -1;

    public OverflowQueue(int size) {
        queue = new int[size];
    }

    public void enQueue(int n){
        rear = getNextIndex(rear);
        queue[rear] = n;
         if (rear == front || front == -1){
          front = getNextIndex(front);
        }

    }

    private int getNextIndex(int index){
        if (index == queue.length - 1 ){
            index = 0;
        } else {
            index ++ ;
        }
        return index;
    }

    public int deQueue(){
        if (front == -1 ){
           throw new NullPointerException("deQueue operation is called on empty queue.");
        }
        int elem = queue[front];
        if (front == rear ){
            front = -1;
            rear = -1;
        } else {
            front = getNextIndex(front);
        }
        return elem;
    }

    public static void main(String[] args) {
        OverflowQueue q = new OverflowQueue(5);
        q.enQueue(1);q.enQueue(2);q.enQueue(3);
        q.enQueue(4);q.enQueue(5);q.enQueue(6);
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
    }
}

With this implementation, it would not throw a stackoverflow exception but there could be an unusual behavior. Maybe there could be some better exception message to handle this case.

OverflowQueue q = new OverflowQueue(n);

Now, let's say I want to enqueue n+1 number of elements and then dequeue the same number of elements. Here it doesn't throw any error to enqueue n+1 elements. However deQueue method will throw NullPointerException as soon as the method is executed (n+1)th times.

I would prefer to "resize the array" to avoid Stack overflow exception. There is a possibility of unused space in memory in case of resize array implementation if enqueue and dequeue are executed randomly. This can be handled by sinking the array if required.


Grade student as number of array scores Assume that you have the ready sorted array

Is it a good solution?

Plunker OR:

<script>
    var score = [10, 20, 20, 20, 40, 50, 60, 60, 60, 60, 70, 80, 80, 90]
    var j = 0;
    var k = 0;

    for( i in  score ){
        var grade = '';

        if( i== 0 || score[i] > score[i - 1] ){
            grade = j = j+1+k;
            k = 0;
        }else{
            k++;
            grade = j;
        }

        document.write( 'Grade: ' + ( grade ) +'<br>');
    }
    </script>

The value your looking for is more like a position rather then a grade.
Just add...

var position   = 0;
var last_grade = 0;

outside the for loop. then add a comparison before the document.write... statement like so.

if (grade>last_grade) position++;
document.write( 'Grade: ' + ( position ) +'
');
last_grade=grade;

That should give you the following result...

Grade: 1

Grade: 2

Grade: 2

Grade: 2

Grade: 3

Grade: 4

Grade: 5

Grade: 5

Grade: 5

Grade: 5

Grade: 6

Grade: 7

Grade: 7

Grade: 8


Reimplementation of min() in Python I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:

def my_min(num_list):
    minimum = num_list[0]
    for num in num_list[1:]:
        if num < minimum:
            minimum = num
    return minimum

My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?

My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.

iterators

You can use an iterator

def my_min(num_list):
    # empty lists
    if not num_list:
        raise ValueError('Empty list')

    list_iter = iter(num_list)
    minimum = next(list_iter)
    for num in list_iter:
        if num < minimum:
            minimum = num
    return minimum

In response to Mathias' comment, here is a version that works with an iterable:

def my_min(seq):
    seq = iter(seq)

    try:
        minimum = next(seq)

        for num in seq:
            if num < minimum:
                minimum = num

        return minimum

    except StopIteration as e:
        pass

    raise ValueError('Empty list')

Improved based on @Wombatz comment:

def my_min(seq):
    seq = iter(seq)

    try:
        minimum = next(seq)

    except StopIteration as e:
        raise ValueError('Empty list') from None

    else:
        for num in seq:
            if num < minimum:
                minimum = num

        return minimum


Pushing an array into an object with an undefined/non-existing property If I want to "push" an array into my object inside of a property, I must first assure that this property exists - it works the same way for arrays too. However, what is the smoothest way of doing this?
Currently, I am first assigning the property it's first initial value so it gets made: then, since the property exists, I can push data into it.
const result = {};
const data = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];

const key = "helloworld";

if(result.hasOwnProperty(key)) {
  result[key].push(data);
} else {
  Object.assign(result, {
    [key]: data
  });
}

console.log(result);

Which gives me the following object.
{
    helloworld: [
        {
            name: "John Doe"
        },
        {
            name: "Doe John"
        }
    ]
}

What is the smoothest/better way to do this, if there is such a way?

The overall approach looks fine - check if the property exists on the object, and then either create the collection or append the data to the existing collection. While there are other methods than yours that achieve the same thing, none of them is clearly smoother or more semantically appropriate - the tools to do this more concisely just don't exist in vanilla JS yet (though there are libraries like Lodash and Underscore that implement the same sort of logic under the hood).
But, your current code has a bug: if the property already exists on the object, the data will be pushed to the existing array as a subarray, rather than pushing all elements of data to the existing array:

const result = {
  helloworld: [{
    alreadyExistingProp: 'alreadyExistingVal'
  }]
};
const data = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];

const key = "helloworld";

if(result.hasOwnProperty(key)) {
  result[key].push(data);
} else {
  Object.assign(result, {
    [key]: data
  });
}

console.log(result);

You want a flat structure instead. Change
result[key].push(data);

to
result[key].push(...data);

A couple other pointers:
hasOwnProperty? Since it sounds like the values of the object will always be truthy, you can consider making a truthy test instead of using hasOwnProperty:
if (result[key]) {

Object.assign is unnecessary when setting just a single property This:
Object.assign(result, {
  [key]: data
});

can be
result[key] = data;

Mutation worries? Note that the approach used so far will mutate the result object and the data array. Mutation may cause unexpected behavior and bugs elsewhere if other parts of the script have a reference to the object that gets modified. If this is something to worry about, either clone the data before assigning it, or immutably update the result variable (like how state is updated in React).
For a short contrived example of how accidental mutation might result in a bug:

const result = {};
const addData = (data) => {
  const key = "helloworld";
  if(result.hasOwnProperty(key)) {
    result[key].push(...data);
  } else {
    result[key] = data;
  }
};

const dataFromUser = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];
addData(dataFromUser);
addData([{ name: 'Default Name' }]);

// now the `result` object contains all the data
// but the dataFromUser now contains an extra object, which may be a mistake:
for (const item of dataFromUser) {
  console.log('Name from dataFromUser:', item.name);
}

This may well not be a problem for your situation, but variable contents changing unexpectedly due to mutation by code elsewhere is quite a common source of bugs in my experience.
Of course, if you understand well how references to objects work, and have no problem with (or like) the mutation that will occur, feel free to use it.


Pythonic way to do strategy design pattern,avoid use switch base on string compare Here are two functions, which are quite similar. The type of dtIndex is pandas DatetimeIndex and the only difference is the i.dayofyear part. There are days of week, month of year, week of month, week of year I still need to implement.

def extract_day_of_year(dtIndex):
    dayofyear_arr = []
    for i in dtIndex:
        dayofyear_arr.append(i.dayofyear)
    return dayofyear_arr

def extract_day_of_month(dtIndex):
    dayofmonth_arr = []
    for i in dtIndex:
        dayofmonth_arr.append(i.dayofmonth)
    return dayofmonth_arr

Is there a "Pythonic" way than switch according to an additional str parameter?

Yes. The most flexible approach would use getattr.

def extract(attr, datetimeindex):
    return [getattr(x, attr) for x in datetimeindex]

# Now, for example:
extract_day_of_year = partial(extract, attr='dayofyear')

# or
def extract_day_of_month(datetimeindex):
    return extract('dayofmonth', datetimeindex)

Alternatively with attrgetter:

def extract(attr, datetimeindex):
    return map(attrgetter(attr), datetimeindex)

I've also converted the for loop into a list comprehension (first) or map() (second), both of which spare you from needing to name a temporary variable.


Outputting prime numbers in given ranges I coded an algorithm which shows prime numbers in the ranges provided by the user. The first line states the number of test cases. Example:

INPUT

2
1 10
1 5

OUTPUT

2
3
5
7

2
3
5

t - number of cases, n and m is the range
(t<=10)
m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space

And here is my problem, algorithm works fine, but website which test this, shows- too slow. I need less than 6s !

In my opinion, problem is in method addPrimeNumbers.

class PrimeNumbers{

    private static int m = 0;
    private static int n = 0;
    private static int t = 0;
    private static int i = 0;
    private static String beforeSeparate;
    private static Scanner sc = new Scanner(System.in);
    private static List<int[]> scope = new ArrayList<>();

    public static void main (String[] args) {
        t = Integer.valueOf(sc.nextLine());
        if (checkT(t)) {

            beforeSeparate = sc.nextLine();

            if (separate(beforeSeparate).length == 2) {
                m = separate(beforeSeparate)[0];
                n = separate(beforeSeparate)[1];
                i++;
            }
            if (checkM(m) && checkN(n) && t != 1 && n - m <= 100000) {
                int firstScope[] = {m,n};
                scope.add(firstScope);
                repeatReader();
            }
            else if (t == 1 && checkM(m) && checkN(n) && n - m <= 100000){
                int firstScope[] = {m,n};
                scope.add(firstScope);
            }
            for (int[] aScope : scope) {
                addPrimeNumbers(aScope[0], aScope[1]);
            }
        }
    }

    private static void repeatReader(){
        beforeSeparate = sc.nextLine();
        if (separate(beforeSeparate).length == 2){
            m = separate(beforeSeparate)[0];
            n = separate(beforeSeparate)[1];
            i++;
            int nextScope[] = {m,n};
            scope.add(nextScope);
            if (i < t){
                repeatReader();
            }
        }
    }

    private static void addPrimeNumbers(int i, int i1) {
        String result = "";

        for (int j = i; j <= i1 ; j++) {

            int counters = 0;
            for (int num = j; num >= i ; num--) {

                if (j % num == 0){
                    counters = counters +1;
                }
            }
            if (counters == 2){
                result = result + j + "\n";
            }
        }
        System.out.println(result);
    }

    private static boolean checkT(int i){
        return i > 0 && i <= 10;
    }

    private static boolean checkMinMax(int i) {
        return i >= 1 && i <= 1000000000;
    }

    private static boolean checkM(int i) {
        return checkMinMax(i) && n > 0 && i <= n;
    }

    private static boolean checkN(int i) {
        return checkMinMax(i) && m > 0 && i >= m;
    }

    private static int[] separate(String i){
        String twoValue[] = i.split(" ");

        m = Integer.parseInt(twoValue[0]);
        n = Integer.parseInt(twoValue[1]);
        return new int[]{Integer.parseInt(twoValue[0]), Integer.parseInt(twoValue[1])};
    }
}

Someone know, how to speed up this ?

Before addressing the performance problem I would like to make some
general remarks:

You validate the input values (t, m, n), but invalid numbers are
simply ignored. For a programming challenge I would assume that the
input values are in the specific ranges. However, if you decide to
check the validity then an invalid input should produce an error message
or program exception.

Also the check is unnecessary complicated: m and n are passed to
functions checkM and checkN, but those functions also refer to
the class variables m and n directly. This could be simplified to

if (1 <= m && m <= n && n <= 1000000000 && n - m <= 100000) { ... }

Even better, define and use constants for those limits.
The recursive function repeatReader is used to handle all test
cases (but only if there is more than one test case). This seems
unnecessary complicated to me, a simple loop would suffice.
The logic to get two integers from the input line is duplicated
in main and repeatReader.
Several variables are declared as static class variables, but
needed only locally in a function (such as m, n, beforeSeparate).
There is no need to store all ranges in an array first, you can
read each range and then produce the corresponding output.
Scanner.nextInt() can be used to read the input into integers
directly.
In addPrimeNumbers you can print all found prime numbers directly,
without concatenating them to a string first.

So the overall structure could be simplified to

import java.util.Scanner;

class PrimeNumbers {

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int numTests = sc.nextInt();
        for (int test = 1; test <= numTests; test++) {
            int m = sc.nextInt();
            int n = sc.nextInt();
            printPrimesInRange(m, n);
            System.out.println();
        }
    }

    private static void printPrimesInRange(int low, int hi) {
        // Print prime numbers in the range low...hi
    }
}

Note that

       for (int num = j; num >= i ; num--) {

in addPrimeNumbers should be

       for (int num = j; num >= 1 ; num--) {

otherwise the result is not correct for ranges not starting at 1.

With respect to performance: Your function counts all divisors
of a number, but

one can stop the test if any non-trivial divisor has been found,
any non-prime number \$ n \$ has a divisor which is \$ \le \sqrt n \$

Therefore this

    private static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        int limit = (int) Math.sqrt(n);
        for (int j = 2; j <= limit; j++) {
            if (n % j == 0) {
                return false;
            }
        }
        return true;
    }

    private static void printPrimesInRange(int low, int hi) {
        for (int n = low; n <= hi; ++n) {
            if (isPrime(n)) {
                System.out.println(n);
            }
        }
    }

would already improve the performance because the primality check
for each number \$ n \$ is reduced from \$ O(n) \$ to \$ O(\sqrt n) \$.

For the range 100000 200000 this reduced the time from 43 seconds
to approx 0.3 seconds on my 3.5 GHz Intel Core i5 iMac, measured with

$ time java PrimeNumbers < input > output

and for the range 999900000 1000000000 I measured 0.7 seconds.

So this might be sufficiently fast to pass the challenge.
For even better performance, use sieving methods like the
(segmented) sieve of Eratosthenes (see for example https://www.geeksforgeeks.org/segmented-sieve/).


ASP.NET MVC Html.XXFor OK to discard lambda argument and just use Model directly? I find it a bit odd in ASP.NET MVC that the Html helper extensions, like Html.EditorFor, take a Func<T1, TResult> where the T1 argument is just the already in scope Model variable, e.g.:

@Html.EditorFor(x => x.Name)

If I really wanted Model renamed, I would just assign it once to a variable in the top of the razor view. So, I feel compelled to do the following:

@Html.EditorFor(_ => Model.Name)

Does this seem reasonable?

I'd fail this review if I saw it at my company.  Most are probably shown the first approach, doing this will only confuse people that come after you.  Now they have to determine if the way you've chosen is actually equivolent to the "standard" way.  I actually just went through that exercise myself.


T-SQL Query remove duplicates except for original row from the table Question:
There is an Exam_Merge table into which to import
records from a similarly structured table in another database.
In this case, the Exam_Merge table contains the values of the primary key ID
from another database, but this field is not unique.
For some reason, some of the entries in it were duplicated:
an entry with the same ID is contained in the table 2 times,
the values of the remaining field of duplicate records also coincide.

It is necessary to remove duplicates, leaving only non-duplicate IDs.

My question -  is it correct and efficient approach or something efficient way exists?
sqlfiddle: http://www.sqlfiddle.com/#!18/dce35/1

DDL:

CREATE TABLE exam_merge
  (
     id           INT NOT NULL,
     student_code NVARCHAR(10) NOT NULL,
     exam_code    NVARCHAR(10) NOT NULL,
     mark         INT NULL
  );

QUERY:

WITH cte
     AS (SELECT id,
                student_code,
                exam_code,
                mark,
                Row_number()
                  OVER(
                    partition BY id, student_code, exam_code, mark
                    ORDER BY student_code) AS rn
         FROM   exam_merge)
DELETE cte
WHERE  rn > 1

Review

Your SQL seems the generally accepted way (Discussed Before) of deleting duplicates.

WITH cte
     AS (SELECT id,
                student_code,
                exam_code,
                mark,
                Row_number()
                  OVER(
                    partition BY id, student_code, exam_code, mark
                    ORDER BY student_code) AS rn
         FROM   exam_merge)
DELETE cte
WHERE  rn > 1

Optimization

I found a possible optimization using a non-clustered index. You would like to create a (non-unique) index on your key (id) with the other columns included.

CREATE NONCLUSTERED INDEX idx_exam_merge ON exam_merge
(id)
INCLUDE (student_code, exam_code, mark);

This example shows how such index could optimize the query plan to avoid clustered index lookup.


Find the max. difference between two array elements a[j] and a[i] such that j > i The source of the problem is here.

  Given an array of integer elements, return the maximum difference of any pair of
  numbers such that the larger number of the pair occurs at a higher index
  than the smaller.

Here is my implementation in Java.

package algo.mindiff;

public class Main {

    // http://www.careercup.com/question?id=5185822661804032
    public static void main(String[] args) {
        System.out.println(minDiff(new int[] { 10, 1, 12, 3, 4, 28, 1 }));
    }

    private static int minDiff(int[] array) {
        int diff = 0;
        int result = 0;
        for (int i = 0; i < array.length;) {
            int maxIndex = maxIndex(array, i);
            int minIndex = minIndex(array, i, maxIndex);
            diff = array[maxIndex] - array[minIndex];
            if (result < diff)
                result = diff;
            i = maxIndex + 1;
        }
        return result;
    }

    private static int minIndex(int[] array, int start, int end) {
        int min = start;
        for (int i = start + 1; i < end; i++) {
            if (array[i] < array[min]) {
                min = i;
            }
        }
        return min;
    }

    private static int maxIndex(int[] array, int start) {
        int max = start;
        for (int i = start + 1; i < array.length; i++) {
            if (array[i] >= array[max]) {
                max = i;
            }
        }
        return max;
    }

}

And here is a brief summary of my algorithm:

I find the maximum element in the given array. Its index is maxIndex.
Then I find the minimum element within the range [0, maxIndex). Its index is minIndex.
If the difference result I calculated last time is less than the difference diff between array[maxIndex] and array[minIndex], I'll just assign the new value to result.
I do steps 1 - 3 for the other elements of the array starting with maxIndex + 1.

If my algorithm doesn't work on any input data you might have in mind, please let me know.

The algorithm you're using does a bunch of superfluous work. It would be much more efficient to concentrate on tracking the maximum difference that conforms to the specification than where you are in the array.

Setting the maxIndex the first time through your main loop isn't really setting any meaningful limit for you, because you also need to check to see if there are any other number combinations that have a higher difference than just the array maximum. In fact, you don't need to know what the highest value is at all or it's position in the array. The highest difference already assumes both of these, because when you set the greatest difference it is calculated based on the lowest value up to the current point in the array.

The idea of limiting the minimum check to the position of the previous high is well intentioned, but why not just run through the array once and keep track of everything at the same time?

The pseudo-code is much simpler:

Set the first value in the array to your low value.
Loop through the
array.
If the current element minus the low value is higher than the
maximum difference found, update the maximum difference.
If the current element is lower than the previous low, update the previous
low value.
Return the maximum difference when you hit the end of the array.


Setting some element widths, disabling a button, and initializing some date fields Does anyone have suggestions on how to refactor this?

$(document).ready(function () {

        $("td,select,th").css("min-width", "150px");

        $("#cancel").button({
            disabled: true
        });
        $(".group-32 input").datepicker();
        $(".group-6 input").datepicker();

        $("#0LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#0EffectiveDate").val("01/01/" + (currentYear + 1));
        });

        $("#1LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#1EffectiveDate").val("01/01/" + (currentYear + 1));
        });

        $("#3LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#3EffectiveDate").val("01/01/" + (currentYear + 1));
        });
    });

Since your code is all the same, you can dynamically create your selector:

...

$( '#0LevelId,#1LevelId,#3LevelId' ).change( function(){
    ...
    $( '#' + this.id.substr( 0, 1 ) + 'EffectiveDate' )...
} );


Method that receives a hexadecimal string and returns a formatted matrix of those values This method is part of a larger project and comes after encoding ascii characters into hexadecimal values, so it assumes the parameter is always a valid hex string.

public static String toMatrix(String hex) {

    StringBuilder builder = new StringBuilder();
    int rows = 0;
    int columns = 16;
    int row = 0;
    int column = 0;

    rows = ( hex.length() / 32 ) + ( hex.length() % 32 );

    for (row = 0; row < rows; row++) {

        for (column = 0; column < columns; column++) {

            if (hex.length() > 0) {

                builder.append(hex.substring(0,2));
                hex = hex.substring(2,hex.length());

                if ((column + 1) % 4 == 0) {

                    builder.append("  ");
                }else {

                    builder.append(" ");
                }
            }
        }

        builder.append("\n");
        column = 0;
    }

    return builder.toString().trim();
}

Input:

1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D1D

Output:

1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C
1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C  1C 1C 1C 1C
1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D
1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D  1D 1D 1D 1D

In which way can this method be better?

int columns = 16;

This should be a constant and defined outside the method.

public static final int MATRIX_WIDTH = 32;

I prefer singular names for scalar variables.  I use plural names for collections.

I'll explain the value change later.

    int row = 0;
    int column = 0;

These could be declared with their loops.

    rows = ( hex.length() / 32 ) + ( hex.length() % 32 );

This seems wrong.  Consider

    matrixHeight = ( hex.length() / MATRIX_WIDTH ) + (( hex.length() % MATRIX_WIDTH == 0 ) ? 0 : 1);

Does that do what you want?  Test it with a 224 character string to be sure.

But you could probably do without it.

    for (row = 0; row < rows; row++) {

        for (column = 0; column < columns; column++) {

            if (hex.length() > 0) {

I'd try

    while ( !hex.isEmpty() ) {

        for (int column = 2; column <= MATRIX_WIDTH && !hex.isEmpty(); column += 2) {

This way you don't keep looping after reaching the end of the string.  And you don't need row or rows at all.

I'll explain the 2 in a moment.

                hex = hex.substring(2,hex.length());

This could be just

                hex = hex.substring(2);

You don't need to specify the end of the string if that's how far you want to go.  It's the default in the one argument version.

                if ((column + 1) % 4 == 0) {

But if we start at 2, this could be just

                if (column % 8 == 0) {

Now you don't have to calculate every iteration.  You can just work off the variable directly.


Dynamically create a table with values from an object I want to create a table that looks like this:

--------------------------------------------------
|                         | USD            |CAD   |
--------------------------------------------------
|Smallest Donation        | 100            |250   |
--------------------------------------------------
|Largest Donation         | 9200           |7600  |
--------------------------------------------------
|                                                 |
--------------------------------------------------
|Total Donation           | 12500          |11000 |
--------------------------------------------------

using the values from this object:

perCurrency: {USD:{0:100, 1:200, 2:9200, 3:1500, 4:1500}, PHP:{0:250, 1:7600, 2:150, 3:3000}}

I have this code and it actually works, though I believe there's an easier and shorter way to this using only one loop.

var numOfCurrency = Object.keys(perCurrency).length + 1;
var donation_table = '';
donation_table += '
';
donation_table += '
&nbsp;	';

$.each(perCurrency, function(index, value){
  donation_table += ''+index+'	';
});

donation_table += '

Smallest Donation	';
$.each(perCurrency, function(index, value){
  var lowest = Infinity;
  $.each(value, function(k, v){
    if (v < lowest) lowest = v;
  });
  donation_table  += ''+lowest+'	';
});

donation_table += '

Largest Donation	';
$.each(perCurrency, function(index, value){
  var highest = 0;
  $.each(value, function(k, v){
    if (v > highest) highest = v;
  });
  donation_table += ''+highest+'	';
});

donation_table += '

&nbsp;

Total Donation	';
$.each(perCurrency, function(index, value){
  var total = 0;
  $.each(value, function(k, v){
    total = total + v;
  });
  donation_table += ''+total+'	';
});

donation_table += '

';

$("#giving_capacity").html(donation_table);

I am trying to put this table in a div with an id #giving_capacity.

I rewrite in my style with only loop. It maybe easier to read.

perCurrency = {
  USD: { 0:100, 1:200, 2:9200, 3:1500, 4:1500 },
  CAD: { 0:250, 1:7600, 2:150, 3:3000 }
};
var numOfCurrency = Object.keys(perCurrency).length + 1;
var donation_table;
donation_table = $('<table>').attr('id', 'donation_table').addClass('table table-condensed'));

$.each(perCurrency, function(index, currency) {
  var lowestInCurrency  = Infinity,
      highestInCurrency = 0,
      totalInCurrency   = 0;
  $.each(currency, function(k, v){
    totalInCurrency = totalInCurrency + v;
    if (v < lowestInCurrency) lowestInCurrency = v;
    if (v > highestInCurrency) highestInCurrency = v;
  });

  donation_table.append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').html('&nbsp;')
    ).append(
      $('<td>').css('width', '150px').text(index)
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Smallest Donation')
    ).append(
      $('<td>').text(lowestInCurrency)
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Largest Donation')
    ).append(
      $('<td>').text(highestInCurrency)
    )
  ).append(
    $('<tr>').append(
      $('<td>').attr('colspan', numOfCurrency).html('&nbsp;')
    )
  ).append(
    $('<tr>').append(
      $('<td>').css('font-weight', 'bold').css('width', '160px').text('Total Donation')
    ).append(
      $('<td>').text(totalInCurrency)
    )
  );
});

$("#giving_capacity").html(donation_table);


Iterating worksheets and cells, copying data to summary sheet I have been working on this particular sub for a while and it was very very slow from the beginning. Compared to my other subs that go through a lot more data the task of this one is almost minuscule. All it has to do is to go through about ~15 sheets and parse through a couple hundred cells. Since this is a fairly complicated task I need to test it a lot which becomes almost unbearable with how long it takes. I am not sure if there is anything I can do or if there even is a solution. I am open to all kinds of suggestions.

Private Sub CommandButton24_Click()

Dim xSheet As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim copyRng As Range
Dim destRng As Range
Dim cRange As Range
Dim c As Range
Dim uniqueVal() As Variant
Dim x As Long

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

'Delete the summary worksheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Summary").Delete
On Error GoTo 0
Application.DisplayAlerts = True

' Add a worksheet with the name "Summary"
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Summary"
DestSh.Range("A1").Value = "Account"
DestSh.Range("B1").Value = "Exchange"
DestSh.Range("C1").Value = "Quarter"
DestSh.Range("D1").Value = "Year"
Set destRng = DestSh.Range("E1")

'Define inital array values
uniqueVal = Array("Account by Type", "Total", "lv_nsac_ACCOUNT", "ams_ACCOUNT", "bru_ACCOUNT", "lsem_ACCOUNT", "mse_ACCOUNT", "par_ACCOUNT", "swx_ACCOUNT", "us_ACCOUNT", "wbag_ACCOUNT", "xetra_ACCOUNT", "europe_ACCOUNT", "lv_ACCOUNT", "lv_apac_ACCOUNT")

' This first part subtracts all the relevant column names, just running this
'already took excel about 3-5 minutes
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each xSheet In ActiveWorkbook.Worksheets

    If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _

        Set copyRng = xSheet.Range("A:A")

        For Each c In copyRng.SpecialCells(xlCellTypeVisible)

            If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _

                'Copy to destination Range
                c.Copy destRng
                'move destination Range
                Set destRng = destRng.Offset(0, 1)
                'change / adjust the size of array
                ReDim Preserve uniqueVal(0 To UBound(uniqueVal) + 1) As Variant
                'add value on the end of the array
                uniqueVal(UBound(uniqueVal)) = c.Value

            End If

        Next c

    End If

Next xSheet

'This second part is supposed to capture account names from the sheets and
'and put them in the first column. The command has been running for 20
'minutes with the program being completely non responsive.
'Loop through all worksheets and copy the data to the
'summary worksheet.
For Each xSheet In ActiveWorkbook.Worksheets

    If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _

        Set copyRng = xSheet.Cells

        For Each c In copyRng.SpecialCells(xlCellTypeVisible)

            If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _

                If InStr(1, c.Value, "C-") Then _

                'Set destination
                Set destRng = xSheet.Range("A2:A").Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues)

                'Copy to destination Range
                c.Copy destRng

                End If

            End If

        Next c

    End If

Next xSheet

ExitTheSub:

Application.Goto DestSh.Cells(1)

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub

Sorry for the massive block of code.

I have found the answer. What seems to have cause the issue is these lines of code:

Set copyRng = xSheet.Range("A:A")
Set copyRng = xSheet.Cells

All I wanted was to access the entire sheet with all of its non-empty cells. This seems to have been the wrong way of doing that since the code does in fact only take mere fractions of a second if I give it a clear defined range such as "A1:A100" in case of the first instance.


Multilingual command handler using inheritance My problem is that you have a lot of ifconditions to be checked and inside that if condition you have multiple lines of code. I want to eliminate it and use inheritance instead. For every if statement I will be using a separate class to handle it. This is more like a derivative of the command pattern but not command pattern itself.

I have an interface which contains only one method which defines the task I want it to be implemented. I have an abstract class implementing that interface and contains a static map and static methods to add values and retrieves the task. The classes I specified will be extending this Handler class.

This is my scenario:

I am sending a string as parameter to get a specific translator. Let's say Sinhala or Tamil or English. On each implementation of those translators, I will be adding the necessary values to the map in the Handler class in a static block. Basically adding them in the class load time.

Command Interface

public interface Command {
    LanguageTranslator getLangTranslator();
}

Handler Abstract class

public abstract class Handler implements Command {

    private static Map<String, Command> map = new HashMap<>();

    public static void AddToMap(String key, Command command){

        map.put(key,command);
    }
    public static LanguageTranslator getTranslator(String value) throws Exception {
        if (!(map.containsKey(value))){
            throw new LanguageNotFoundException("Translator not found");
        }else {
            return map.get(value).getLangTranslator();
        }
    }

 }

Sinhala Translator

public class SiCommand extends Handler {
    static {
        Handler.AddToMap("1",new SiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new SiTranslator();
    }
}

Tamil Translator

public class TiCommand extends Handler {
    static {
        Handler.AddToMap("2",new TiCommand());
    }

    @Override
    public LanguageTranslator getLangTranslator() {
        return new TiTranslator();
    }
}

English Translator

public class EnCommand extends Handler {
    static {
        Handler.AddToMap("3",new EnCommand());
    }

@Override
    public LanguageTranslator getLangTranslator() {
        return new EnTranslator();
    }
}

Demo

 RowTranslator rowTranslator = Handler.getTranslator("2");

Questions

Since all values are assigned to the map during the class loading time these are my questions:

Is using static blocks like this a good practice?
I want to eliminate the use of if conditions as I mentioned before. By using this method, whenever someone wants to add a new if condition, you just only have to create a new class extending handler and implement it. Therefore the outside user doesn't need to know the internal handling of the Command's subclasses. The output is just gonna be a translator. Is this a good way of doing it? What are the better alternatives? What should be adjusted?

Note: I will also be focusing strictly on Open/Close principle as well.

Static registration should be avoided. Not only because it is global code, burdening start-up and the class must be loaded (!), but also for unit-testing and diversification (proposing Tamil+English and Sinhala+Tamil as two configurable choices).

This is almost something for declarative extensions, say in XML with class loading with Class.forName.

You also might opt for loading by convention or configuration: instead of 1, 2, 3 use "si", "ti", "en" checked by a config properties "translators=si,ti,en" or "si=mypackage.SiTranslator".

Or a discovery system: java SPI (Service Provider Interface): in META-INF/services/ a text file mypackage.Command containing the class name(s). You can have several jars.

A map held in a singleton object is not bad, with a small, not very dynamic domain, like languages.

Map<String, Command> commandsMap = new HashMap<>();

But you might consider the overhead of 3 or more languages, when only 2 are used on average. Say if they load a dictionary. In that case: register first
producers of those classes, which you then place in the map with a java 8 Supplier<Command>:

register("si", SiTranslator::new);
register("ta", TaTranslator::new);
register("en", EnTransleightour::new);

A special factory class as your Handlers does not seem needed, or can in java 8 be defined as interface annotated with @FunctionalInterface and written as anonymous lambda.

Open/Close would imply using the java SPI, where you plug-in a new language, possibly in a separate jar. You still better use "si" (best the Locale key) instead of a number "1". One interface method would be String getKey().

However I would not say that a declarative or map registry at one place would be a sin. A specified orchestrated system behavior (at one point) is just as worthwile as independent extendibility. Only if you want to plug-in new languages, say separate jars, then it matters.

The Open/Close Principle is important for multitudes, maybe fine grained business rules. Open domains of a large magnitude.


Can this code be cleaned? Multiple objects triggering different hover events When the user visits the web page and hovers over an album artwork, the title of the piece and the artist name appears. It leaves when the mouse leaves.
I have achieved this with the following code:
HTML:

artist

song title

artist

song2

JQuery

    $(document).ready(function () {

    $("img#pic1").hover(

    function () {
        $("div.info1").animate({
            'opacity': 1
        });
    },

    function () {
        $("div.info1").animate({
            'opacity': 0
        });
    });
});
$(document).ready(function () {

    $("img#pic2").hover(

        function () {
            $("div.info2").animate({
                'opacity': 1
            });
        },

        function () {
            $("div.info2").animate({
                'opacity': 0
            });
        });
    });

The problem is with the javascript; I have to manually add new parts when I add a new image and it takes up a lot of space. Is there a way to condense the code?

CSS:
    .info1, .info2 {
    opacity:0;
}

http://jsfiddle.net/burntember/22grA/

In your hover method you want to select the next two divs after the img. Assuming that the divs are located (in DOM) immediately after the img, then you can select them using the jQuery .next() method, instead of selecting them by name.

ALso instead of selecting each img by id, you could give them all the same class, and then use a single jQuery selector to select every img with that class.

Untested and probably slightly buggy example code:

artist

song title

artist

song2

$(document).ready(function () {

    $("img.album").each().hover(

        $div = $(this).next(); // find the next element after this img

        function () {
            $div.animate({
                'opacity': 1
            });
        },

        function () {
            $div.animate({
                'opacity': 0
            });
        });
    });

If the div element is not immediately after the img (so you can't use the .next method), you can relate each div to its img by defining a new attribute which begins with data-, for example data-img-id:

artist

song title

artist

song2

Then, in your general-purpose hover method, you can get the id of the this img tag, and use that id value to select the corresponding div using its data-img-id element.


Count array inversions merge sort How does it look?  Comments, code correctness, etc.

//Function Prototypes
void buildArray(int anArray[]);

void printArray(int anArray[], int start, int end);
void sortArray(int start, int end, int masterArray[], int tempArray[]);
void mergeArray(int start, int split, int end, int masterArray[], int tempArray[]);

void bruteCount(int masterArray[]);

//Globals BAD, but gets the job done here
long long INVERSIONS_SORT = 0;
long long INVERSIONS_BRUTE = 0;
const int size = 100000;

void main() {
  int masterArray[size];
  int tempArray[size];

  buildArray(masterArray);

  bruteCount(masterArray);
  cout << "Inversion from Brute: " << INVERSIONS_BRUTE << endl;
  cin.get();

  sortArray(0, size - 1, masterArray, tempArray);
  cout << "Inversions from Sort: " << INVERSIONS_SORT << endl;

  cin.get();
}

//Builds an array from a txt file
void buildArray(int anArray[]) {
  ifstream dataFile;
  dataFile.open("integerArray.txt", ios::in);

  for (int i = 0; i < size; i++)
    dataFile >> anArray[i];
}

//Prints the entire array
void printArray(int anArray[], int start, int end) {
  for (int i = start; i <= end; i++)
    cout << anArray[i] << " ";

  cout << endl;
}

//Recursive function to split the array into sub arrays for merging
void sortArray(int start, int end, int masterArray[], int tempArray[]) {
  int split = (start + end) / 2;

  if (start < end) {
    sortArray(start, split, masterArray, tempArray);
    sortArray(split + 1, end, masterArray, tempArray);
    mergeArray(start, split, end, masterArray, tempArray);
  }

}

//Master function to marge two arrays into the correct order, and track the number of inversions
void mergeArray(int start, int split, int end, int masterArray[], int tempArray[]) {
  int leftCount = start; //Counter for left array
  int rightCount = split+1; //Counter for right array
  int tempCount = start; //Counter for temporary array

  while ((leftCount <= split) && (rightCount <= end)) { //When there are still values in both arrays
    if (masterArray[leftCount] <= masterArray[rightCount]) { //If value of left array is lower
      tempArray[tempCount] = masterArray[leftCount];
      leftCount++;
    }
    else {
      tempArray[tempCount] = masterArray[rightCount];  //If value of right array is lower
      INVERSIONS_SORT = INVERSIONS_SORT + (split + 1 - leftCount);  //If value of the right array is lower, add how many left array values are higher (number of inversions) and add to count
      rightCount++;
    }
    tempCount++;
  }

  //Cleanup when either array is done
  if (leftCount > split) {
    for (int i = rightCount; i <= end; i++) {
      tempArray[tempCount] = masterArray[i];
      tempCount++;
    }
  }
  else {
    for (int i = leftCount; i <= split; i++) {
      tempArray[tempCount] = masterArray[i];
      tempCount++;
    }
  }

  //Copy back into master array
  for (int i = start; i <= end; i++)
    masterArray[i] = tempArray[i];

}

//Counts the number of inversions via brute force, here to check to see if MergeSort method is working correctly
void bruteCount(int masterArray[]) {
  int i, j;

  for (i = 0; i < size-1; i++)
    for (j = i + 1; j < size; j++)
      if (masterArray[i] > masterArray[j])
        INVERSIONS_BRUTE++;
}

The comment about the globals is noisy, but at least you're aware that they're bad.  You can reduce the possibility of bugs by removing them, which is always good idea.  Otherwise, it could suggest that this implementation needs reworking, especially if you do encounter some bugs.

Side-note: size is technically a constant, not a global.  It's okay to have constants in global scope as they cannot be modified elsewhere.
I would recommend replacing the C-arrays with a storage container such as std::vector or std::array (if you have C++11).  In C++, it's not good to pass C-arrays to functions because they decay to pointers instead of passing the array itself.  Storage containers, on the other hand, do not do this; they pass an object.  That said, your implementation looks very C-like, although that's not relevant to the sorting.  It's still worth knowing about storage containers in C++.

You will also be able to invoke operator= in one line to reassign the master array to the temp array instead of using a manual loop.  These little things will help make your code cleaner.
For bruteCount():

Why are i and j declared outside the loop statement?  It's done differently elsewhere, so it should be done here as well.
The loops and the if statement should have curly braces, even if the body of a statement is just one line (also more a general recommendation).  Not having them this way could hurt maintenance, in case you ever need to add or remove something.


Find the square root of the number without using any built-in function? I am working on below problem:

  Given an integer, how do you find the square root of the number
  without using any built-in function?

  private static double computeSquareRootBinarySearch(double x, double precision) {
    double start = 0;
    double end = x / 2 + 1;
    double mid = (start + ((end - start) / 2));
    double prevMid = 0;
    double diff = Math.abs(mid - prevMid);

    while ((mid * mid != x) && (diff > precision)) {
      if (mid * mid > x) {
        end = mid;
      } else {
        start = mid;
      }
      prevMid = mid;
      mid = (start + end) / 2;
      diff = Math.abs(mid - prevMid);
    }
    return mid;
  }

I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?

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


C++ compile-time checked switch 'statement' In the project I work on there are several places where a switch statement is used on a type enum. (I know, better to use virtual functions or a visitor pattern or something, but sometimes switching on type codes is unavoidable - e.g., deserializing XML.) All of our type enums are of the simple form enum { TypeA, TypeB, TypeC, NumTypes } so it is known at compile time that all type codes for a given type are in the half-open range [0, NumTypes).

I decided to see if I could make the compiler verify that all type codes were being checked, and this is what I came up with:

// Switch.h

template <int iIndex, int iCount, class Dispatcher>
struct Switcher
{
    typename Dispatcher::ResultType
    operator()( const Dispatcher& dispatcher, int iCase ) const
    {
        if ( iCase == iIndex )
        {
            return dispatcher.template Case<iIndex>();
        }
        else
        {
            return Switcher<iIndex + 1, iCount, Dispatcher>()( dispatcher, iCase );
        }
    }
};

template <int iCount, class Dispatcher>
struct Switcher<iCount, iCount, Dispatcher>
{
    typename Dispatcher::ResultType
    operator()( const Dispatcher& dispatcher, int iCase ) const
    {
        return dispatcher.Default( iCase );
    }
};

template <int iCount, class Dispatcher>
typename Dispatcher::ResultType
Switch( const Dispatcher& dispatcher, int iCase )
{
    return Switcher<0, iCount, Dispatcher>()( dispatcher, iCase );
}

Example use:

#include "Switch.h"

#include <iostream>
#include <cassert>
#include <string>

enum MyType { TypeA, TypeB, TypeC, NumTypes };

class MyDispatcher
{
public:
    typedef std::string ResultType;

    template <int iType>
    std::string Case() const;

    std::string Default( int iType ) const;
};

template <>
std::string
MyDispatcher::Case<TypeA>() const
{
    return "TypeA";
};

template <>
std::string
MyDispatcher::Case<TypeB>() const
{
    return "TypeB";
};

template <>
std::string
MyDispatcher::Case<TypeC>() const
{
    return "TypeC";
};

std::string
MyDispatcher::Default( int iType ) const
{
    std::cout<< "ERROR: Unexpected type " << iType << std::endl;
    assert( false );
    return std::string();
}

int main() {
    MyType iType = TypeB;

    std::string zTypeName = Switch<NumTypes>( MyDispatcher(), iType );

    std::cout << "Type name: " << zTypeName << std::endl;
}

The Switcher template class will recursively instantiate versions of itself with increasing type codes, starting with zero and terminating at the iCount template parameter to the Switch function. Each instantiation will check its iIndex template parameter against the runtime iCase variable and call the dispatcher's Case<iIndex> function if it matches. The Default function will only be called if the runtime iCase variable is outside the expected range.

The key is that if any specialization of Case is missing in the dispatcher class, a linker error will be given complaining about a missing function. I know that many (most?) compilers can be set to produce warnings if not all members of an enum are handled in a switch statement, but there are too many places in the codebase (and likely in external headers) where not all cases are handled by design.

Thoughts? Any potential pitfalls? The system could be pretty easily extended to a range of enum values not starting at zero, but non-contiguous enum values would be a no-go.

That seems like an awful lot of boilerplate code to replace a single diagnostic that already exists in a lot of compilers. You're replacing

switch (fruit) {
  case APPLE: return "apple"; break;
  case PEAR: return "pear"; break;
  case PLUM: return "plum"; break;
}

with

<at file scope>
NEWSWITCH(uniqueID, std::string);
DEFCASE(uniqueID, APPLE) { return "apple"; }
DEFCASE(uniqueID, PEAR) { return "pear"; }
DEFCASE(uniqueID, PLUM) { return "plum"; }
DEFDEFAULT(uniqueID) { assert(false); }

...
Switch<NumTypes>(uniqueID(), fruit);

The most onerous requirement there is putting all the switch logic at file scope; you can't localize it to the actual codepath where it's going to be used. The second most onerous requirement is coming up with uniqueID, a global identifier which must be different for each switch that you convert using this pattern.

A much better solution to your original problem would be to use an array:

int main() {
    MyType iType = TypeB;

    std::string typenames[NumTypes] = { "TypeA", "TypeB", "TypeC" };

    assert(0 <= (int)iType && (int)iType < NumTypes);
    std::string zTypeName = typenames[iType];

    std::cout << "Type name: " << zTypeName << std::endl;
}

This code statically enforces that each index in 0..NumTypes-1 is associated with a std::string in the array; and (just like your original code) it dynamically asserts that iType is in the proper range.


Drawing circles from array to a Form I've actually been struggling with painting with VB.Net for a few weeks. All I know is that I shouldn't use CreateGraphics if I can avoid it, so I've done just that. One of the community-challenge questions comes from a CodeGolf challenge that requires users to draw sprockets.

This is only my beginning of that. I've never displayed anything I haven't drawn in excel. At first I tried a Class of sprockets, but it wouldn't fill my List properly, so I've boiled it down to

populating an array
passing that array to the form
Painting my circles.

Essentially I read the input, convert it to integer array, send that to the form and draw the circles. I've probably made it way too complicated, but like I said, I've struggled for a few weeks, which is why I'm here. Parsing the input was pretty tricky to me, actually.

Input

Comes in the form of (sets of) 3 integers (x-position, y-position, radius) e.g.

(0, 0, 16),  (100, 0, 16),  (100, 100, 12),  (50, 50, 24),  (0, 100, 12)

Output

Standard Module

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Imports System.IO
Module Module1
    Const INPUT_PATH As String = "C:\Temp\gearinput.txt"
    Public delimiter() As String = {"),"}
    Sub Main()
        Dim inputData() As String
        inputData = GetInput()
        Dim sprocketData() As String = Custom_Split(inputData(0))
        Dim paintingdata(,) As Integer = StringToIntArray(sprocketData)
        Dim targetForm As New Form1
        targetForm.Visible = True
        targetForm.DrawSprockets(targetForm, paintingdata)
    End Sub
    Private Function Custom_Split(ByVal stringToSplit As String) As String()
        stringToSplit = stringToSplit.Replace("(", String.Empty)
        stringToSplit = stringToSplit.Replace(" ", String.Empty)
        Dim stringArray() As String = stringToSplit.Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
        stringArray(stringArray.Length - 1) = stringArray(stringArray.Length - 1).Replace(")", String.Empty)
        Return stringArray
    End Function
    Private Function StringToIntArray(ByVal sprocketdata() As String) As Integer(,)
        Dim firstDimensionSize As Integer = sprocketdata.GetUpperBound(0)
        Dim integerArray(firstDimensionSize, 2) As Integer
        Dim tempString() As String
        For i As Integer = 0 To firstDimensionSize
            tempString = sprocketdata(i).Split(","c)
            For j = 0 To 2
                integerArray(i, j) = Convert.ToInt32(tempString(j))
            Next
        Next
        Return integerArray
    End Function

    Private Function GetInput() As String()
        Return File.ReadAllLines(INPUT_PATH)
    End Function
End Module

Form Code

Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Const BUFFER As Integer = 20
 Dim xValue As Integer
    Dim yValue As Integer
    Dim pRadius As Integer
    Dim paintData(,) As Integer
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load

    End Sub
Public Shared Sub DrawSprockets(ByVal myForm As Form1, ByVal dataArray(,) As Integer)
        myForm.paintData = dataArray
        For i As Integer = 0 To myForm.paintData.GetUpperBound(0)
            myForm.paintData(i, 0) += 10
            myForm.paintData(i, 1) += 10
        Next
        myForm.Refresh()
    End Sub

    Private Sub Form1_Paint(ByVal sender As Object, e As PaintEventArgs) Handles MyBase.Paint
Dim myPen As Pen

        myPen = New Pen(Brushes.Black)

        For i As Integer = 0 To paintData.GetUpperBound(0)
            e.Graphics.DrawEllipse(myPen, New Rectangle(paintData(i, 0), paintData(i, 1), paintData(i, 2), paintData(i, 2)))
            e.Graphics.FillEllipse(Brushes.Black, New Rectangle(paintData(i, 0), paintData(i, 1), paintData(i, 2), paintData(i, 2)))

        Next

    End Sub

End Class

The overall structure of your code looks good, but the readability is a tad poor. You should always strive to follow the Framework Design Guidelines. Use proper naming and add a few linebreaks.

Rather than using arrays, create a dedicated "Sprocket" class to hold the parsed input data.

Public Class Sprocket
    Public Property X As Integer
    Public Property Y As Integer
    Public Property R As Integer
End Class

Now, if you add the rest of the non-numeric characters to the separator list you could actually read and parse the file in two lines. (Though you ougth to use the line-continuation character for readability as seen at the bottom)

Dim numbers = File.ReadAllText("C:\Temp\gearinput.txt").Split($"{Environment.NewLine} ,)(".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(Function(n) Integer.Parse(n)).ToArray()
Dim sprockets = Enumerable.Range(0, (numbers.Length \ 3)).Select(Function(i) New Sprocket With {.X = numbers(((i * 3) + 0)), .Y = numbers(((i * 3) + 1)), .R = numbers(((i * 3) + 2))}).ToArray()

Sprocket.vb

Public Class Sprocket

    Public Property X As Integer
    Public Property Y As Integer
    Public Property R As Integer

    Public Overrides Function ToString() As String
        Return $"{{ X={Me.X}, Y={Me.Y}, R={Me.R} }}"
    End Function

End Class

Program.vb

Public Module Program

    <STAThread>
    Public Sub Main()

        'TODO: Read file
        Dim input = "(0, 0, 16),  (100, 0, 16),  (100, 100, 12),  (50, 50, 24),  (0, 100, 12)"

        Dim numbers = input _
            .Split($"{Environment.NewLine} ,)(".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) _
            .Select(Function(n) Integer.Parse(n)) _
            .ToArray()

        Dim sprockets = Enumerable _
            .Range(0, (numbers.Length \ 3)) _
            .Select(Function(i) New Sprocket With
            {
                .X = numbers(((i * 3) + 0)),
                .Y = numbers(((i * 3) + 1)),
                .R = numbers(((i * 3) + 2))
            }) _
            .ToArray()

        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.Run(New Window(sprockets))

    End Sub

End Module

Window.vb

Public Class Window
    Inherits Form

    Private ReadOnly sprockets As Sprocket()

    Public Sub New(sprockets As Sprocket())

        If (sprockets Is Nothing) Then
            Throw New ArgumentNullException(NameOf(sprockets))
        End If

        Me.sprockets = sprockets

        Me.SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer, True)

        Me.Text = "Sprockets"
        Me.AutoScaleMode = AutoScaleMode.Font
        Me.ClientSize = New Size(800, 450)

    End Sub

    Protected Overrides Sub OnPaint(e As PaintEventArgs)

        e.Graphics.Clear(Me.BackColor)
        e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.HighQuality

        For Each sprocket In Me.sprockets

            Dim diameter = (sprocket.R * 2)
            Dim rect = New Rectangle(sprocket.X, sprocket.Y, diameter, diameter)

            e.Graphics.FillEllipse(Brushes.Black, rect)

        Next

    End Sub

End Class


Extraction of value from a dict-tree, given a path of arbitrary length Problem: We read a complex json-file which grants us a tree in terms of a python "dict of dicts". We're then requested to retrieve a specific path from the tree, represented by a list of elements. The list (i.e. the path) may have any, arbitrary length.

Simple Example:

# The dict-tree:
d = {"a":{"1":{"aa":"a2", "aaa":"a3"}},
     "b":{"2":{"bb":"b2", "bbb":"b3"}},
     "c":{"3":{"cc":"c2", "ccc":"c3"}},
     "d":{"4":{"dd":"d2", "ddd":"d3"}},
     "e":{"5":{"ee":"e2", "eee":"e3"}}
     }

# The path ..
p = ["b", "2", "bb"] # --> "b2"

Solution (to be improved):
Now, a naive solution could be to simply return d[p[0]][p[1]][p[2]]. However this obviously fails for any path-length not equal to three. Thus, I wrote two functions as shown below,

# Recursive approach
def get_val_from_path_1(d, p):
    if len(p)>1 and p[0] in d:
        return get_val_from_path_1(d[p[0]], p[1:])
    if p[0] in d:
        return d[p[0]]
    return None

# Iterative approach
def get_val_from_path_2(d, p):
    tmp = d
    for s in p:
        if not s in tmp:
            return None
        tmp = tmp[s]
    return tmp

A (very) simple time-consumption test can be run on my repl.it, which suggests that the iterative approach (no.2) is significantly faster than the recursive (no.1).

Preferably, I would really like a simpler approach, without any need of loops, however, any suggestions that improves performance, readability and/or code-line-usage are most appreciated.

EDIT: The question was intended for Python-3.x. I do not edit the label, because it is discussed in the comments of the below answer(s).

Recursive Approach Review

In this method you are performing too many look-ups.

First, you are looking up the 0th value of p two or three times.  List indexing does take time, so it may be faster to store p[0] in a local variable, to avoid repeatedly indexing into the list.

Second, you are  performing a dictionary looking ups two or three times.  While dictionary look-ups are fast, ideally \$O(1)\$ in time, they do take time.  p[0] in d is a dictionary lookup without retrieving the looked up value; d[p[0]] is a dictionary lookup that retrieves the value.

The first and second if statements do effectively the same things.  They check p[0] in d, and if true, they retrieve d[p[0]].  We can extract this common functionality, perform it once, and then, depending on len(p), perform the recursion.  Additionally, we'll use dict.get(p[0], None) to perform a single dictionary lookup, using the value from a single list index operation:

def get_val_from_path_1(d, p):
    d = d.get(p[0], None)
    if d is not None and len(p) > 1:
        return get_val_from_path_1(d, p[1:])
    return d

Note: I used d is not None, instead of simply testing if d is "truthy", so that if a subkey is requested of a "falsy" value (0, False, ""), the dictionary lookup will happen in the recursive call, and an exception will be raised similar to the original code.

EDIT: As mentioned by RootTwo in the comments, it is "safer" to use a sentinel object, in case None is an actual value contained in the JSON object.  Although if None values are contained in the JSON object, it is ambiguous as to whether the key does not exist, or exists with the value None:

def get_val_from_path_1(d, p):
    sentinel = object()
    d = d.get(p[0], sentinel)
    if d == sentinel:
        return None
    if len(p) > 1:
        return get_val_from_path_1(d, p[1:])
    return d

Iterative Approach Review

This code begins with tmp = d, which is odd as d is never used in the remainder of the code.  The temporary variable can be removed.

Similar to the Recursive Approach, you are using a double dictionary lookup.  s in tmp followed by tmp[s].  Again, using tmp.get(s, None) would perform the dictionary lookup once, and return None if the key was not present.

def get_val_from_path_2(d, p):
    for s in p:
        d = d.get(s, None)
        if d is None:
            break
    return d

EDIT: A sentinel can be used here as well, with the same ambiguity disclaimer:

def get_val_from_path_2(d, p):
    sentinel = object()
    for s in p:
        d = d.get(s, sentinel)
        if d is sentinel:
            return None
    return d

Which approach is better?

EDIT: Clarifications added at based on comments by Konrad.

Gloweye attempts to make the case that "recursive is the way to go".  I disagree.

First off, Python does not do tail call optimization.  If it did, it would close the performance gap with the iterative approach, but with the current recursive implementation, the iterative method would still win.

In each recursive call, the p[1:] is being passed to the p argument.  This is building a brand-new list, and copying the elements to the new list.  With n items in the original list, n-1 elements are copied the first time, n-2 are copied the second, n-3 the third, and so on, making this an \$O(n^2)\$ time algorithm.

Gloweye's approach is a constant factor worse, since *args[1:] in addition to constructing the list slice must "splat" the items into the argument list, which then gets unsplatted back to args tuple in the next call.  I should stress it is not that much worse; it is still only \$O(n^2)\$.

Both Gloweye's and the current recursive approach, passing p[1:] as the argument in the recursive call, can be corrected from \$O(n^2)\$ to \$O(n)\$ by replacing the list slicing with an iterator.  Since the recursive argument has changed from a list to an iterator, a second function would be needed to implement this change.

If tail call optimization was present, and the list was not being repeatedly sliced and recreated each step, such as by using an iterator to walk down the list of keys, then things would be better (as in \$O(n)\$).  Tail call optimization works by updating the arguments for the next call, and jumping to the top of the function, which turns the recursion into a simple loop.

So why not just use a loop?

One last optimization is to stop checking for the existence of the keys (or even a None default or sentinel value); these checks slow the loop down.  Instead, unconditionally lookup and retrieve the values.  Rely on Python's blazingly fast exception handling to efficiently recover from non-existent keys.

Also, use meaningful variable names.  d and p are far too obscure.

Finally, use """docstrings""" to document how to use the function.

def get_val_from_path(json_object, key_path):
    """
    Retrieve a value from a JSON object, using a key list to
    navigate through the JSON object tree.

    Parameters:
       json_object (JSON): An object return from json.loads()
       key_path (Iterable[str]): A list of keys forming the key path.

    Returns:
       The value found at the given key path, or `None` if
       any of the keys in the path is not found.
    """

    try:
        for key in key_path:
            json_object = json_object[key]

        return json_object

    except KeyError:
        return None

Optionally, use Gloweye's *args method signature for slightly friendlier calls, without the [] noise.

def get_val_from_path(json_object, *key_path):
    ...

get_val_from_path(d, "b", "2", "bb")  # --> "b2"


Programmatic text substitution across rows and columns in R I'm replaced character strings with numeric codes in R. I find myself doing a lot of copying and pasting, so there's probably a better solution with apply, sapply, or ddply that I'm missing.

Here's an example:

example <- data.frame(matrix(nrow = 20, ncol = 20))
example[,1]  <- 30:49
example[,10] <- 10:29
example[,2]  <- c("apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                  "apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                  "apple", "banana", "gum", "steak")
example[,3:9]  <- c("banana", "gum", "steak", "apple", "banana", "gum", "steak",
                    "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                    "banana", "gum", "steak", "apple", "apple", "apple")
example[,11:20]  <- c("apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                      "apple", "banana", "gum", "steak", "apple", "banana", "gum", "steak",
                      "apple", "banana", "gum", "steak")
names(example) <- c("ID", "food_day_1", "food_day_2", "food_day_3", "food_day_4",
                    "food_day_5", "food_day_6", "food_day_7", "food_day_8",
                    "Some_Numeric_Code", "otherfood_day_1", "otherfood_day_2",
                    "otherfood_day_3", "otherfood_day_4", "otherfood_day_5",
                    "otherfood_day_6", "otherfood_day_7", "otherfood_day_8",
                    "otherfood_day_9",  "otherfood_day_10")

which looks like:

> head(example)
  ID food_day_1 food_day_2 food_day_3 food_day_4 food_day_5 food_day_6 food_day_7 food_day_8 Some_Numeric_Code otherfood_day_1
1 30      apple     banana     banana     banana     banana     banana     banana     banana                10           apple
2 31     banana        gum        gum        gum        gum        gum        gum        gum                11          banana
3 32        gum      steak      steak      steak      steak      steak      steak      steak                12             gum
4 33      steak      apple      apple      apple      apple      apple      apple      apple                13           steak
5 34      apple     banana     banana     banana     banana     banana     banana     banana                14           apple
6 35     banana        gum        gum        gum        gum        gum        gum        gum                15          banana
  otherfood_day_2 otherfood_day_3 otherfood_day_4 otherfood_day_5 otherfood_day_6 otherfood_day_7 otherfood_day_8 otherfood_day_9
1           apple           apple           apple           apple           apple           apple           apple           apple
2          banana          banana          banana          banana          banana          banana          banana          banana
3             gum             gum             gum             gum             gum             gum             gum             gum
4           steak           steak           steak           steak           steak           steak           steak           steak
5           apple           apple           apple           apple           apple           apple           apple           apple
6          banana          banana          banana          banana          banana          banana          banana          banana
  otherfood_day_10
1            apple
2           banana
3              gum
4            steak
5            apple
6           banana

Here's what I did:

example$food_day_1[example$food_day_1 %in%
                            c("apple", "banana")] <- 1
example$food_day_1[example$food_day_1 %in%
                     c("gum", "steak")] <- 2

and so on.

What should I have done?

You could first create a mapping using a named vector:

map <- c("apple" = 1, "banana" = 1, "gum" = 2, "steak" = 2)

Then create a vector of all the variable names that need to be modified:

vars <- c(paste0("food_day_", 1:7),
          paste0("otherfood_day_", 1:10))

Then modify the data as follows:

example[vars] <- map[unlist(example[vars])]

(where unlist transforms the data.frame example[vars] into a single long vector.)

An interesting aspect of that approach, apart from its conciseness, is that it guarantees than the output columns become numeric. Whereas your approach, by making incremental changes to the columns, would preserve the original class of your columns, i.e. "character". Also note that foods that are not included in the map vector will be turned to NA since for example map["pineapple"] is NA.


Concept - DRY code vs. Readable code? I run into this often.  I have two functions very similar, that if I combine would be more DRY but if I didn't would be easier to read and make more sense.

In this case I have two implementations of fade, one using setInterval and one using setTimeout.

How do I not get stuck deciding between Dry vs. readability.  I hope this is not an opinion question that is not answerable.

   /*fade
    **  d:none
    **  n:uses setTimeout
    **
    */
    NS.prototype.fade = function (direction, max_time) {
        var statics = {},
            elements = this;
        statics.elapsed = 0;
        statics.granularity = 10;
        if (statics.timeout_id) {
            clearTimeout(statics.timeout_id);
        }
        (function next() {
            var kindex,
                opacity;
            statics.elapsed += statics.granularity;
            if (direction === 'up') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        opacity = statics.elapsed / max_time;
                        elements[kindex].style.opacity = opacity;
                    }
                }
            } else if (direction === 'down') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                    }
                }
            }
            if (statics.elapsed < max_time) {
                statics.timeout_id = setTimeout(next, statics.granularity);
            }
        }());
    };

    /*fadeL
    **  d:none
    **  n:(L)inear. Uses setInterval. Better for short animations.
    **
    */
    NS.prototype.fadeL = function (direction, max_time) {
        var statics = {},
            elements = this;
        statics.elapsed = 0;
        statics.granularity = 10;
        if (statics.timeout_id) {
            clearInterval(statics.timeout_id);
        }
        (function next() {
            var kindex,
                opacity;
            statics.elapsed += statics.granularity;
            if (!statics.timeout_id) {
                statics.timeout_id = setInterval(next, statics.granularity);
            }
            if (direction === 'up') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        opacity = statics.elapsed / max_time;
                        elements[kindex].style.opacity = opacity;
                    }
                }
            } else if (direction === 'down') {
                for (kindex in elements) {
                    if (elements.hasOwnProperty(kindex)) {
                        elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                    }
                }
            }
            if (statics.elapsed > max_time) {
                clearInterval(statics.timeout_id);
            }
        }());
    };

It's generally a good idea to remove duplication wherever possible. If you have two functions that are logically similar, but don't share code, you run the risk of code rot - updating one function and forgetting to apply similar changes to the other.

There are a few ways I would suggesting working around this without sacrificing too much readability.

Find common parts of each function and refactor them out into their
own sub-functions
Use higher-order functions to inject the unique
logic into a more generic base function

I hardly know Javascript at all, so I can't be too specific on how to handle this case, but it looks like you only have a very small amount of code that isn't shared.

if (statics.timeout_id) {
    clearTimeout(statics.timeout_id); // fade
    clearInterval(statics.timeout_id); // fadeL
}

// .. snip ..

// Added in fadeL
if (!statics.timeout_id) {
    statics.timeout_id = setInterval(next, statics.granularity);
}

// .. snip ..

if (statics.elapsed < max_time) { // fade
if (statics.elapsed > max_time) { // fadeL
    statics.timeout_id = setTimeout(next, statics.granularity); // fade
    clearInterval(statics.timeout_id); // fadeL
}

A really simple approach would be to make a base function that accepts a boolean value to differentiate between the slight changes in behavior:

NS.prototype.base_fade = function (direction, max_time, is_fade_l) {
    var statics = {},
        elements = this;
    statics.elapsed = 0;
    statics.granularity = 10;
    if (statics.timeout_id) {
        if (is_fade_l) {
            clearInterval(statics.timeout_id);
        } else {
            clearTimeout(statics.timeout_id);
        }
    }
    (function next() {
        var kindex,
            opacity;
        statics.elapsed += statics.granularity;
        if (is_fade_l && !statics.timeout_id) {
            statics.timeout_id = setInterval(next, statics.granularity);
        }
        if (direction === 'up') {
            for (kindex in elements) {
                if (elements.hasOwnProperty(kindex)) {
                    opacity = statics.elapsed / max_time;
                    elements[kindex].style.opacity = opacity;
                }
            }
        } else if (direction === 'down') {
            for (kindex in elements) {
                if (elements.hasOwnProperty(kindex)) {
                    elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
                }
            }
        }
        if (is_fade_l) {
            if (statics.elapsed > max_time) {
                clearInterval(statics.timeout_id);
            }
        } else {
            if (statics.elapsed < max_time) {
                statics.timeout_id = setTimeout(next, statics.granularity);
            }
        }
    }());
};

Then call that function from fade and fadeL providing the correct boolean. This way, at least, you have a guarantee that the code that is logically the same will stay the same. It also takes up less space in your codebase, and doesn't require all that much more parsing to understand it mentally.

You might be able to get more modular with this, and refactor some elements out into their own functions, but my own lack of knowledge of the language and the codebase means I'm not quite up to suggesting those changes. In general though, try to consolidate logically equivalent code wherever you can. It will make your life easier in the long run.


Compare List to Enum Where Contains Any I have a List that I want to compare to an Enum.
If a.Value is found in the Enum we return true.
I feel that I should be able to make this a single line, but have struggled.
private bool IsFound(IEnumerable<SomeAttribute> attributes)
{
    foreach (AttributesInMethod option in Enum.GetValues(typeof(AttributesInMethod)))
    {
        if (attributes.Any(a => option.GetDisplayNameENUM().Contains(a.Value)))
        {
            return true;
        }
    }
    return false;
}

I would suggest a two lines of code solution instead of one. :)
Let me show you first the solution then the explanation.
Solution
private static readonly Lazy<IEnumerable<string>> enumValues = new Lazy<IEnumerable<string>>(() => Enum.GetValues(typeof(AttributesInMethod)).Cast<AttributesInMethod>().Select(option => option.GetDisplayNameENUM()));

private bool IsFound(IEnumerable<SomeAttribute> attributes) => attributes.Select(att => att.Value).Any(enumValues.Value.Contains);

Explanation
Two methods instead of one

You have two kinds of data

A fairly static data, which could be changed only with code change

The mapped values of the enumeration

An absolutely dynamic data, which could change by each and every method call

The IsFound input parameter

You don't need to calculate each and every time the derived data from the enumeration. It should be calculated once and stored for long term.
Usage of Lazy
"It should be calculated once and stored for long term." > That's where the Lazy<T> type comes into play.
All you have to do is to provide a factory method (how to compute the derived data) and then the calculated information should be stored in a long-living variable. Lazy<T> gives us thread-safety so there is a guarantee that it will be calculated only once.
How to derive the data
Enum.GetValues(typeof(AttributesInMethod))
  .Cast<AttributesInMethod>()
  .Select(option => option.GetDisplayNameENUM())

GetValues returns an Array so you have to call Cast<T> to be able to use Linq operator on it.
Composing functions
For each input data check the existence of it in a predefined collection.

For each input data: attributes.Select(att => att.Value)
check the existence of it: .Any(... .Contains)
in a predefined collection: enumValues.Value

All you have to do to compose them to create a new higher level function.