Simplified method with multiple if-else I need to refactor some pice od method for drag-and-drop angular material.

Here is a working method in production, I need suggestion for CLEAN way to write this method.
I can't change var name and anything...

WHAT I TRY - I try to made small functions for every if/else, but in this case, I missing this drop event.
Like this example

checkIfHasRole() {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
    let lastAddedRole = event.container.data[event.previousIndex];
    if (lastAddedRole !== undefined) {
      this.userRoleCopy.push(lastAddedRole.valueOf());
    }

But, in this case, all event is missing

Here is the working method in production

drop(event: CdkDragDrop < string[] > ) {
  if (event.container.id === "delete") {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
    this.userRoleCopy = this.userRole.slice();
  } else {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      let lastRole = Object.values(
        event.previousContainer.data[event.previousIndex]
      );
      let parentRole = JSON.parse(JSON.stringify(event.container.data));

      let hasRole = parentRole.some(rola => {
        return rola.role === String(lastRole);
      });

      if (!hasRole) {
        transferArrayItem(
          event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex
        );
        let lastAddedRole = event.container.data[event.previousIndex];
        if (lastAddedRole !== undefined) {
          this.userRoleCopy.push(lastAddedRole.valueOf());
        }
        this.resetList();
      }
    }
  }
}

Yes, this could use a refactoring

I think your instincts are correct.  Those nested if-elses are hard to comprehend.  And the simplest way to break it apart is by creating helper functions.

Here I go through a step-by-step refactoring.  As with any refactoring, it involves a number of judgment calls.

Assumptions

First, I need to make clear one assumption, as not everything was spelled out in the question.  I'm assuming that the data properties of the event's container and previousContainer nodes, as well as your this object's userRole and userRoleCopy nodes consist of arrays of objects of the form {role: 'some string'}.

InitialCode

We start with code that looks like this:

    drop: function(event)  {
    if (event.container.id === "delete") {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveItemInArray(
          event.container.data,
          event.previousIndex,
          event.currentIndex
        );
      } else {
        let lastRole = Object.values(
          event.previousContainer.data[event.previousIndex]
        );

        let parentRole = JSON.parse(JSON.stringify(event.container.data));

        let hasRole = parentRole.some(rola => {
          return rola.role === String(lastRole);
        });

        if (!hasRole) {
          transferArrayItem(
            event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex
          );
          let lastAddedRole = event.container.data[event.previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push(lastAddedRole.valueOf());
          }
          this.resetList();
        }
      }
    }
  },

This code implies that there two helper functions available: transferArrayItem and moveItemInArray, and also that the this object also has the method resetList and the properties userRole and userRoleCopy.  I created dummies for these, with a wrapper I creatively (:-)) called "something".  You can see it in Step 0.  I of course do not expect that these helper functions do anything like your original.  The goal here is to simply fix things up without changing the behavior.

Removing unnecessary clone

My first step was to remove an unnecessary clone made in this:

          let parentRole = JSON.parse(JSON.stringify(event.container.data));

        let hasRole = parentRole.some(rola => {
          return rola.role === String(lastRole);
        });

There is no advantage to cloning that parent role.  The call to some does not alter the data, so we can just use the original.

Thus we can just write:

        let hasRole = event.container.data.some(rola => {
          return rola.role === String(lastRole);
        });

This minor change is available in Step 1, and you can see just by switching tabs that the output remains the same.

Tweaking the search

This code seems odd:

          let lastRole = Object.values(
          event.previousContainer.data[event.previousIndex]
        );

        let hasRole = event.container.data.some(rola => {
          return rola.role === String(lastRole);
        });

Perhaps my initial assumption was wrong.  But if you're trying to see if that data object has an element whose role property matches the specified value, I believe it's much simpler.  This is available in Step 2.

        let lastRole = event.previousContainer.data[event.previousIndex].role

        let hasRole = event.container.data.some(rola => {
          return rola.role === lastRole;
        });

Stop repeating event.x.y

Repeating event.something.somethingElse all over the place makes the code both harder to read and harder to change.  We can capture values like prevData and id from the event, and the rest of the code will be simpler.  There are several ways we could do this, but I find the nicest one is with destructuring parameters.  Using that, we can simplify the code to version Step 3:

  drop: function ({
    container, container: {id, data},
    previousContainer, previousContainer: {data: prevData},
    previousIndex,
    currentIndex
  }) {
    if (id === "delete") {
      transferArrayItem(prevData, data, previousIndex, currentIndex);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (previousContainer === container) {
        moveItemInArray(data, previousIndex, currentIndex);
      } else {
        let hasRole = pluck('role', data).includes(prevData[previousIndex].role)

        if (!hasRole) {
          transferArrayItem(prevData, data, previousIndex, currentIndex);
          let lastAddedRole = data[previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push({...lastAddedRole});
          }
          this.resetList();
        }
      }
    }
  }

Using helper functions

I'm still bothered by this bit:

          let lastRole = prevData[previousIndex].role

        let hasRole = data.some(rola => {
          return rola.role === lastRole;
        });

If we were working with ['role 1', 'role 2', 'role 3', ...], it would be very easy to search for our target role by just calling includes.  I happen to have handy a helper function that transforms [{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}...] into ['a', 'b', 'c'], a function called pluck.  In fact it's built into the Ramda REPL I've been using, but we could write our own as easily as this:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

and use it as in Step 4, like this:

        let hasRole = pluck('role', data).includes(prevData[previousIndex].role)

And now that we can extract helpers, we can do a substantial clean-up of our main function by adding a few helper methods to our object:

  deleteRole: function (prevData, data, previousIndex, currentIndex) {
    transferArrayItem(prevData, data, previousIndex, currentIndex);
    this.userRoleCopy = this.userRole.slice();
  },
  transferRole: function(prevData, data, previousIndex, currentIndex) {
    if (!pluck('role', data).includes(prevData[previousIndex].role)) {
      transferArrayItem(prevData, data, previousIndex, currentIndex);
      if (previousIndex in data) {
        this.userRoleCopy.push({...data[previousIndex]});
      }
      this.resetList();
    }
  },
  drop: function ({
    container, container: {id, data},
    previousContainer, previousContainer: {data: prevData},
    previousIndex,
    currentIndex
  }) {
    if (id === "delete") {
      this.deleteRole(prevData, data, previousIndex, currentIndex);
    } else {
      if (previousContainer === container) {
        moveItemInArray(data, previousIndex, currentIndex);
      } else {
        this.transferRole(prevData, data, previousIndex, currentIndex);
      }
    }
  }

(This is Step 5.)

Moving back to an event parameter

As we've proceeded, it seems as though the decision to destructure our event parameter is actually complicating things.  Certainly the signature of our main function is not as nice as we'd like.  If we undo that, now that we've abstracted things a bit, using these property accesses doesn't seem so ugly.

And this would let us move some of the helpers from object methods to plain functions, which are often more tractable.  There is a problem with the this property though, which would necessitate moving this line back into the main function:

   this.userRoleCopy = this.userRole.slice();

With this the code now could look like Step 6:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

const transferEvent = (event) =>
  transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);

const moveEvent = (event) =>
  moveItemInArray(event.container.data, event.previousIndex, event.currentIndex)

const something = (userRole) => ({
  // ...
  transferRole: function(event) {
    if (!pluck('role', event.container.data).includes(
      event.previousContainer.data[event.previousIndex].role)
     ) {
      transferEvent(event);
      if (event.previousIndex in event.container.data) {
        this.userRoleCopy.push({...event.container.data[event.previousIndex]});
      }
      this.resetList();
    }
  },
  drop: function (event) {
    if (event.container.id === "delete") {
      transferEvent(event);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveEvent(event);
      } else {
        this.transferRole(event);
      }
    }
  }
})

Making plain functions out of methods

The reason we haven't been able to move transferRole into a plain function as well is that it makes reference to this.  So long as we need this, we're stuck with methods.  But it's quite easy to make it a function parameter.  When we do so we end up with a final cleaner codebase, Step 7:

const pluck = (prop) => (xs) => xs.map(x => x[prop])

const transferEvent = (event) =>
  transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);

const moveEvent = (event) =>
  moveItemInArray(event.container.data, event.previousIndex, event.currentIndex)

const transferRole = (something, event) => {
  if (!pluck('role', event.container.data).includes(
    event.previousContainer.data[event.previousIndex].role)
  ) {
    transferEvent(event);
    if (event.previousIndex in event.container.data) {
      something.userRoleCopy.push({...event.container.data[event.previousIndex]});
    }
    something.resetList();
  }
};

const something = (userRole) => ({tion: 'resetList'}),
  // ...
  drop: function (event) {
    if (event.container.id === "delete") {
      transferEvent(event);
      this.userRoleCopy = this.userRole.slice();
    } else {
      if (event.previousContainer === event.container) {
        moveEvent(event);
      } else {
        transferRole(this, event);
      }
    }
  },
})

Lessons Learned

I was going to write a few paragraphs about choices made during this refactoring, and about alternatives that might apply.  But I'm tired now, and want to finish up.  So I'll just say although there are many good reasons to refactor code -- including performance, compliance with conventions and standards, and others -- the most important reason is to make your code easier to read and to modify.

I believe the final version makes the branching much more clear.  I believe it is easier to read.  So I believe we have improved this code.

Note: I'm seeing after writing all this up that we folded two separate changes into Step 5.  As well as pulling out helper functions, that step changed this:

          let lastAddedRole = data[previousIndex];
          if (lastAddedRole !== undefined) {
            this.userRoleCopy.push({...lastAddedRole});
          }

to this:

      if (previousIndex in data) {
        this.userRoleCopy.push({...data[previousIndex]});
      }

It does the same thing, but without introducing a temporary variable.  To me that's usually an improvement.


