- (10 points) For each of the following user interface scenarios, choose from the
following list the type of widget you think is most appropriate.
- slider
- menu/list
- type in text box
- radio button
- check box
- command button
- _________________ You want the user to select an occupation from a
set of 50 possible occupations.
- _________________ You want the user to select one of 6 rooms
returned from a hotel search engine. The user may select only
one room.
- _________________ You want the user to select a font style. The
possible options are bold, italic, underline, and oblique. They
can select anywhere from zero to all four options.
- _________________ You want the user to enter the weight of a
package and are willing to accept any weight up to 100000 pounds.
- _________________ You want the user to specify a color by entering
the values for red, green, and blue as integers between 0 and 100.
The user should be able to rapidly change the values and see the
current color immediately updated in a color swatch.
- (4 points) Functions are considered first-class objects in a language if which
of the following condition applies:
- A function may be passed as an argument to a function
- A function pointer may be passed as an argument to a function
- The language supports nested functions (i.e., a "private"
function can be defined by declaring it within another function).
- A function can be created as a value within a function and
returned as a value from that function.
- (4 points) The following technique used by functional language interpreters involves
tagging an expression internally when an expression is first evaluated, and saving the expression's computed value. Thereafter, references to
the expression use this computed value, rather than re-evaluating the
expression.
- tail recursion
- memoization
- lazy evaluation
- applicative evaluation
- (4 points) Which of the following is an argument-passing scheme in functional programming that evaluates
a function argument only when it is needed in the body of a function.
- applicative evaluation
- on demand evaluation
- normal order evaluation
- strict evaluation
- (4 points) Which of the following terms is used
to describe a concurrency condition in which memory may have an unpredictable
value due to two threads trying to modify the same memory
simultaneously.
- deadlock
- liveness
- starvation
- race condition
- (4 points) Which of the following programs would be the best candidate for being
implemented in a scripting language?
- A climate-modeling simulation
- A math library that provides a set of functions, such as
trigonometric functions, random number generators, and exponentiation
functions
- A program to calculate the student grades in a courses
- A compiler
- (4 points) Which of the following programs would be the best candidate for being
implemented in a functional language?
- A program for finding the best move in a chess game by traversing
a tree of possible moves.
- A talk server/client implementation, like the one in your JTtalk assignment.
- A graphical user interface for a drawing program.
- A program for counting word frequencies in a file.
- (4 points) The followng term refers to one endpoint of a two-way communication link between two programs running on the network. This endpoint is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
- thread
- listener
- socket
- adapter
- (4 points) Which of the following Java synchronization techniques enforce
happens-before relationships? Circle all valid answers.
- synchronized statements
- synchronized methods
- join
- atomic variables
- wait
- conditional critical regions
- (5 points) Which of the following characteristics common to functional languages
have found their way into modern scripting languages, such as Python?
Circle all correct answers. There are 5 correct answers:
- garbage collection
- prototype-instance model for objects rather than a class-instance
model
- ability to create functions at run-time using lambda expressions
- higher-order functions such as map and reduce
- powerful macro facilities
- regular expressions for performing pattern matching in strings
- dictionaries (i.e., hash tables) as a built-in language feature
- implicit, parametric polymorphism
- constructors for data structures, such as lists, that allow a
programmer to initialize a structure "all at once".
- side-effect free execution as a general way of programming
- (3 points) What are the advantages of using an appropriate Java thread pool? Circle all
correct answers. There are three correct answers.
- Allow an application to degrade gracefully if a large number
of thread requests are received simultaneously
- Allow the programmer to assign competing threads to separate
pools and hence avoid race conditions
- Reduce the overhead of constantly allocating and deallocating
thread objects.
- Increase concurrency by subdividing tasks until the amount of
work they perform falls under a threshold and allowing the thread
pool to concurrently schedule these tasks.
- Allow programmers to explicitly designate cores that should
be used to execute different threads
- Prevent deadlock by removing a blocked thread from one pool
and moving it to another pool where the lock may be available.
- (4 points) Suppose you are given the following Scheme function:
(define mystery
(lambda (L)
(cond ((null? L) '())
((null? (cdr L)) (car L))
(#t (let ((result (mystery (cdr L))))
(if (< (car L) result)
(car L)
result)))))))
What is the value returned by:
(mystery '(3 8 10 2 8 5))
- (4 points) What is the output of the following Python function call?
map(lambda x,y: x + y, [3, 6, 8, 10], [4, 9, 1, 8])
- [7, 15, 9, 18]
- [3, 6, 1, 8]
- [3, 6, 8, 10, 4, 9, 1, 8]
- [27, 22]
- 27
- 22
- 49
- (5 points) Suppose I have 3 buttons, b1, b2, and b3. I want them to be
grouped together with 20 pixels between b1 and b2 and 20 pixels
between b2 and b3. I want the whole group of 3 buttons pushed against
the right side of the window and to stay attached to the right
side of the window if the window is resized. The figure below gives
an example of how the buttons might look after the window has been
resized:
Assuming that buttonGroup is a horizontal box object, how
would you assign the buttons and filler objects to buttonGroup
to achieve the desired layout?
-
buttonGroup.add(new RigidArea(new Dimension(INFINITY, 0)));
buttonGroup.add(b1);
buttonGroup.add(new RigidArea(new Dimension(20, 0)));
buttonGroup.add(b2);
buttonGroup.add(new RigidArea(new Dimension(20, 0)));
buttonGroup.add(b3);
-
buttonGroup.add(Box.createHorizontalGlue());
buttonGroup.add(b1);
buttonGroup.add(Box.createRigidArea(new Dimension(20, 0)));
buttonGroup.add(b2);
buttonGroup.add(Box.createRigidArea(new Dimension(20, 0)));
buttonGroup.add(b3);
-
buttonGroup.add(new horizontalGlue(), b1, 20, b2, 20, b3);
-
buttonGroup.add(Box.createRigidArea(new Dimension(0, 0)));
buttonGroup.add(b1);
buttonGroup.add(Box.createHorizontalGlue(20));
buttonGroup.add(b2);
buttonGroup.add(Box.createHorizontalGlue(20));
buttonGroup.add(b3);
-
buttonGroup.add(Box.createHorizontalGlue());
buttonGroup.add(b1);
buttonGroup.add(Box.createHorizontalGap(20));
buttonGroup.add(b2);
buttonGroup.add(Box.createHorizontalGap(20));
buttonGroup.add(b3);
- Model-View-Controller (MVC) model (10 points): An intern has created
the following GUI that shows candidates' vote totals and allows a person to
vote for a candidate:
Below is a Java pseudo-code representation of the Java code
that the intern created for
displaying and updating the results of an election:
class ElectionResults extends JPanel {
int candidateVoteTotal = new int[4];
JFrame window = new JFrame();
ElectionResults() {
initializeView();
pack and make window visible
}
void addToCandidate(int candidate) {
candidateVoteTotal[candidate]++;
repaint();
}
void initializeView() {
window.getContentPane().add(this);
for each candidate {
create a JButton labeled vote
create a JLabel with the candidate's name
create a JLabel that display's the candidate's
total votes
add an event handler to the JButton that
1) calls addToCandidate with the appropriate index
2) updates the candidate's total vote JLabel
3) calls repaint
}
}
}
This code obviously does not conform to the MVC format. Assume that:
- your boss
has told you to modify this code so that it conforms to the MVC format, and
- you have decided that ElectionResults will be your glue class
Which of the following actions should you take to transform the code so that
it meets the MVC format. Circle all answers that apply (if an answer has
some valid and some invalid actions in it, do not circle it). There are
5 correct answers.
- Move the candidateVoteTotal array and the addToCandidate methods
to a new model class. Remove the repaint() call from the
addToCandidate method and add code to the addToCandidate method that
notifies each view of the change to the candidate vote totals.
- Move the candidateVoteTotal array and the addToCandidate methods
to a new model class and don't modify the addToCandidate method in
any way.
- Move the view and event handling code to a new view class, but do
not change any of the event handling code and do not add any additional
methods to the view class.
- Create an interface that each view implements and that allows
the model class to notify each view of changes to a candidate's
vote.
- Keep the candidateVoteTotal array and the addToCandidate methods in
ElectionResults. Remove the repaint() call from the addToCandidate
method and add code to the addToCandidate method that
notifies each view of the change to the candidate vote totals.
- Keep the view and event handling code in ElectionResults and
don't modify any of it.
- Keep the view and event handling code in ElectionResults but
1) create a method that the model can call to notify the view of any
changes, and 2) move the code that updates the JLabel representing the candidate's total votes and that calls repaint() (actions 2 and 3) from the event handling code to this new method.
- Add code to the constructor for ElectionResults that creates an
instance of the new model class, an instance of the new view class
(creating the instance will replace the call to initializeView()),
and ties the two classes together. The constructor will continue to
pack the window and make it visible.
- Move the code in the constructor for ElectionResults to the
constructor for the new model class so that the new model class
creates the instance of the view and packs and makes the window visible.
The constructor for ElectionResults should be changed so that
all it does is create an instance of the model and then returns.
- Move the view and event handling code to a new view class, and
1) create a method that the model can call to notify the view of
any changes, and 2) move the code that updates the JLabel representing the candidate's total votes and that calls repaint() (actions 2 and 3) from the event handling code to this new method.
- Move the view and event handling code to a new view class and
modify the
first action in the event handling code so that it notifies any other
views of changes to one of the candidate's vote totals. Don't modify
either actions 2 or 3 in the event handling code. Finally, add methods
to the new view class that allows new views to register and
de-register themselves with the view.
- Add methods to the new model class that allows views to register and
de-register themselves with the model.
- Add methods to the ElectionResults class that allows new views to
register and de-register themselves with the ElectionResults class.
- Create an interface that the model implements and that allows
the event handling code to notify the model of changes to a candidate's
vote.
- (6 points) Suppose you wanted to write a Scheme function to reverse the elements
of a list. For example
(reverseList '(3 8 5 2 7))
should return
(7 2 5 8 3)
Which of the following functions would correctly perform this
task? Circle all answers that apply:
-
(define reverseList (lambda (L)
(letrec ((reverseHelper (lambda (L reversedList)
(cond
((null? L) reversedList)
(#t (reverseHelper (cdr L)
(cons (car L) reversedList)))))))
(reverseHelper L '()))))
-
(define reverseList (lambda (L)
(cond
((null? L) '())
(#t (cons (cdr L) (car L))))))
-
(define reverseList (lambda (L)
(cond
((null? L) '())
(#t (append (reverseList (cdr L)) (list (car L)))))))
-
(define reverseList (lambda (L)
(letrec ((reverseHelper
(lambda (L reversedList)
(cond
((null? L) reversedList)
(#t (reverseHelper (cdr L) (car L)))))))
(reverseHelper L '()))))
- (6 points--Java Concurrency) Consider the following Java class definition:
public class BadThreads {
static final int maxTasks = 5; // the maximum number of tasks that may
// be waiting for execution
int tasksQueue[] = new int[maxTasks]; // holds the queued tasks, and more specifically the
// number of milliseconds required to
// execute the task
int taskFront = 0; // the index of the front of the task queue (i.e.,
// the index of the next task to execute)
int taskEnd = 0; // the index of the back of the task queue (i.e.,
// the index of the next empty spot in the task queue)
int waitingTasks = 0; // the number of queued tasks waiting to execute
class Worker extends Thread {
public void run() {
try {
while (true) {
int taskId = taskFront;
int taskTime = tasksQueue[taskFront];
taskFront = (taskFront + 1) % maxTasks;
waitingTasks--;
Thread.sleep(taskTime);
}
} catch (InterruptedException e) {}
}
}
class Scheduler extends Thread {
public void run() {
try {
while (true) {
int taskTime = ThreadLocalRandom.current().nextInt(5, 10000);
tasksQueue[taskEnd] = taskTime;
taskEnd = (taskEnd + 1) % maxTasks;
waitingTasks++;
Thread.sleep(ThreadLocalRandom.current().nextInt(300, 2000));
}
} catch (InterruptedException e) {}
}
}
public BadThreads() {
Worker workers[] = new Worker[3];
int i;
for (i = 0; i < 3; i++) {
workers[i] = new Worker();
workers[i].start();
}
Scheduler s = new Scheduler();
s.start();
}
public static void main(String args[]) {
new BadThreads();
}
}
The tasksQueue is a wrap-around queue that can hold up to 5 tasks.
The application spawns three Worker threads which execute infinite loops
that remove tasks from
the tasksQueue array and "execute" the task by sleeping for the indicated
amount of time. It does not matter which Worker thread gets which task.
The application also spawns a single Scheduler thread that executes
an infinite loop that generates tasks with execution times of between 5 and
10000 milliseconds and adds the tasks to the tasksQueue. The Scheduler thread
sleeps for a random interval between 300 and 2000 milliseconds after adding
each task.
There are three major bugs in this code. Circle the three choices from the
following list that correctly describe these bugs.
- The Scheduler thread never yields to the Worker threads
- The Worker threads do not wait on the Scheduler thread if the
tasksQueue is empty and hence might try to remove a task from an
empty tasksQueue
- The Scheduler thread may get into a race condition trying to get
a random number.
- The Scheduler thread does not wait on the Worker threads if the
tasksQueue is full and hence could try to add a task to a full tasksQueue.
- The Worker threads could deadlock by both claiming a task and
then trying to defer to the other thread that has claimed the task
- The Worker threads could livelock by waiting for each other
to take a task from the tasksQueue
- The Worker threads can get into race conditions with each other as
they update the information associated with the tasksQueue and the
Scheduler thread can also get into a race condition with any of the
Worker threads over the same information.
- the Worker threads and Scheduler thread could deadlock by blocking
each other from using the tasksQueue.
- (15 points) Write a Python function that:
- takes a list of (voter, candidate) tuples as a parameter
- tabulates the vote for each candidate.
- prints out the candidates in descending order by vote count. If two
candidates tie, you can print them out in any order.
For each candidate print the candidate's name, a space, and the
number of votes they
received.
Do not let a voter vote for
more than one candidate. In other words, the first time you see a voter
you should have the function record that voter's vote.
If you encounter the voter later in the list,
then ignore the voter's vote.
For example, if your input were:
[('nels', 'smiley'), ('brad', 'wolf'), ('nels', 'wolf'), ('sue', 'smiley')]
then your output would be:
smiley 2
wolf 1
Note that nels tried to vote twice and that his second vote was ignored.
If your input list were instead:
[('nels', 'smiley'), ('brad', 'wolf'), ('nels', 'wolf'),
('sue', 'smiley'), ('sarah', 'huck'), ('mindy', 'smiley')]
then your output would be:
smiley 3
wolf 1
huck 1
It would be fine if the order of wolf and huck were reversed.