Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
CS 169 Spring 2016, Quiz 1 Wednesday, Feb. 17, 2016 710pm 155 Dwinelle
Your name: SID#: Name & signature of person on your left: Name & signature of person on your right:
I certify that in accordance with the UC Berkeley honor code, all the work on this exam is my own, that I did not receive assistance from anyone in constructing the answers, and that I did not use any resources other than those specifically allowed or provided for by the exam. I understand that the penalty for academic dishonesty is a grade of zero for the exam with no possibility of makeup; a likely reduction in the course final grade in addition to that implied by the lower exam grade; and referral of the case for disciplinary action and possible unenrollment from the course.
Sign & date
Instructions 1. The exam is designed to take 90 minutes but everyone will have 180 minutes to complete it.
Points reflect relative difficulty of questions at 1 point per minute. Scan the whole exam first. 2. For nonmultiplechoice questions, fill in answers on these pages. 3. For multiplechoice questions, fill in answers on bubble sheet. 4. You're allowed one doublesided page of notes ("cheat sheet"); no other books, notes, phones,
tablets, computers, smart watches, etc etc. Note that we have provided a Capybara cheat sheet at the end of this handout.
Good skill! Summary of the questions:
1. (20 points) SOA, REST, and nonREST: short answers 2. (12 points) Ruby Iterators: writing code 3. (20 points) Cucumber & Capybara: writing code 4. (38 points) Multiplechoice questions covering SaaS, REST, Ruby, and Hangperson homework
SOA and REST (20 points)
Ru B. Hacker and Ray L. Zapp are reviewing each other's proposed SaaS architecture diagrams. Ray has proposed a serviceoriented architecture for a system he's been asked to design. In the diagram below, A1, A2, A3 are three different SaaS apps, and D1 and D2 are two different databases (i.e. databases with different schemata). D1 primarily stores A1's data, but A2 can access it directly; similarly for D2 and A2. Ru objects that this is not a SOA, but that it could be converted into one by removing one or more of the numbered arrows <==> that represent communication between the components.
Q1.1 [6] Why does Ru believe this is not a SOA? Explain briefly (12 sentences max). Because A1 and A2 is manipulating each other’s database directly, not through their service interface. Q1.2. [4] Indicate the minimum set of arrows that could be removed to convert it into an SOA. Arrow 2 and 3
Ru B. Hacker then proposes the below SaaS deployment for her new app: it uses three copies of the app server to handle more users, and also includes a background application that users cannot access that automatically makes a backup copy D’ of the database D periodically.
Q1.3 . [5] Ray says "Aha! Now it's my turn to point out that your design isn't SOA either!" Is Ray correct? If so, explain what changes would have to be made to the architecture diagram to make it SOA. If he is not correct, explain why not. Ray is not correct, even though the application is duplicated, browser can only get data through communicating with SaaS application interface and SaaS application doesn’t need to talk to backup copy D’, so it is still SOA
This is a true story but the names have been changed. Earlier this semester, Prof. Fox was reviewing applications of prospective Berkeley graduate students. The main view shows a list of all applicants. Clicking an applicant's name shows a detail page for that applicant, including a form where a faculty member can enter comments about the applicant.
Prof. Fox likes to compare similar applicants side by side, so:
1.First he Shiftclicked the link for applicant Marissa Mayer , so that her app would appear in a new window.
2.Then he went back to the list of applicants window and clicked the link for Mark Zuckerberg , so now he has 2 sidebyside windows, one showing Zuck's application and one showing Marissa's application.
3.After reading both applications, he entered comments on Marissa 's app, and clicked Save.
But the confirmation message when the form was submitted said, "Thank you for commenting on Mark Zuckerberg 's app." Sure enough, Prof. Fox reloaded both windows, and his comments had been associated with Mark's app instead of Marissa's! "Goshdarn these nonRESTful application actions!" cried Prof. Fox (only he didn't say "goshdarn"). Q1.4 [5] What aspect(s) of the app's design do you think resulted in this nonintuitive behavior? Try to be specific. The app’s design is not RESTful. It stores the last student application user clicked in session and use that information to decide which application to update. So no matter which applicant user is editing, the app would only update the last application user clicked.
Ruby Iterators (12 points) Ruby's hacker friend Diamond is trying to learn the "Ruby way" of doing things by creating her own iterators for the following Matrix class. A Matrix is created by passing an array of rows, each of which is an array of column values:
m = Matrix.new([ [3,5,7,8], [0,4,‐1,0], [1,3,1,1] ])
The above would represent the following matrix of 3 rows and 4 columns: 3 5 7 8 0 4 –1 0 1 3 1 1
Internally, the class stores a matrix as an array of arrays, for example, the matrix above would be stored in the instance variable @rows as:
[ [3,5,7,8] , [0,4,‐1,0], [1,3,1,1] ] Q2.1. [2] Fill in the code for the instance methods num_rows and num_columns, which return the number of rows and number of columns in the matrix respectively. You may assume matrices are not ragged, that is, every subarray contains the same number of elements. Q2.2 [4] Fill in the code for the each_row iterator on the answer sheet code skeleton, which is used as follows:
matrix.each_row do |row| puts row end
[3,5,7,8] [0,4,‐1,0] [1,3,1,1]
(Be careful: the iterator should just yield each row, not print it.) Q2.3 [6] Fill in the code for the each_column iterator on the answer sheet code skeleton, which is used as follows:
matrix.each_column do |col| puts col end
[3,0,1] [5,4,3] [7,‐1,1] [8,0,1]
class Matrix attr_reader :rows def initialize(rows,cols,array_of_arrays) # assume the code exists to populate instance variable @rows as above end def num_rows # Q2.1: your code here #
@rows.length # Assume matrix non‐empty, at least has one row end def num_columns # Q2.2: your code here #
@rows[0].length # Assume matrix non‐empty, at least has one row end def each_row # Q2.3: your code here #
@rows.each do |row| yield row
end end def each_column 0..upto(self.num_columns ‐ 1) do |index| # Q2.4: your code here #
col = [] @rows.each do |row|
col << @rows[index] end yield col
end end end
Cucumber & Capybara (20 points) You are working on Whiskr, which is Tinder for whiskey lovers with cats. One feature of the
application is that users can sign up with their name and email. Let’s write some Cucumber
steps to test out this feature:
Feature: signup for an account
As a whiskey‐drinking cat lover
So that I can socialize with other similar people
I want to signup for an account on Whiskr.com
Given I am on the signup page
When I fill in the signup form with name: "Ernest Hemingway" and email: "[email protected]"
And I press "Sign Up"
Then a user with email "[email protected]" should exist
The routes file contains these routes, among others: resources :users get '/signup', :controller => 'users', :action => 'signup' post '/signup', :controller => 'users', :action => 'create_signup'
The ActiveRecord model for User has the following attributes: name (string), email (string) Fill in the step definitions for the above steps, and the body of the create_signup controller method, in the provided code skeleton . (You don’t need to add additional steps in the scenario.) You should assume the app does not have access to the web_steps.rb prepackaged steps file. On the last page of the quiz is a Capybara cheat sheet you may find
helpful. Assume for the user form that only the name and email are required to register, without
a password.
File user_steps.rb: Given /^I am on the signup page$/ do visit "/signup" end When /^I fill in the signup form
with name: “([^”]*)” and email: “([^”]*)” $/ do |name,email| # Q3.1[2] # Q3.2 [2] your code here # fill_in(“name”, name) fill_in(“email”, email)
end When /^I press "Sign Up"$/ do
# Q3.3 [2] your code here click_button(“Sign Up”)
end Then /^A user with email: “([^”]*)” should exist$/ do |email| # Q3.4[2] # Q3.5 [4] your code here
expect(User.where(email: email)).not_to be_nil end File users_controller.rb: class UsersController < ApplicationController def create_signup # Q3.5 [2] params.require( :name, :email ) # Q3.6 [2] @user = User.create(params) # Q3.7 [4] redirect_to user_path(@user) end end
Name:
SID:
Spring 16 Midterm 1 multiple choice questions
Please read the questions carefully! Some have a single correct answer, others ask you to "check
all that apply".
For 'select all that apply' questions worth N points, you get 1/N of the points for each RIGHT
answer that you check, but you are penalized 1/N for each answer you check that is not correct
(or for each answer you leave unchecked that is correct). In other words, it doesn't pay to guess.
Good skill!
1. [1 point] Select ALL that apply: Which of the following software development methodologies include the
iterative refinement of prototypes as part of the overall software lifecycle?
Agile
Spiral
Waterfall
RUP (Rational Unified Process)
2. [1 point] Regardless of development methodology, which of the following parts of the software lifecycle
consumes the largest fraction of resources?
a. Design
b. Testing
c. Bug fixing
d. Enhancing/adding new features
e. Deployment/operations
3. [1 point] The term "TCP port" refers to which of the following?
a. The socket on a server computer that accepts a network cable
b. A textual label (such as "http") that identifies which app running on a server is the intended"endpoint" of a particular network traffic stream
c. A numerical label (such as "3000") that identifies which app running on a server is the intended
"endpoint" of a particular network traffic stream
d. A fortified wine fermented by the TCP Company
4. [1 point] Which is NOT an advantage of SaaS over shrink wrapped software?
a. SaaS is a better fit for Agile teams, which are becoming increasingly popular in industry
b. SaaS often has one centralized database, which is easier to manage when data is updatedfrequently
c. SaaS software updates can happen frequently, as long as external API compatibility is maintained
5. [2 points] Select ALL that apply: Which statements are TRUE regarding cloud computing and SOA?
One reason "elastic" cloud computing is a good match for SaaS is the stateless HTTPprotocol.
A stateless protocol between client and server means any "copy" of a server can handle anyclient's request, simplifying scaling-out using cloud computing.
Internal datacenters could achieve comparable cost savings to those enjoyed by warehouse-scale
computing if they re-architected their apps to exploit service-oriented architecture.
Part of the savings from utility computing comes from the higher utilization of cloudresources achieved by sharing them among multiple companies or apps.
6. [1 point] Select ALL that apply: Which of the following are true regarding the use of migrations to manage
the database schema of a SaaS app?
Migrations allow "versioning" the database schema analogously to how code is versioned.
Migrations may change the schema, but they never result in destroying or discarding data.
Migrations can be expressed in a way that is independent of minor syntactic differencesbetween different underlying databases.
7. [1 point] Select ALL that apply: In a client-server architecture, which are advantages of a stateless
communication protocol?
Simplifies client design
Simplifies horizontal scaling
Eliminates need for cookies
More secure than a stateful protocol
Enables RESTful communication
8. [1 point] In a Sinatra or Rails application, which layer handles the actual HTTP interactions of receiving
requests and serving responses back to the client?
a. Relational Database
b. Sinatra or Rails Framework
c. Web Server
d. Rack App Server
9. [1 point] Which of the following would most likely be the result of an HTTP POST request?
a. Fetching search results from a search engine
b. Logging into your email account
c. Viewing your profile on your favorite social media website
10. [1 point] Select ALL that apply: Requirements analysis and specification in P&D corresponds to whatAgile practice(s)? (Select all that apply)
Test driven development
Velocity
User stories
11. [1 point] Which of the following is NOT a value expressed in the Agile Manifesto?
a. We value individuals and interactions over processes and tools
b. We value working software over comprehensive documentation
c. We value customer collaboration over contract negotiation
d. We value following a plan over responding to change
12. [3 points] Helen Hacker is creating a Ruby application to keep track of her favorite books and plays. Shedecides to create separate Ruby classes for Book and Play, because even though both have a title andauthor, they are otherwise very different: for example, a Play has an opening_date, number_of_acts,and other attributes that don't apply to a Book. One function she needs to implement is to sort a list of books and plays by their title, that is, to sort acollection that may contain both instances of Book and instances of Play. What design should she use tosolve this problem in Ruby?
a. Book and Play must be subclasses of some common ancestor, such as Manuscript; this ancestorclass should provide a sort method that can recognize and handle either the Book or Play subclass.
While this would technically work, it's poor design to create a common ancestor of two classes thathave very little in common, just to enable a simple behavior like sorting.
b. As long as Book and Play both have an attribute named title, Helen can use the sort_bymethod to write something like sorted = list_of_works.sort_by |work| work.title .
Because of duck typing, the solution using sort_by will work as long as any object passed to thesorting method can respond to title. This solution is economical because it doesn't require us togive Book and Play a common ancestor just to enable sorting, and because it allows us to reuseexisting methods like sort_by that are part of Ruby's standard library (in the Enumerablemodule).
c. Helen must create a separate instance method in either Book or Play and use that that method to dothe sorting.
This is incorrect because we are not sorting a single Book or Play, but a collection.
d. Since not all the elements to be sorted are of the same type, Helen must create a variant of Ruby'sexisting sort method (in the standard library) that can handle a mixed collection.
Because of duck typing, the solution using sort_by will work as long as any object passed to thesorting method can respond to title. This solution is economical because it doesn't require us togive Book and Play a common ancestor just to enable sorting, and because it allows us to reuseexisting methods like sort_by that are part of Ruby's standard library (in the Enumerable module).
e. Since not all the elements to be sorted are of the same type, Helen must separate the collection intotwo collections (one containing only Books and the other containing only Plays), sort eachcollection, then re-combine the two sorted collections.
Because of duck typing, the solution using sort_by will work as long as any object passed to thesorting method can respond to title. This solution is economical because it doesn't require us togive Book and Play a common ancestor just to enable sorting, and because it allows us to reuseexisting methods like sort_by that are part of Ruby's standard library (in the Enumerable module).
13. [1 point] Suppose x refers to an object of class X and y refers to an object of class Y. The result ofevaluating x+y:
a. will raise an error because x and y are of different classes
Recall that 3+1.0 will work even though 3 is a Fixnum and 1.0 is a Float.
b. will only work if X and Y are subclasses of classes that define the + operation
Remember that a module included by a class can also define instance methods.
c. depends on how + is defined in class X or any of its included modules
Since x+y is syntactic sugar for x.send(:+, y), the behavior depends on how + is defined by thereceiver x.
d. depends on how + is defined in class Y or any of its included modules
You're on the right track, but remember which object is the receiver here.
14. [1 point] Which of the following functionality would most likely be defined as a class method?
a. update an instance variable of a Movie object
b. return the total number of Movie objects created
c. compare two movies, e.g. for the purposes of sorting
15. [3 points] Suppose we have a Movie model with title and rating attributes stored in the database, plus theadditional instance variable num_stars as defined below:
1 class Movie < ActiveRecord::Base2 # database columns are title & rating3 attr_accessor :num_stars45 def initialize()6 @num_stars = 07 super8 end9 end
Suppose we start out with no movies in the database, then run the following code:
movie = Movie.newmovie.title = "The Best Movie"movie.rating = "PG"movie.num_stars = 5movie.save
load_movie = Movie.where(:title => "The Best Movie")
The result of evaluating movie.num_stars is:
a. nil
b. 0
c. 5
d. An error
16. [1 point] (Continued from previous question) The result of evaluating load_movie.num_stars is:
a. nil
b. 0
c. 5
d. An error
17. [1 point] (Continued from previous question) Which of the following is true after calling movie.destroy?
a. The object is gone forever, so asking for the value of movie.title will raise an error
b. The object still lives in memory, so we can still get and set movie.title
c. The object is in memory but is no longer in the database. We can get the value ofmovie.title, but we cannot set it.
d. We need to call movie.save before the row corresponding to movie is actually deleted from themovies table.
18. [3 points] Read the following code for a simple Sinatra app:
require "sinatra"
get "/" do erb :formend
post "/create" do "Start!"end
get "/win" do "You win!"end
get "/create" do "Cool!"end
Where views/form.erb contains the following content:
Suppose the site is hosted at www.myapp.com, and a user visits www.myapp.com and clicks the "Start"button. What will be shown in the browser?
a. Cool!
b. You win!
c. Start!
19. [1 point] Select ALL that apply: Given the HTTP request GET http://www.mysearch.com:8000/search?q=cs169, which elements of that request does a SaaS app framework use to determine what app code to
run (e.g., in the case of Rails, which controller method to call)?
GET
www.mysearch.com
:8000
/search
q=cs169
20. [1 point] Select ALL that apply: Which of the following are true of all well-designedRESTful APIs?
Each route clearly identifies both a resource and an operation to do on thatresource
it returns resources in JSON format
it requires authentication, for example by providing an API key
21. [1 point] When your Rails app receives an HTTP request, how does Rails know what codein your application to call to handle that request?
a. Rails calls a method with the same name as the HTTP request, passing in thearguments from the URI in params
b. Rails parses the name of the controller and action from the URI
c. Rails looks for a view matching the URI of your request
d. Rails uses a mapping between routes and controller actions to find the correctaction to call
22. [1 point] Completing which of the following tasks would not contribute to the teamvelocity?
a. Add Facebook/Google 3rd party authentication
b. Strengthen user security by salting and hashing user passwords
c. Implement infinite scroll in frontpage display
d. Create separate views for mobile users
23. [1 point] Select ALL that apply: A user submits a new movie form. How would the
associated controller access the title of the movie?
params['title']
Form parameters always get put into params, which quacks like a hash.
params.title
Form parameters always get put into params, which quacks like a hash.
session.title
Form parameters always get put into params, which quacks like a hash.
session['title']
Form parameters always get put into params, which quacks like a hash.
24. [1 point] Select ALL that apply: What does line 4 do in the following code?
1 class PostsController < ActionController::Base
2 def add_post
3 # ...code to create new blog post...
4 flash[:notice] = "Post added successfully"
5 redirect_to posts_url
6 end
7 end
Writes a message to the log
Makes the message available to whatever view is rendered for this action
Persists the message until the next request
25. [1 point] In a Sinatra app such as the Hangperson app assigned in the homework, how are
routes (HTTP verb plus URI) mapped to Ruby code that handles each request type?
a. The verbs and routes are specified in the routes.rb file
b. The verbs and routes are specified in the config.ru file used by the rackup
command that starts the rack app server
c. There are Sinatra methods corresponding to each verb, and the URI is specifieddirectly in the app
26. [1 point] Where is the Hangperson game state stored between (stateless) HTTP requestsfrom the player?
a. In a session cookie
b. In the database
c. In the app server's memory
27. [1 point] In the Hangperson SaaS code, why do the create-game action and the guess-a-letter action end with a redirect?
a. Because actions that modify state must always end with a redirect
b. Because actions that modify state should use HTTP POST or PUT, but we can onlyrender a view for actions that use a GET
c. Because it allows us to re-use existing actions to display the game state aftermodifying it by creating a new game or guessing a letter
28. [2 points] Select ALL that apply: If the Hangperson SaaS code were incorporated into atrue service-oriented architecture in which another service "plays" the game remotely,which of the existing game actions, if any, would NOT be needed?
GET /new
POST /create
POST /guess
29. [1 point] In terms of how Cucumber executes scenarios (features), what is thedifference between Given, When, and Then steps?
a. Only When steps (representing actions to be taken) can modify application state orhave side effects, for example via POST requests.
b. You must specify at least one Given step before any When or Then steps.
c. There is no difference in execution; Given, When, and Then are aliases for thesame method.
30. [1 point] Select ALL that apply: In Agile/XP, when a user story is delivered, who maysign off on the story as 'complete'?
The team's tech lead
The customer
A team member acting as the voice of the customer, such as the product owner
The project manager
The developer whose code and tests constitute the delivered story
31. [1 point] EXTRA CREDIT: Which of the following is NOT an example of an early SaaSsystem introduced in Armando's Computer History Minute?
a. Airline reservations processing
b. Email/electronic correspondence
c. Electronic banking