Number of occurrences of each different word in a line of text I am looking for feedback on a solution to the following problem posed from a book that I'm working through (Java: How To Program 9th Edition):

  Write an application that reads a line of text and prints a table indicating the number of occurrences of each different word in the text. The application should include the words in the table in the same order in which they appear in the text. For example, the lines

  To be, or not to be: that is the question:
  Whether 'tis nobler in the mind to suffer

  contain the word “to” three times, the word “be” two times, the word “or” once, etc.

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;

public class TextAnalysisC {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Scanner sc = new Scanner( System.in );
    System.out.println( "Please enter a line of text" );
    String userInput = sc.nextLine();

    userInput = userInput.toLowerCase();

    userInput = userInput.replaceAll( "\\W", " " );     // strip out any non words.
    userInput = userInput.replaceAll( "  ", " " );      // strip out any double spaces
                                                        //   created from stripping out non words
                                                        //   in the first place!
    String[] tokens = userInput.split( " " );
    System.out.println( userInput );

    ArrayList< String > items = new ArrayList< String >();

    items.addAll( Arrays.asList( tokens ) );

    int count = 0;

    for( int i = 0; i < items.size(); i++ )
    {
        System.out.printf( "%s: ", items.get( i ) );
        for( int j = 0; j < items.size(); j++ )
        {
            if( items.get( i ).equals( items.get( j ) ) )
                count++;
            if( items.get( i ).equals( items.get( j ) ) && count > 1 )
                items.remove( j );                      // after having counted at least
        }                                               // one, remove duplicates from List
        System.out.printf( "%d\n", count );
        count = 0;
    }
}
}

Can this be simplified?  Is this easy to understand?  What should I improve?

I regret to report that I have been remiss on the current scope of my knowledge as I work through my textbook (Java: 9th Edition). Solutions should be within the limits of what I have covered so far, that being:

Introduction to Computers and Java
Introduction to Java Applications
Introduction to Classes, Objects, Methods and Strings
Control Statements: Part 1
Control Statements: Part 2
Methods: A Deeper Look
Arrays and ArrayLists
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
Exception Handling: A Deeper Look
GUI Components: Part 1 (Swing)
Strings, Characters and Regular Expressions

The easiest way would be to use a LinkedHashMap<String,AtomicInteger>, adding the words in order.

LinkedHashMap is a Map, so duplicate keys can easily be detected. AtomicInteger will allow incrementing the value without having to replace the value in the Map. Yet AtomicInteger isn't exactly intended to be used as a dumb counter, making your own Counter class is also a good option, as long as it has an increment() and a get() method, it'll make your interaction with the Map a lot smoother.

You can use String.split() to break up the input String in words.

Quick pseudo code:

split input String into words
loop the words
   if word not in map
      add word as key, with new counter
   get counter for word and increment
loop map entries
   print word and number of occurrences

Edit

Given the scope of your knowledge, I'll make a suggestion that only uses what you should know already. The idea is to replace the Map by an ArrayList of words and a matching array of int to hold the counts.

split input String into words
initialize an int[] array with the size equal to the number of words // max needed capacity
initialize an ArrayList of Strings
loop the words
   determine index of the word in ArrayList.
   if word not in ArrayList
      add word to ArrayList
   increment int in array at matching index as the word in the ArrayList
loop ArrayList
   print word and number of occurrences (from same index in array)


Printing all strings in a Boggle board I am trying to print all the strings given in a N x N Boggle board. Its basically a N x N scrabble-like board where words can be made from a position - horizontally, vertically and diagonally.

Here is my naive implementation. Is this correct? Any hints on optimizations? Any other useful links?

public class BoggleSolver {

    private void solve(String prefix, int i, int j, char[][] Board, boolean[][] marker, int N)
    {
        if ((i < 0) || (j < 0) || (i >= N) || (j >= N)) return;

        if (marker[i][j] == true) return;

        String s = prefix + Character.toString(Board[i][j]);

        // TODO Fictional dictionary that can tell us if
        // a string is a legal word
        if (dict.HasWord(s)) System.out.println(s);

        // Mark current index and traverse horizontal,vertical
        // and diagonal
        marker[i][j] = true;

        solve(s, i, j + 1, Board, marker, N);
        solve(s, i + 1, j, Board, marker, N);
        solve(s, i + 1, j + 1, Board, marker, N);
    }

    public void solve(char[][] Board, int N)
    {
        boolean[][] marker = new boolean[N][N];

        solve("", 0, 0, Board, marker, N);
    }
    public static void main(String[] args) {

        // TODO make board and call solve(board, N)
    }

}

I wouldn't consider that a Boggle solver, as you only consider words that start at [0, 0] and progress east, south, or southeast.  (With coordinates that are always nondecreasing, you need not have bothered using marker to prevent backtracking.)

A complete search will probably take an extremely long time.  You should use a dictionary that can check whether there are any words that begin with some prefix, so that you can prune fruitless search paths.  Use a trie data structure, or possibly a TreeSet<String>.

Board, N, and HasWord(…) all have improper capitalization.  It doesn't make sense to require N to be passed in explicitly, since it should be detectable from the board's dimensions.

Appending a character to a string can be simply written as prefix + board[i][j].

I would recommend redesigning the class with a more versatile interface, because printing the results to System.out limits reusability.

public interface BoggleSolutionHandler {
    public void foundWord(String word);
}

public class BoggleSolver {
    public static void solve(char[][] board, BoggleSolutionHandler callback, NavigableSet<String> dictionary) {
        …
    }
}

An iterator would be even nicer to use, but probably harder to implement since you can't take advantage of recursion:

public class BoggleSolver implements Iterator<String> {
    public class BoggleSolver(char[][] board, NavigableSet<String> dictionary) {
        …
    }

    @Override
    public boolean hasNext() {
        …
    }

    @Override
    public String next() {
        …
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}


Date Detection Regex in Python I worked on a problem from Automate the Boring Stuff Chapter 7:

Write a regular expression that can detect dates in the DD/MM/YYYY
format. Assume that the days range from 01 to 31, the months range
from 01 to 12, and the years range from 1000 to 2999. Note that if the
day or month is a single digit, it’ll have a leading zero.
The regular expression doesn’t have to detect correct days for each
month or for leap years; it will accept nonexistent dates like
31/02/2020 or 31/04/2021. Then store these strings into variables
named month, day, and year, and write additional code that can detect
if it is a valid date. April, June, September, and November have 30
days, February has 28 days, and the rest of the months have 31 days.
February has 29 days in leap years. Leap years are every year evenly
divisible by 4, except for years evenly divisible by 100, unless the
year is also evenly divisible by 400. Note how this calculation makes
it impossible to make a reasonably sized regular expression that can
detect a valid date.

Here's my code:
#Program that detects dates in text and copies and prints them

import pyperclip, re
#DD/MM/YEAR format
dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')
#text = str(pyperclip.paste())
text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'

matches = []
for groups in dateRegex.findall(text):
    day = groups[0]
    month = groups[1]
    year = groups[2]

    #convert to int for comparisons
    dayNum = int(day)
    monthNum = int(month)
    yearNum = int(year)

    #check if date and month values are valid
    if dayNum <= 31 and monthNum > 0 and monthNum <= 12:
        #months with 30 days
        if month in ('04', '06', '09', '11'):
            if not (dayNum > 0 and dayNum <= 30):
                continue
        #February only
        if month == '02':
            #February doesn't have more than 29 days
            if dayNum > 29:
                continue
            if yearNum % 4 == 0:
                #leap years have 29 days in February
                if yearNum % 100 == 0 and yearNum % 400 != 0:
                    #not a leap year even if divisible by 4
                    if dayNum > 28:
                        continue
            else:
                if dayNum > 28:
                    continue
        #all other months have up to 31 days
        if month not in ('02', '04', '06', '09', '11'):
            if dayNum <= 0 and dayNum > 31:
                continue
    else:
        continue
    date = '/'.join([groups[0],groups[1],groups[2]])
    matches.append(date)

if len(matches) > 0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No dates found.')

I've tested it out with various different date strings and it works as far as I can tell. I wanted to know about better ways of doing this though. As a beginner and an amateur, I understand there might be methods of writing the above code that are better and I don't mind being guided in the right direction and learning more about them. What is a better way of doing all of the above without using so many if statements?

You can import and use datetime rather than validating date yourself.
>>> import datetime
>>> datetime.date(2020, 9, 9)
datetime.date(2020, 9, 9)
>>> datetime.date(1990, 2, 29)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

As such we can just change all your checks to a call to datetime.date in a try except block.
for groups in dateRegex.findall(text):
    try:
        datetime.date(int(groups[2]), int(groups[1]), int(groups[0]))
        matches.append('/'.join(groups))
    except ValueError:
        pass

Rather than using '/'.join(groups) if we use finditer we can just use groups[0].
And we'd need to increment the other indexes by one too.
for groups in dateRegex.finditer(text):
    try:
        datetime.date(int(groups[3]), int(groups[2]), int(groups[1]))
        matches.append(groups[0])
    except ValueError:
        pass

We can also change the creation of datetime.date to use a comprehension.
We need to use * to map all the values of the built list to arguments to the function.
for group in dateRegex.finditer(text):
    try:
        datetime.date(*(int(part) for part in group.groups()[::-1]))
        yield group[0]
    except ValueError:
        pass

You should also use an if __name__ == '__main__': guard to prevent your code from running on import.
And I'd define more functions.
import pyperclip
import datetime
import re

DATE_MATCHER = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')

def find_dates(text):
    for group in DATE_MATCHER.finditer(text):
        try:
            datetime.date(*(int(part) for part in group.groups()[::-1]))
            yield group[0]
        except ValueError:
            pass

def main():
    text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'
    dates = list(find_dates(text))
    if not dates:
        print('No dates found.')
    else:
        pyperclip.copy('\n'.join(matches))
        print('Copied to clipboard:')
        print('\n'.join(dates))

if __name__ == "__main__":
    main()


Concise and exception-prone method for running method on component I have a list of Components. When an actor is connected, I want to run onActorConnected on each component. However, if a component's onActorConnected method throws an exception for whatever reason, this cannot affect other components' execution of that method.
Here's a minimized extract of my code:
import static java.lang.String.format;

public class Match {
    private final Set<Actor> actors = ...;
    private final List<MatchComponent> components = ...;

    public void connectActor(@NotNull Actor actor) {
        if (actors.contains(actor))
            throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));

        actors.add(actor);

        // This is hard to read!
        // But I will be doing this in a lot of places, so I want to keep in short.
        components.forEach(c-> runOrLogException(() -> c.onActorConnect(actor), c.getName(), "onActorConnect"));
    }

    // The same pattern will be used in `disconnectActor` and other similar methods.

    private void runOrLogException(@NotNull Runnable runnable, @NotNull String instanceName, @NotNull String methodName) {
        try {
            runnable.run();
        } catch (Exception e) {
            logger.log(Level.SEVERE, format("'%s' on '%s' in '%s' threw an exception.", methodName, instanceName, this.getName()), e);
        }
    }
}

My question primarily is about whether this is a good way to do it? I fear I might be missing some way of using Java's lambdas to make this cleaner.
Bonus question is whether it's considered good practice to throw an exception if an "actor" is already connected. I considered just returning false if this is the case, but I do not ever expect myself to call this method if an actor is already connected. If that happens, something has gone wrong somewhere. I instead provide an isActorConnected method that the caller can use to explicitly handle such a case.

Are there certain exceptions you can anticipate for onActorConnected?  Let's make an encompassing checked exception ActorUnconnectableException, though this would need to be be made more finegrained for particular connectivity issues:
class ActorUnconnectableException extends Exception {
    ActorUnconnectableException(Actor actor, MatchComponent component) {
        super(
            String.format("actor: %s cannot connect to component: %s", actor.getName(), component.getName())
        );
    }
}

And declare onActorConnect within MatchComponent like this:
void onActorConnect(Actor actor) throws ActorUnconnectableException {
    ...
}

The reason I advocate for a checked exception here is because it sounds like the it is hard to guarantee that an Actor is connectable without attempting to connect it. If we were able to verify that an Actor is connectable beforehand, an unchecked exception would be better suited here.
For something like a string that we're trying to parse as a number, let's say this parsable string is typed in our frontend. We can enforce through whatever frontend framework that this string contains only digits. That's why Integer::parseInt throws an unchecked exception, it expects that the validation is done before hand.
Another thing that can be improved is this:
if (actors.contains(actor))
     throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));

actors.add(actor);

Apart from adding braces for the if, we can utilize the fact that actors::add returns true if actor is not contained, otherwise false, like this:
boolean actorAdded = actors.add(actor);

if (!actorAdded) {
    throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));
}

This should remain an unchecked exception cause the calling code should be able to determine whether it already added an Actor equal to actor beforehand.
The rest of connectActor ends up looking like this:
var unconnectableComponents = new ArrayList<MatchComponent>();

for (MatchComponent component : components) {
    try {
        component.onActorConnect(actor);
    }
    catch (ActorUnconnectableException e) {
        unconnectableComponents.add(component);
    }
}

// Log `unconnectableComponents` or create new exception to report their collective failure.

This definitely ends up looking verbose, but the idea is that we want things outside of the calling code's control (like whether can actor is in fact connectable, which sounds like it can't be decided beforehand) to be checked at compile time.


Xerox Parc MVC implementation I've been trying to understand the original MVC implementation (the Xerox Parc's one). I'm sure it has flaws, but it's simple code to practice/learn the original MVC.

Working example

View (index.html):

<!DOCTYPE html>

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

Birth Date:

Age:

Model (model-person.js):

var ModelPerson = (function () {
    'use strict';

    var ModelPerson = function (name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getName = function () {
        return this.name;
    };

    ModelPerson.prototype.setName = function (name) {
        this.name = name;
    };

    ModelPerson.prototype.getBirthDate = function () {
        return this.birthDate;
    };

    ModelPerson.prototype.setBirthDate = function (birthDate) {
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getAge = function () {
        var dateDifference = new Date(Date.now() - this.birthDate.getTime());
        return Math.abs(dateDifference.getFullYear() - 1970);
    };

    return ModelPerson;
}());

Controller (controller-person.js):

var ControllerPerson = (function () {
    'use strict';
    var controller;

    var ControllerPerson = function (modelPerson) {
        controller = this;
        controller.modelPerson = modelPerson;
    };

    ControllerPerson.prototype.initialize = function () {
        document.getElementById('person-name').addEventListener('blur', function () {
            controller.modelPerson.setName(this.textContent);
            controller.updateView();
        });

        document.getElementById('person-birth-date').addEventListener('blur', function () {
            controller.modelPerson.setBirthDate(new Date(this.textContent));
            controller.updateView();
        });

        controller.updateView();
    };

    ControllerPerson.prototype.updateView = function () {
        document.getElementById('person-name').textContent = this.modelPerson.getName();
        document.getElementById('person-birth-date').textContent = this.modelPerson.getBirthDate();
        document.getElementById('person-age').textContent = this.modelPerson.getAge();
        document.getElementById('json-model-representation').textContent = JSON.stringify(controller.modelPerson);
    };

    return ControllerPerson;
}());

Instantiation (main.js):

(function () {
    'use strict';
    var modelPerson = new ModelPerson('John Doe', new Date('1987-09-11')),
        controllerPerson = new ControllerPerson(modelPerson);

    controllerPerson.initialize(); }());

My model is the mental object model. My controller handles events and update the Model. The view is "dumb" and just presents the content.

Do you think it's like the original MVC? What's wrong? What am I missing?

I am assuming you are used to getters/setters because you are experienced in another language, please don't do this. Performance matters, there is no good reason to download all those functions for no good reason, model-person.js should be

var ModelPerson = (function () {
    'use strict';

    var ModelPerson = function (name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getAge = function () {
        var dateDifference = new Date(Date.now() - this.birthDate.getTime());
        return Math.abs(dateDifference.getFullYear() - 1970);
    };

    return ModelPerson;
}());

Also, updateView does not belong in the controller, it should be part of your view class which should contain all view related logic.

Furthermore, I think in the original pattern, the model actually updates the view, meaning that the controller should not be done the one doing controller.updateView();, that should be handled implicitly by controller.modelPerson.setName(this.textContent);

Personally, I like your approach better, I think the controller should decide when the UI gets updated.

Finally, there is the matter of the element id's like person-name, you use them more than once so you should use a constant. Now the question is, should this constant be defined in Model, View or Controller ? I personally define these id's in the View class and then the controller asks the View what the element is, so that it can attach the listener. I dont think the MVC pattern goes into this detail, so it's up to you.

Other than that, your code is very readable and easy to follow.


Checking if a sequence is almost strictly increasing The question

Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

My java solution
boolean almostIncreasingSequence(int[] sequence) {

    Integer[] arr = new Integer[sequence.length];

    for(int ctr = 0; ctr < sequence.length; ctr++) {
        arr[ctr] = Integer.valueOf(sequence[ctr]); // returns Integer value
    }
    System.out.println("Integer :: " + arr);
    List<Integer> al = new ArrayList<Integer>();

    // adding elements of array to arrayList.
    Collections.addAll(al, arr);
    System.out.println("list :: " + al);
    int save, flag = 0;
    for(int i=0; i<al.size(); i++) {
        save = al.get(i);
        al.remove(i);
        if(al.size()==1) return true;
        for(int j=0; j<al.size()-1; j++) {
            if(al.get(j+1) > al.get(j)) {
                flag = 0;
                continue;
            }
            else {
                flag = 1;
                break;
            }
        }
        if(flag == 0) {
            return true;
        }
        al.add(i,save);
    }

    if(flag == 1)
        return false;
    return true;
}

Here, I have created 2 for loops because in the first loop I'm generating the list where each index will be removed and in the second loop I'm iterating over the new list which has removed the element.
like sample array is {1,2,4,3} then in the first loop I'm creating an array which will be {2,4,3},{1,4,3},{1,2,3} and {1,2,4}. In the second loop I'm iterating over all these 4 arrays to compare each element.
The problem
For some of the test cases, it shows that it takes more than 3 seconds to execute this. But, I'm not sure where can I make a change to execute it faster. I don't have access to the test case.

You are repeating a lot of work.

For example, let's take a look at the sequence [1,2,3,4,5].

Your code does the following:
- copy it to a list
- remove "1" and check if {2,3,4,5} is sorted
- remove "2" and check if {1,3,4,5} is sorted
- remove "3" and check if {1,2,4,5} is sorted
- remove "4" and check if {1,2,3,5} is sorted
- remove "5" and check if {1,2,3,4} is sorted

Instead, let's go over the entire sequence once and do something special on the first item that is smaller than the previous one.

At some point into the loop we see the following where sequence[i-1] > sequence[i]

  {done part, a, sequence[i-1], sequence[i], c, remainder}

The whole start of the sequence up to sequence[i-1] is strictly increasing (checked in earlier iterations of the loop). So what do we still need to check here to give a meaningful answer?

Given that sequence[i-1]>sequence[i] either one of those needs to be removed. So we have 2 cases:

remove sequence[i-1] -> check if {a, sequence[i], c, remainder} is strictly increasing
remove sequence[i] -> check if {a, sequence[i-1], c, remainder} is strictly increasing

Note that in both cases we want to check if the remainder is strictly ascending. So the main loop will look something like this:

for(int i = 1; i < sequence.length; i++){
    if (sequence[i - 1] > sequence[i]) {
        // {..., a, sequence[i-1], sequence[i], c, remainder}
        //check if remainder is sorted
        for(int j = i+1; j < sequence.length; j++){
            if (sequence[j - 1] > sequence[j]) {
                return false;
            }
        }
        int a = sequence[i - 2];
        int c = sequence[i + 1];
        //remove i-1
        if (a < sequence[i] && sequence[i] < c) {
            return true;
        }
        //remove i
        if (a < sequence[i - 1] && sequence[i - 1] < c) {
            return true;
        }
        //neither removing i-1 or i fixed the strictly increasing rule
        return false;
    }
}
//entire list is strictly increasing
return true;

There's still some edge cases that will cause trouble. This loop as it is now will throw an ArrayIndexOutOfBoundsException because we're accessing from sequence[i-2] up to sequence[i+1].

Let's handle those cases before the loop to keep things as simple as possible and reduce the bounds for the loop:

//trivial case with up to 2 items
if(sequence.length < 3){
    return true;
}
//edge case first 3 items are descending
if(sequence[0]>sequence[1]
        &&sequence[1]>sequence[2]) {
    return false;
}
//edge case last 3 items are descending
int last = sequence.length-1;
if(sequence[last-2]>sequence[last-1]
        &&sequence[last-1]>sequence[last]) {
    return false;
}
for(int i = 2; i < sequence.length-1; i++){ //skip first 2 and last item
    ...

With this we're no longer checking the same items over and over again and we no longer copy all the items into a list which should give you a major improvement in speed.

DISCLAIMER I have not tested this code. It's possible it contains typo's or other edge cases. Be sure to fully understand it instead of blindly copy-pasting.


Google Apps Script shifting columns containing specified substring - using array functions The link is to the example sheet of what I have done

This code solves the problem of shifting large amounts of specific data in a google spreadsheet. The data is shifted to the right by one column, but only the data containing the specified substring (in this case, "PO"). It is intended to shift the leftmost row over by one column.

https://docs.google.com/spreadsheets/d/12w4rGArGi1I1wlpm5yJJtT5AAlMM4LcZC31_DpP6jZQ/edit?usp=sharing

I shifted the rows that contain "PO" in my data selection. (see shift function)

It was suggested to me that I use array functions to made the code better, but I am honestly not sure how to refactor it. I am still very much a beginner.

I'm guessing I can more easily do this instead of trying to reassign array index values.

Here is my current script:

function shift() {
  try{
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var as = ss.getActiveSheet();
    var ar = as.getActiveRange();
    var vals = ar.getValues();
    var r; //variable for rows

    // in this first section, I've already stored the active range (my selection) into a two dimensional array.

    for (r = 0; r < vals.length; r++){                                           // for each row, up to the last row (iterate over all rows from top to bottom)
      if((vals[r][0].indexOf("PO") != -1)||(vals[r][0].indexOf("P0") != -1)){    // if first column in each row contains "PO"
        var c; // variable for columns
        var cols = []; // array to store all data temporarily (will be uses to set new values later)
        for (c = 0; c < vals[r].length; c++){                                   // then iterate over each column(cell) in the row
          if(c == 0){                                                           // if it is the first row,
            cols[c+1] = vals[r][c];                                             // assign second index of the array with the PO value (to simulate a shift)
            cols[c] = "";                                                       // assign the first index of the array a blank string
          }
          else{                                                                 // if it is not the first row
            cols[c+1] = vals[r][c];                                             // assign each additional column value to the next index (+1) of the array
          }
        }
        for (c = 0; c < vals[r].length; c++){                                   // once the array is finished, loop through the columns again foreach row
          vals[r][c] = cols[c];                                                 // this time, assigning the new values to the corresponding array indices
        }
      }
    }
    ar.setValues(vals);                                                         // now, set the values that you reassinged to the array
  }
  catch(err){
    SpreadsheetApp.getUi().alert(err);
  }
}

Just as a general note, you could avoid the temporary array by copying the array from the end. I would also use a temporary variable for simplicity:

for (r = 0; r < vals.length; r++) {
  var row = vals[r], first=row[0];
  if(first.indexOf("PO") != -1)||first.indexOf("P0") != -1)) {
    for (var c = row.length; c > 0' c--) {
      row[c] = row[c-1];
    }
    row[0] = "";
  }
}

However in this case you can let JavaScript do all the work:

  if(first.indexOf("PO") != -1)||first.indexOf("P0") != -1)) {
    row.splice(0, 0, "");
  }

Also, assuming you only need to support recent browsers, I would look at using methods like forEach and includes.


Scala fraction addition This just adds fractions. For example, if we have a text file with:

1/3
1/2

It will print:

5/6

I would love to hear some remarks on how I can make this more Scala-like.

class Fraction(c: BigInt, d: BigInt) {
  val divisor = c.gcd(d);
  def counter = c / divisor;
  def denominator = d / divisor;

  def lcm(a: BigInt, b: BigInt):BigInt = (a * b).abs / a.gcd(b)

  def + (f: Fraction): Fraction = {
    val lcmVal = lcm(f.denominator, denominator)
    val apply = (count: BigInt, div: BigInt) => lcmVal / div * count
    new Fraction(
      apply(f.counter, f.denominator)
        + apply(counter, denominator)
      , lcmVal)
  }

  override def toString(): String = {
    return String.format("%s / %s", counter, denominator)
  }
}

object AddingFractions {

  def sumFractions(fractions: Array[Fraction]): Fraction = {
    val sum = fractions(0) + fractions(1)
    if (fractions.length > 2) {
      return sumFractions(sum +: fractions.slice(2, fractions.length))
    }
    sum
  }

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.fromFile(args(0)).getLines()
    val linesArray = lines.toArray

    val fractions = linesArray
      .map((s: String) => s.split("/"))
      .map((ar: Array[String]) => Array(Integer.parseInt(ar(0)), Integer.parseInt(ar(1))))
      .map((iar: Array[Int]) => new Fraction(iar(0), iar(1)))

    println(sumFractions(fractions))
  }
}

Basic problems with input

Your code will blow up if there are fewer than two fractions in the input.  Even @janos's solution (which can cope with only one fraction) fails if there are no fractions in the input.  Is that reasonable, especially given that the sum of no numbers at all is 0?

Your code also fails on any badly formatted input but there's enough else to talk about to leave that for another day.

Style

apply method

It's common practice in Scala, with types like your Fraction, to add an apply method to dispense with the need for new.  It can be added directly to the class or in a companion object.

object Fraction {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)
}

With the apply method added, Fraction(1,2) will return Fraction = 1 / 2 with no need for new.  It's a minor convenience, in the case of your simple class, but feels more natural.

Note: It would also be very useful to add an unapply method, for pattern matching.  Ask if you need details.

Implicit conversions

This is not necessary for the scope of your current, simple code but if you intend to do more with your Fraction, it may be useful to be able to add fractions and integers and get fractions as a result).  If you add one simple method to your class...

  def + (i: Int): Fraction = this + (new Fraction(i, 1))

then Fraction(1, 2) + 1 will return Fraction = 1 / 2.  However, 1 + Fraction(1, 2) will not work, because Int has no + method which takes a Fraction parameter.  This can be fixed by creating an Int-wrapping class which does have such a method and creating an implicit conversion which can turn an Int into such a class.  To make this magic optional rather than an unexpected surprise, put them into a companion object, thus:

object Fraction {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)
  // Implicit classes added in Scala 2.10
  implicit class FractionalInt(i: Int) {
    def + (that: Fraction) = that + i
  }
}

Now anybody using your Fraction code can choose to do import Fraction._, after which 0 + Fraction(1,2) will return Fraction = 1 / 2

Pattern matching in explicit recursion

As Janos said, the best solution is a higher-order function but if you are going to do explicit recursion, pattern matching is often much more expressive and clean, as in

def sumFractions(fractions: Array[Fraction]): Fraction =
  fractions match {
    Array() => new Fraction(0, 1)
    Array(x) => x
    Array(x, y) => x + y
    Array(x, y, _*) => sumFractions((x + y) +: (fractions drop 2))
  }

Note that

This copes with 0 or 1 entries
I could have left the third match out and it would still work

This style is more expressive and less fragile than your imperative implementation.

Make functions generic

Later I'm going to argue that arrays are no benefit at all anywhere in your current code, but my point now is that sumFractions should not dictate that it be passed an array. janos's solution only really requires a Seq - and so does your explicitly recursive solution, as discussed elsewhere in this answer.

Janos's solution could be rewritten as

def sumFractions(fractions: Seq[Fraction]) : Fraction =
  fractions.reduceLeft(_ + _)

and nothing would break, because in Scala Array implements the Seq trait.  Any Seq-derived type will have reduceLeft, so there is no reason for this function to demand one.  That gives you much more freedom in the rest of your code.  If you decide to switch from arrays to sets or lists, this function does not then have to be rewritten.

Note: my pattern-matching variant on your explicitly recursive function can also be rewritten to be more generic.  Can add an example if you want.

sumFractions is redundant

Your class deals with a particular representation of rational numbers.  I've already mentioned that it might be useful (via implicits) to make them work with integers.  However, if you go further and do the work to make Fraction part of Scala's Numeric type class, then pretty much anything you can do with a sequence of Int (or Double or other numeric types) can be done with a sequence of Fraction.  If you do that work, you can simply replace sumFractions with fractions.sum.  Here's one way how

/* This could be placed inside the companion object
implicit object NumericFraction extends Numeric[Fraction] {
  def plus(x: Fraction, y: Fraction): Fraction = x + y
  /* Actually, there's a whole extra bunch of abstract
   * methods that you have to implement - see later
   */
}

Once this is done, assuming fractions is a sequence of Fractions (Seq[Fraction], List[Fraction], Array[Fraction] or whatever) then you can throw away sumFractions and simply use

fractions.sum

But there's more.  To actually make Fraction numeric, you have to implement the rest of the type class.  Here's an extended version of the companion object, which does just that, without adding any more methods to your original class:

object Fraction extends Numeric[Fraction] {
  def apply(c: BigInt, d: BigInt) = new Fraction(c, d)

  implicit object NumericFraction extends Numeric[Fraction] {
    // Required by scala.math.Numeric
    def fromInt(x: Int): Fraction = Fraction(x, 1)
    def minus(x: Fraction, y: Fraction): Fraction = x + negate(y)
    def negate(x: Fraction) = Fraction( - x.counter, x.denominator)
    def plus(x: Fraction, y: Fraction): Fraction = x + y
    def times(x: Fraction, y: Fraction): Fraction =
      Fraction(x.counter * y.counter, x.denominator * y.denominator)
    def toDouble(x: Fraction): Double =
      x.counter.toDouble / x.denominator.toDouble
    def toFloat(x: Fraction): Float =
      x.counter.toFloat / x.denominator.toFloat
    def toInt(x: Fraction): Int = (x.counter / x.denominator).toInt
    def toLong(x: Fraction): Long = (x.counter / x.denominator).toLong
    // Required by scala.math.Ordering
    def compare(x: Fraction, y: Fraction) =
      (x.counter * y.denominator) compare (y.counter * x.denominator)
  }
}

Once that is done, you get to do all this:

scala> val fractions = List(Fraction(1,2), Fraction(1,3), Fraction(1,4))
fractions: List[Fraction] = List(1 / 2, 1 / 3, 1 / 4)

scala> fractions.sum
res1: Fraction = 13 / 12

scala> fractions.product
res2: Fraction = 1 / 24

scala> fractions.min
res3: Fraction = 1 / 4

scala> fractions.max
res4: Fraction = 1 / 2

scala> fractions.sorted
res5: List[Fraction] = List(1 / 4, 1 / 3, 1 / 2)

I did this using a companion object, which is easier because it doesn't require modification of the original class. This is the conventional way in which type classes are used.  Although I have been able to implement all the Numeric abstract methods using only your + method, it would be useful to add native /, *, - methods to Factor and rewrite the implicit type class instance to call them.

The important point is that what I have shown you is really very little extra work and immediately gives you the use of many built in functions from the collections api.

Arrays are not appropriate here

Did you use arrays simply because you aren't very familiar with pattern matching but understand pulling elements from an array?  There really is almost no benefit at all to using arrays here.  Arrays only offer an advantage where random access is needed to a collection of fixed size.  Your use of the collections is entirely sequential

sumFractions

As covered above, sumFractions need specify nothing more than Seq[Fraction as input.  The reduceLeft solution will use the appropriate, optimised implementation of whichever sequence you pass in.  Even with explicit recursion (example provided on demand), the solution can be generalised to Seq without demanding by default all the copying required by Array.

Even if you choose to optimise the file input and parsing step with parallel collections, sumFractions need not know.

LinesArray not necessary

Any sequence (and other collections) can be mapped over.
As explained, sumFractions does not need an array.  Even if it did, you could convert to an array at the end of input processing.  Also, consider that some of the lines may be invalid.  You may choose either to halt at the first error or discard invalid lines; in either case, converting to an array first would be a waste of effort.

Parsing

Ah, now, split does offer a simple way to parse the input lines.  If you want to handle only perfectly formatted lines (not even permitting whitespace) and halt/crash on bad ones, it will do the job.  Although your current implementation actually does tolerate some possible bad lines.

Processing the input

Halting on the first error

Efficiency

You perform a series of maps.  Each one creates a complete new collection before the next is applied.  If the first line is poorly formatted and there are 20000 lines in the file, your first map will split all 20000 lines before crashing when it cannot parse that first line.  Worse, if the first line is "1/0", which is well formatted but not a valid Fraction, the code will split 20000 lines, then parse 20000 Array[String]s and only then halt on the first invalid input.

The solution is to start with lines.view.  A view is a lazy version of the collection.  If you apply a transformation (e.g map or filter), what you receive is not a transformed collection but a new view with all the original items, each of which will not be transformed until you access it.  If you apply a second transformation, you receive yet another view, still with the original items but now with with two transformations which will be applied in sequence (in other words, they have been composed into a new function) to each item as you access it.  And so on.

So if we change your code to

val fractions = lines.view splitLines parseInts makeFractions

(for simplicity, assume we have created 3 functions which implement your 3 transformations) then fractions will still be untransformed in reality, waiting to apply all 3 transformations to any item you ask for.  So if you then do

`sumFractions(fractions)` // A SeqView is still a Seq

or (if you've implemented the Numeric type class for Fraction)

fractions.sum

then it will start by applying all 3 transformations to the first line.  If that line is "3/0", the program will halt without touching the rest, saving a lot of time.

Catching more bad lines

Your code will tolerate "1/2/3" or "1/2/ gibberish" as input lines, converting them both to Fraction(1,2).  That is because it asks for the first two elements  This can be avoided with pattern matching and a partial function.  So the second, parseInts transformation could be rewritten with

map { case Array(x, y) => Array(x.toInt, y.toInt) }

or

map { case ar@Array(x, y) => ar map { _.toInt } }

Because this uses a partial function, if any input line does not split into an array of precisely 2 items then the program will throw a MatchError.

Pattern matching this way is expressive and succinct enough to combine the second and third transformations.  So we could replace both parseInts and makeFractions with

map { case Array(x, y) => new Fraction(x.toInt, y.toInt) }

Although this may give you concise code at the expense of flexibilty, particularly if you want to report meaningful errors (more later on that).

Regex rather than Split

Regexes offer at least three possible advantages

The option to tolerate whitespace in your input
Powerful pattern matching
Easier error reporting

val fractionLine = """(\d+)/(\d+)""".r

creates a pattern which is even more useful than split "/" because it only matches properly formatted lines with genuine numbers in them.  Optionally,

val fractionLine = """\s*(\d+)\s*/\s*(\d+)\s*""".r

accepts harmless whitespace.  The first transformation could be rewritten as

map { case fractionLine(x, y) => Array(x, y) }

the first two as

map { case fractionLine(x, y) => Array(x.toInt, y.toInt) }

or all three to

map { case fractionLine(x, y) => new Fraction(x.toInt, y.toInt) }

Again, combining these functions may be concise but may hinder debugging or error reporting.

Meaningful errors

A simple way to provide better error reporting is to turn the partial functions into complete functions, raising errors when no match is made.  So the regex version of the first transformation could become

map {
  case fractionLine(x, y) => Array(x, y)
  case s => throw new MyException("Invalid input line:'" + s + "'")
}

Similarly, the second transformation could throw an exception if the input doesn't match Array(x, y) and the third could complain if the divisor is 0.

Another way to add useful information to error reporting would be to add zipWithIndex as a new, first transformation so that the number of the line in the file is available.

Note that combining two or three of the transformations into one would make the error-handling pattern matching more complex and fragile, although not combining them would make it more complex to report the line number and line content if the failure was in the later transformations.

There are more functional ways to deal with errors but that's a more complex topic.


My queue implementation (in C) This is my queue implementtion in C. Feel free to ask me any questions relating to my code. Any tips or suggestions are welcome, including tips on naming/spacing/common conventions.
Queue_node, Queue, create_queue, destroye_queue, queue_push, queue_pop are meant to work with any node struct which has a member struct Queue_node *next and functions to create the node and destroy the node.
#include <stdlib.h>
/* malloc(), EXIT_SUCCESS */
#include <stdio.h>
/* fprintf */
#include <stddef.h>
/* size_t */

struct Coordinate {
    int x;
    int y;
};

struct Queue_node {
    struct Queue_node *next;
};

struct Queue {
    struct Queue_node *front;
    struct Queue_node *back;

    size_t size;
};

struct Queue* create_queue(void) {

    struct Queue *created_queue = malloc(sizeof(*created_queue));

    if (created_queue == NULL) {
        return NULL;
    }

    created_queue->back = NULL;
    created_queue->front = NULL;
    created_queue->size = 0;

    return created_queue;
}

void destroy_queue(struct Queue *input_queue, void (*delete_node)(void*)) {

    while (input_queue->front != NULL) {

        struct Queue_node *deleted_node = input_queue->front;
        input_queue->front = input_queue->front->next;
        if (delete_node != NULL) {
            delete_node(deleted_node);
        }
    }
    free(input_queue);
}

void queue_push(struct Queue *input_queue, void *input_node) {

    ++input_queue->size;

    if (input_queue->front == NULL) { // first insert

        input_queue->front = (struct Queue_node*) input_node;
        input_queue->back = (struct Queue_node*) input_node;

        return;
    }

    input_queue->back->next = (struct Queue_node*) input_node;
    input_queue->back = input_queue->back->next;
}

void* queue_pop(struct Queue* input_queue) {

    if (input_queue->front == NULL) { // empty queue
        return NULL;
    }

    --input_queue->size;

    struct Queue_node *deleted_node = input_queue->front;
    input_queue->front = input_queue->front->next;

    return deleted_node;
}

/*
nodes that are queue_pop()'d must be free()'d by caller
*/

static struct Weighted_coord_node {
    struct Queue_node *next;
    // parent property

    int weight;
    struct Coordinate coord;
    // child properties
};

static struct Weighted_coord_node* create_node(struct Coordinate coord, int weight) {

    struct Weighted_coord_node *node = malloc(sizeof(*node));

    if (node == NULL) {
        return NULL;
    }
    node->next = NULL;
    node->coord = coord;
    node->weight = weight;

    return node;
}

int main() {

    struct Queue *my_queue = create_queue();
    if (!my_queue) {
        return EXIT_FAILURE;
    }

    struct Weighted_coord_node *my_node;

    my_node = create_node((struct Coordinate){5,5}, 0);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    my_node = create_node((struct Coordinate){7,7}, 2);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    my_node = create_node((struct Coordinate){11,11}, 5);
    if (!my_node) {
        return EXIT_FAILURE;
    }
    queue_push(my_queue, my_node);

    while (my_node = queue_pop(my_queue)) {
        fprintf(stderr, "POP->  X: %i, Y:%i   weight: %i\n", my_node->coord.x, my_node->coord.y, my_node->weight);
        free(my_node);
    }

    destroy_queue(my_queue, free);

    return EXIT_SUCCESS;
}

I rewrote the code following @vnp's suggestion. Here is the new version: My queue implementation (in C) [V.2]

DRY. queue_push assigns queue_back to the input_node no matter what. Consider
  if (input_queue->front == NULL) {
      assert(input_queue->back == NULL);
      input_queue->front = input_node;
  } else {
      assert(input_queue->back != NULL);
      input_queue->back->next = input_node;
  }
  input_queue->back = input_node;

(asserts are there only to clarify the logic).
Ditto for queue_pop.

Usually we don't want the client code to be aware of the containers, neither depend of them. If perchance you'd eventually decide to keep the weighted coordinates in a tree rather than a list, you'd need to redesign struct Weighted_coord_node, and the surrounding code. I strongly recommend to have struct Queue_node keeping the pointer to the actual data
  struct Queue_node {
      struct Queue_node * next;
      void * client_data;
  };


Selecting/ Deselecting All from Checkbox $scope.selectAllProctoringUser = function(checked) {
    try {
        for (var k = 0; k < $scope.scheduleUsers.lstOnlineProctoring.length; k++) {
            $scope.scheduleUsers.lstOnlineProctoring[k].selected = checked;
            if (checked) {
                let flag = 0;
                if($scope.selectedUserListOP.length == 0) {
                    $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]);
                    flag = 1;
                } else {
                    angular.forEach($scope.selectedUserListOP, (el, idx) => {
                        if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
                            flag = 1;
                        }
                    });
                }
                if(flag === 0){
                    $scope.selectedUserListOP.push($scope.scheduleUsers.lstOnlineProctoring[k]);
                }

            } else {
                angular.forEach($scope.selectedUserListOP, (el, idx) => {
                    if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
                        $scope.selectedUserListOP.splice(idx, 1);
                    }
                });
            }
        }
    } catch(e) {
                console.log('Method: selectAllProctoringUser:  ' + e.message);
      }
}

I had replaced the above with below snippets and working perfectly

$scope.selectAllProctoringUser = function(checked) {
    try {
        $scope.scheduleUsers.lstOnlineProctoring.forEach(x => {
            x.selected = checked;
            if(checked){
                if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length == 0)
                    $scope.selectedUserListOP.push(x);
            } else if(!checked){
                if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length > 0)
                    $scope.selectedUserListOP.splice(x, 1);
            }
        });
    } catch(e) {
                console.log('Method: selectAllProctoringUser:  ' + e.message);
      }
}

If the above code could still get reduced? or written instead making use of filter operator

Are there any use cases, substituting the above code may cause failure or exceptions?

Expecting more solutions from what that I had initially coded

I see what looks like a bug. The x variable (which should probably be renamed to something more informative - maybe user?) is a object (with selected and StudentScheduleUsrID properties) which you remove from the array in the upper code with

} else {
    angular.forEach($scope.selectedUserListOP, (el, idx) => {
        if(el.StudentScheduleUsrID === $scope.scheduleUsers.lstOnlineProctoring[k].StudentScheduleUsrID) {
            $scope.selectedUserListOP.splice(idx, 1);
        }
    });
}

splice's first argument should be the index of the element you want to start deleting from. That's fine. But in the lower code, the first argument you pass to splice is the object x, not the index:

$scope.scheduleUsers.lstOnlineProctoring.forEach(x => {
  // ...
  } else if(!checked){
      if($scope.selectedUserListOP.filter(m => m.StudentScheduleUsrID == x.StudentScheduleUsrID).length > 0)
          $scope.selectedUserListOP.splice(x, 1);
  }

That won't work, because the first argument is not a number. If you want to remove this x from the array there, find its index in the array with findIndex, then pass that number to splice.

const selectedUserIndex = $scope.selectedUserListOP.findIndex(
  selectedUser => selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID
);
if (selectedUserIndex !== -1) {
  $scope.selectedUserListOP.splice(selectedUserIndex, 1);
}

On a different note: Errors should not arise in synchronous code in most cases. If you have code that sometimes results in an unexpected error, you should fix the code so that the error doesn't ever occur (as far as you can tell). If you've tested the code in various situations (which you should be doing anyway, as a developer) and you can't think of any which might cause an error to occur, there shouldn't be any reason to use try/catch, since it'll just clutter up the code - and besides, you aren't doing anything with the error other than logging it to the console, but the error will be logged to the console anyway. So, feel free to remove the try/catch.

It can be reasonable to have a try/catch if any of the following are true and you can do something useful with the error (such as send it to your server logs for examination, or gracefully degrade functionality for the user):

You're awaiting an asynchronous operation that might throw (eg, due to a network problem - very common)
Synchronous code you're calling and don't have control over may throw (pretty unusual)
Despite implementing your own tests, the logic is extremely complicated and you're not sure if there lingering issues (pretty unusual)
You need to break out of a deeply nested function with throw and yield control flow back to a much higher calling function (pretty unusual and somewhat of a code smell - better to test values and return when invalid)

None of the above are going on here.

Instead of filtering inside the loop to check to see if any of the elements in the selectedUserListOP have a matching StudentScheduleUsrID, it would be more elegant and less computationally complex to construct a Set of all the StudentScheduleUsrIDs in the selectedUserListOP beforehand. Then, all you need to do inside the loop is check whether that set .has it:

$scope.selectAllProctoringUser = function(checked) {
  const selectedUserStudentIds = new Set(
    $scope.selectedUserListOP.map(
      user => user.StudentScheduleUsrID
    )
  );
  $scope.scheduleUsers.lstOnlineProctoring.forEach(user => {
    user.selected = checked;
    if (checked) {
      if (!selectedUserStudentIds.has(user.StudentScheduleUsrID)) {
        $scope.selectedUserListOP.push(x);
      }
    } else {
      const selectedUserIndex = $scope.selectedUserListOP.findIndex(
        selectedUser => selectedUser.StudentScheduleUsrID === user.StudentScheduleUsrID
      );
      if (selectedUserIndex !== -1) {
        $scope.selectedUserListOP.splice(selectedUserIndex, 1);
      }
    }
  });
}

If you did have to iterate over the array there, instead of if (someArr.filter(...).length == 0), it would be better to

Use strict equality with ===, not loose equality (consider using a linter)
To check whether every items in an array passes a test (or doesn't pass a test), use .every or .some - don't use .filter to construct a new array only to check its length. Eg:

if ($scope.selectedUserListOP.every(m => m.StudentScheduleUsrID !== x.StudentScheduleUsrID))


Regularity in the "Rusty Towel of Mutual understanding" I have the following Java class:

import java.util.Random;

public class RandomNameGenerator {

    private Random rand;

    private static String[] prefixes = { "Ultimate", "Bloody", "Crooked",
            "Hallowed", "Magnificent", "Heavy", "Jagged", "Grand", "Shiny",
            "Rusty" };

    private static String[] items = { "Chainsaw", "Towel", "Ping-Pong Ball",
            "Longsword", "Scissors", "Dagger", "Blade", "Bow", "Axe", "Dagger",
            "Spoon", "Fork", "Coat", "Chain Mail", "Plate Mail", "Cloak",
            "Cape", "Mirror", "Cauldron", "Pouch", "Boots", "Shoes", "Greaves",
            "Pants", "Robes", "Locket", "Ring", "Amulet", "Potion", "Fish",
            "Teapot", "Hood", "Crown", "Cap", "Helmet" };

    private static String[] addons = { "Glorious", "Bloody", "Prolonged",
            "Bitter", "Wicked", "Furious" };

    private static String[] postfixes1 = { "Destruction", "Feminism",
            "Twilight", "Massacre", "Dread", "Terror", "Mutual Understanding",
            "Spite", "Immobility", "Mediocrity", "Anger" };

    private static String[] postfixes2 = { "the Occult", "the Captain",
            "the Warrior", "the Hunter", "the Haunted", "the Dead",
            "the Fallen", "the Hitchhiker", "the Wicked King", "the Grue" };

    public RandomNameGenerator() {
        rand = new Random(System.currentTimeMillis());
    }

    public String getRandomName() {
        StringBuilder str = new StringBuilder();
        if (rand.nextInt(100) < 10) {
            str.append("+");
            str.append(Integer.toString(rand.nextInt(10) + 1));
            str.append(" ");
        }
        if (rand.nextInt(100) < 50) {
            str.append(prefixes[rand.nextInt(prefixes.length)]);
            str.append(" ");
        }
        str.append(items[rand.nextInt(items.length)]);
        str.append(" of ");
        if (rand.nextInt(postfixes1.length + postfixes2.length) > postfixes2.length) {
            if (rand.nextInt(100) < 70) {
                str.append(addons[rand.nextInt(addons.length)]);
                str.append(" ");
            }
            str.append(postfixes1[rand.nextInt(postfixes1.length)]);
        } else {
            str.append(postfixes2[rand.nextInt(postfixes2.length)]);
        }
        return str.toString();
    }
}

I use it in a small program to generate sample item names like

  Shiny Dagger of the Haunted
  Shoes of Immobility
  Bow of Mediocrity

In general I get the results that I want, however I can't help but notice, that certain combinations pop up very frequently, for example

  Ping-Pong Ball of the Occult

occurs very often.
Is there a design flaw that leads to this outcome? Is there a better way to format what I'm trying to achieve?

Your randomness for calculating the last postfixes is not regular.... there are very slight deviations

(Note update on the doubling of daggers at the end though... that's not 'slight').

Let's do a couple of things here. Firstly, rename them:

postfixes1 -> concepts:

private static String[] concepts = { "Destruction", "Feminism",
        "Twilight", "Massacre", "Dread", "Terror", "Mutual Understanding",
        "Spite", "Immobility", "Mediocrity", "Anger" };

postfixes2 -> people:

private static String[] people = {"the Occult", "the Captain",
        "the Warrior", "the Hunter", "the Haunted", "the Dead",
        "the Fallen", "the Hitchhiker", "the Wicked King", "the Grue"};

Then, you can make the logic clearer near the end. Your code is (with the renames):

    if (rand.nextInt(concepts.length + people.length) > people.length) {
        if (rand.nextInt(100) < 70) {
            str.append(addons[rand.nextInt(addons.length)]);
            str.append(" ");
        }
        str.append(concepts[rand.nextInt(concepts.length)]);
    } else {
        str.append(people[rand.nextInt(people.length)]);
    }

Now, what's the problem there?

Well, there are 2 ...

people should not have 'the' prepended to all of them. It is repeating yourself. Instead you should have:

str.append("the ").append(people[rand.nextInt(people.length)]);

there is an off-by-one error in if (rand.nextInt(concepts.length + people.length) > people.length) {. This is hard to explain... but....

nextInt(limit) selects a random number up to, but not including the limit.

in this case, the limit is concepts.length + people.length, and, if you put those two arrays together, there are 21 members (11 concepts, 10 people). So, you select a random number up to, but not including 21... then, if it is greater than people.length (10), you choose to add a concept. So, the chances are 10 in 21 that it will be > 10  (values 11, 12, 13, ... 20), and then you chose to do the side that has 11 entries. You are using the proportions of people to decide whether to do a concept.....

Your code should be:

if (rand.nextInt(concepts.length + people.length) >= people.length) {
    // add a concept

or, more logically:

if (rand.nextInt(concepts.length + people.length) < concepts.length) {
    // add a concept

So, you do have an imbalance. You are selecting people about 10% more often than you should....

Update: Jeroen and I were discussing some odd values coming out with dagger, and I hacked out some of your code, and ran it through with this loop:

public static void main(String[] args) {
    RandomNameGenerator rng = new RandomNameGenerator();
    Map<String, AtomicInteger> counts = new TreeMap<>();
    for (int i = 0; i < 100000; i++) {
        String val = rng.getRandomName();
        if (!counts.containsKey(val)) {
            counts.put(val, new AtomicInteger());
        }
        counts.get(val).incrementAndGet();
    }
    counts.forEach((k,v) -> System.out.printf("%6d %s%n", v.get(), k));
}

Note, what I am doing is just counting the occurrences of a String.

I then stripped out some of the 'qualifiers' from your code, and got results like:

   110 Amulet of Anger
   126 Amulet of Destruction
   114 Amulet of Dread
   ......
   127 Chain Mail of Feminism
   125 Chain Mail of Immobility
   118 Chain Mail of Massacre
   134 Chain Mail of Mediocrity
   ......
   140 Crown of the Hitchhiker
   154 Crown of the Hunter
   168 Crown of the Occult
   155 Crown of the Warrior
   141 Crown of the Wicked King
   243 Dagger of Anger
   233 Dagger of Destruction
   271 Dagger of Dread
   245 Dagger of Feminism
   245 Dagger of Immobility
   240 Dagger of Massacre
   254 Dagger of Mediocrity
   ...
   318 Dagger of the Hunter
   299 Dagger of the Occult
   328 Dagger of the Warrior
   295 Dagger of the Wicked King
   131 Fish of Anger
   130 Fish of Destruction
   101 Fish of Dread
   129 Fish of Feminism

Note how Dagger appears about twice as often as other values?

That's because you have "Dagger" in the input data twice:

private static String[] items = { .....,
        "Longsword", "Scissors", "Dagger", "Blade", "Bow", "Axe", "Dagger",
        //
        // Dagger twice          ^^^^^^^^                         ^^^^^^^^
        .....
        "Teapot", "Hood", "Crown", "Cap", "Helmet" };


Regrouping JSON object I wrote a JavaScript source which regrouping by new key i.e. following JSON to the other:

{
    "items" : [
        {
            "company" : "A"
            , "name" : "Prod_A01"
        }
        , {
            "company" : "A"
            , "name" : "Prod_A02"
        }
        , {
            "company" : "B"
            , "name" : "Prod_B01"
        }
    ]
}

to:

{
    "A" : [
        {
            "company" : "A"
            , "name" : "Prod_A01"
        }
        , {
            "company" : "A"
            , "name" : "Prod_A02"
        }
    ]

    , "B" : [
        {
            "company" : "B"
            , "name" : "Prod_B01"
        }
    ]
}

And here is logic:

function regroup(collection, key){
    var novo_obj = {};
    var type = typeof collection;
    var keyGroup = [];

    getKeyGroup(collection, key, keyGroup);

    for(var i = 0; i < keyGroup.length; i++) {
        novo_obj[keyGroup[i]] = [];
        gatherElements(collection, key, keyGroup[i], novo_obj[keyGroup[i]]);
        //console.log(novo_obj);
    }
    console.log(JSON.stringify(novo_obj));
    return novo_obj;
}

function gatherElements(collection, key, value, arr){
    //console.log(collection);
    if(typeof collection == 'object'){
        var targetValue = collection[key];
        if(typeof targetValue != 'undefined' && targetValue == value){
            arr.push(collection);
        }else{
            for(var elem in collection){
                gatherElements(collection[elem], key, value, arr);
            }
        }
    }else if(typeof collection == 'array'){
        for(var i = 0; i < collection.length; i++) {
            getKeyGroup(collection[i], key, value, arr);
        }
    }
}

function getKeyGroup(collection, key, keygroup){
    var targetValue = '';
    if(typeof collection == 'object'){
        targetValue = collection[key];
        if(typeof targetValue != 'undefined'){
            keygroup.push(targetValue);
        }else{
            for(var elem in collection){
                getKeyGroup(collection[elem], key, keygroup);
            }
        }
    }else if(typeof collection == 'array'){
        console.log('isArr');
        for(var i = 0; i < collection.length; i++) {
            getKeyGroup(collection[i], key, keygroup);
        }
    }
    return keygroup;
}

function main(){
    var test = {
        items : [
            {
                company : "A"
                , name : "Prod_A01"
            }
            , {
                company : "A"
                , name : "Prod_A02"
            }
            , {
                company : "B"
                , name : "Prod_B01"
            }
        ]
    }
    regroup(test, "company");
}

However, I think looping every time does not look so good. I need to improve this source code.

I think you may be complicating things a lot. If I understand correctly you are basically after groupBy which you can find in lodash, or implement in a few lines of code:

function groupBy(coll, f) {
  return coll.reduce(function(acc, x) {
    var k = f(x);
    acc[k] = (acc[k] || []).concat(x);
    return acc;
  }, {});
}

var test = {
  items: [{
    company: "A", name: "Prod_A01"
  }, {
    company: "A", name: "Prod_A02"
  }, {
    company: "B", name: "Prod_B01"
  }]
};

var result = groupBy(test.items, function(x){return x.company});

JSON.stringify(result);
/*^
{
  "A": [
    {
      "company": "A",
      "name": "Prod_A01"
    },
    {
      "company": "A",
      "name": "Prod_A02"
    }
  ],
  "B": [
    {
      "company": "B",
      "name": "Prod_B01"
    }
  ]
}
*/

You can use this to group a collection (array of objects) by some property, test.items in this case. Also, I would leave the JSON part out of it, because it is irrelevant to the grouping algorithm.


Parsing positive integers from CSV file Part-2 Part-1 here

This is a small CSV parser for positive integers mostly intended for personal projects.
I (hopefully) improved the code from Part-1 by condensing some parts and improving others while also keeping performance the same.
My main worries are any obvious pitfalls I might have missed as well as concerns about the general approach. Of course anything else you notice is also welcome.
Please see part-1 for a list of requirements/restrictions I had when writing this.

For anyone who wants to test this against actual input I provide a small Perl script to generate CSV files.

Call it with: perl [scriptname] [how many lines you want] >outputfile

use strict;
use warnings "all";

die "usage: perl $0 <amount_of_lines>\n" unless (int(@ARGV) > 0);

for (1 .. $ARGV[0]) {
    my $vals_per_line = int(rand(10));
    my @values;
    for (0 .. $vals_per_line) {
        push(@values, int(rand(1000)));
    }
    print join(",", @values) . "\n";
}

Code:

#include <fstream>
#include <string>
#include <vector>

template<typename T>
void parse_lines(
        const std::string& filename,
        const uint_fast8_t& line_length_estimate,
        const uint_fast8_t& values_per_line_estimate,
        T callback) {
    std::ifstream infile{filename};
    if (!infile.good()) {
        return;
    }

    std::vector<uint_fast16_t> numbers;
    numbers.reserve(values_per_line_estimate);

    std::string buffer;
    buffer.reserve(line_length_estimate);

    while (infile.good() && std::getline(infile, buffer)) {
        if (buffer[buffer.size() - 1] == '\r') {
            buffer[buffer.size() - 1] = ',';
        }
        else {
            buffer.push_back(',');
        }

        uint_fast16_t parsed_number = 0;
        for (const auto& digit : buffer) {
            if (digit == ',') {
                numbers.emplace_back(parsed_number);
                parsed_number = 0;
            }
            else {
                parsed_number = (parsed_number * 10) + (digit - '0');
            }
        }
        callback(numbers);
        numbers.clear();
    }
}

int main(int argc, char** argv) {
    constexpr uint_fast8_t line_length_estimate = 50;
    constexpr uint_fast8_t values_per_line_estimate = 15;
    parse_lines(argv[1], line_length_estimate, values_per_line_estimate, [](auto& values) {
        // ...
    });
}

Great that you renamed you function according to what it does. I would suggest, that you add a helper function that reads a single line.

Creating small well encapsulated functions is key in writing maintainable code.

Regarding you code there are some small nits:

The code pattern

container[container.size() - 1]

can alway be replaced by

container.back()

Regarding the parsing you could use std::string::find_first_of and search for the next occurence of it.

std::size_t first = 0;
std::size_t second;
while (first != buffer.size()) {
    second = buffer.find_first_of(",\r", first);
    // parse [first, second)
    first = second + 1;
}

That way in the interval [first, second) there would always be the numbers and you would not have to replace the final character or other stuff
Again encapsulation. There is no reason why the this block of code is not inside its own function:

uint_fast16_t parsed_number = 0;
for (const auto& digit : buffer) {
    if (digit == ',') {
        numbers.emplace_back(parsed_number);
        parsed_number = 0;
    }
    else {
        parsed_number = (parsed_number * 10) + (digit - '0');
    }
}

Even better if you encapsulate it you can easily adopt for iterators/positions

uint_fast16_t parse_number(cont std::string& buffer, std::size_t first, std::size_t second) {
    uint_fast16_t parsed_number = 0;
    for (std::size_t i = first; i < second; ++i) {
        parsed_number = (parsed_number * 10) + (buffer[i] - '0');
    }
    return parsed_number;
}

Now you can write the loop as

while (infile.good() && std::getline(infile, buffer)) {
    std::size_t first = 0;
    std::size_t second;
    while (first != buffer.size()) {
        second = buffer.find_first_of(",\r", first);
        numbers.push_back(parse_number(buffer, first,second));
        first = second + 1;
    }
    callback(numbers);
    numbers.clear();
}

I would even suggest to create another function for parsing the single line:

void parse_single_line(std::string& buffer, std::vector<uint_fast16_t>& numbers) {
    std::size_t first = 0;
    std::size_t second;
    while (first != buffer.size()) {
        second = buffer.find_first_of(",\r", first);
        numbers.push_back(parse_number(buffer, first,second));
        first = second + 1;
    }

Together this leads to

while (infile.good() && std::getline(infile, buffer)) {
    parse_single_line(buffer, numbers);
    callback(numbers);
    numbers.clear();
}


Turning a grayscale image into a histogram of the intensity of the pixels of that image This is exercise 3.1.4. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a program that takes the name of a grayscale image file as a command-line argument and uses StdDraw to plot a histogram of the frequency of occurrence of each of the 256 grayscale intensities.
Here is my program:
import java.awt.Color;

public class ImageToHistogram
{
    public static double getIntensity(Color color) // this method produces monochrome luminance
    {
        int r = color.getRed();
        int g = color.getGreen();
        int b = color.getBlue();
        return 0.299*r + 0.587*g + 0.114*b;
    }
    public static double[][] convertPictureToArray(Picture picture)
    {
        int width = picture.width();
        int height = picture.height();
        double[][] pixels = new double[width][height];
        for (int col = 0; col < width; col++)
        {
            for (int row = 0; row < height; row++)
            {
                Color color = picture.get(col,row);
                pixels[col][row] = getIntensity(color);
            }
        }
        return pixels;
    }
    public static void drawHistogram(double[][] a)
    {
        int m = a.length;
        int n = a[0].length;
        int pixels = m*n;
        int[] histogram = new int[256];
        StdDraw.setPenColor(StdDraw.BOOK_BLUE);
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                int intensity = (int) a[i][j];
                histogram[intensity]++;
            }
        }
        StdDraw.setXscale(0,256);
        StdDraw.setYscale(0,pixels/20); // obtained "20" by experimentation
        StdDraw.enableDoubleBuffering();
        for (int i = 0; i < 256; i++)
        {
            StdDraw.filledRectangle(i+0.5,histogram[i]/2,0.5,histogram[i]/2);
        }
        StdDraw.show();
    }
    public static void main(String[] args)
    {
        Picture picture = new Picture(args[0]);
        double[][] a = convertPictureToArray(picture);
        drawHistogram(a);
    }
}

StdDraw and Picture are simple APIs written by the authors of the book. I checked my program and it works. Here is one instance of it:
Input (Grayscale picture of Coleen Gray taken from Wikipedia):

Output:

I also tested the extreme cases of pure black and pure white images.
Is there any way that I can improve my program?
Thanks for your attention.
Clarification:
I used the preview of the image provided by Wikipedia with resolution of 800 by 933 and not the original image with resolution of 2000 by 2333.

JPG vs PNG
Somehow, your code seems to produce wrong results with the above JPG. When used with the same image converted to PNG, the histogram looks much better, and much closer to what Photoshop displays.
ImageIO.read(file) seems to not return the correct RGB values with the above JPG. It is outside of your code though, and seems to be called by Picture class.
As mentioned by @Nayuki, it seems to be a known bug/feature:

https://bugs.openjdk.java.net/browse/JDK-5051418
https://stackoverflow.com/questions/31312645/java-imageio-grayscale-png-issue
https://stackoverflow.com/questions/32583772/reading-grayscale-png-image-files-without-distortion

Double -> int
getIntensity returns a double.
For example, getIntensity(new Color(1, 1, 1)) returns 0.9999999999999999, which is very close to 1.0 but strictly smaller than 1.0.
When you cast this double to an integer in int intensity = (int) a[i][j], it gets converted to 0, which isn't desired.
With your current code, the first histogram bins look like this:
[37509, 2429, 0, 3981, 0, 1763, 1757, 4131, 0, 2016, 4718, 0, 6498, 0, 3526, 7824, ...

If you replace the line with int intensity = (int) Math.round(a[i][j]);, the first bins look like this:
[32317, 5192, 2429, 2327, 1654, 1763, 1757, 2034, 2097, 2016, 2230, 2488, 2947, 3551, 3526, 3683, 4141, ...

Which should produce a smoother and more correct diagram.
As mentioned by @MarkRansom:

the goal should be to redistribute the values in a way that preserves
their overall distribution.

Rounding the doubles should work fine in the above case, because the values are very close to integers. In the general case, truncating might be preferred.


Pattern for creating a globally accessible custom plugin I'm currently using this pattern to create and extend a globally accessible custom plugin to be used in a web application:

; // defensive programming: script may be concatenated with others

(function($) {
    "use strict";

    // allow Plugin to be extended from other scripts
    var window.Plugin = window.Plugin || {};

    var privateVars = {
        // this contains all of the plugin's "private static" fields
    };

    function someHelperFunction() {
        // this is a private method
    }

    $.extend(window.Plugin,
    {
        method1: function() {
            // this is a public method
        },
        method2: function() {
            // this is a public method
        }
    });
})(jQuery);

This approach looks fine to me and seems to tick all the boxes. However, since I'm far from a JS guru I wonder:

Are there any issues with the above pattern that I should be aware of?

Now suppose I want to introduce global configuration that affects the behavior of all subsequent calls to method1, for example allow the user to register a callback that will get fired every time before method1 executes.

In my mind, this syntax would be nice:

window.Plugin.method1.registerCallback(function() { ... });
window.Plugin.method1(); // take it for a test drive

Is this a good idea? If not, why? What would be a better approach?

To implement this, I would do

window.Plugin = { ... }; // as above
window.Plugin.method1.registerCallback = function() {
    // this would write something inside privateVars
};

Is there a more convenient way to add many properties to method1 like this?

For example, one that would not require one statement per property to be added. Should I use jQuery.extend for this as well?

The usual way to create a plugin is to declare a namespace or use an existing and append to it. Usually done using the module pattern:

(function(ns){

  //private scoping
  var privVar = '...';
  function priv(){...}

  //expose a function
  ns.myFunc = function(){...};

}(this.myLib = this.myLib || {}));

//using the exposed myFunc
myLib.myFunc();

Issues with your code? Well, it depended on jQuery just to append methods. It's not really necessary to use extend. With the above pattern, you can cleanly add functions to the namespace.

If you really need just some parts of jQuery, you can grab their code and just use it directly. I usually interrogate the code and pick out only the parts that are necessary. Or you can roll your own jQuery build. They have instructions on their GitHub on how to roll your own mix of jQuery.

Now, for function callbacks, you should use the a technique similar to pub-sub or event emitters or jQuery's on method. The syntax looks like this:

myLib.on('fnName',function(){...});

where fnName is the function name that is equivalent to the function called.

Now how to implement?

Well, each of your functions should call a special internal function that fires callbacks collected in your library. Basically, the on, method of your library just collects callbacks and registers them in an internal cache id'ed with the name of the function. The implementation would look like this:

(function(){

  //handler cache
  var handlers = {};

  //our internal function that executes handlers with a given name
  function executeHandlers(eventName){
    //get all handlers with the selected name
    var handler = handlers[eventName] || []
      , len = handler.length
      , i
      ;
    //execute each
    for(i = 0; i< len; i++){
      //you can use apply to specify what "this" and parameters the callback gets
      handler[i].apply(this,[]);
    }
  }

  //our on function which collects handlers
  ns.on = function(eventName,handler){
    //if no handler collection exists, create one
    if(!handlers[eventName]){
      handlers[eventName] = [];
    }
    handlers[eventName].push(handler);
  }

  //so we expose a shout function
  ns.shout = function(){

    ...stuff shout does...

    //now we execute callbacks registered to shout
    executeHandlers('shout');
  }

}(this.myLib = this.myLib || {}));

//we register a callback
myLib.on('shout',function(){
  //executed after calling shout
});

//execute shout
myLib.shout();