In this guide you will learn how controllers work and how they fit into the request cycle in your application.
After reading this guide, you will know:
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that’s not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
NOTE: For more details on the routing process, see Rails Routing from the Outside In.
The naming convention of controllers in Rails favors pluralization of the last word in the controller’s name, although it is not strictly required (e.g. ApplicationController
). For example, ClientsController
is preferable to ClientController
, SiteAdminsController
is preferable to SiteAdminController
or SitesAdminsController
, and so on.
Following this convention will allow you to use the default route generators (e.g. resources
, etc) without needing to qualify each :path
or :controller
, and keeps URL and path helpers’ usage consistent throughout your application. See Layouts & Rendering Guide for more details.
NOTE: The controller naming convention differs from the naming convention of models, which expected to be named in singular form.
A controller is a Ruby class which inherits from ApplicationController
and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
class ClientsController < ApplicationController def new end end
As an example, if a user goes to /clients/new
in your application to add a new client, Rails will create an instance of ClientsController
and run the new
method. Note that the empty method from the example above would work just fine because Rails will by default render the new.html.erb
view unless the action says otherwise. The new
method could make available to the view a @client
instance variable by creating a new Client
:
def new @client = Client.new end
The Layouts & Rendering Guide explains this in more detail.
ApplicationController
inherits from ActionController::Base
, which defines a number of helpful methods. This guide will cover some of these, but if you’re curious to see what’s in there, you can see all of them in the API documentation or in the source itself.
Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after “?” in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It’s called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params
hash in your controller:
class ClientsController < ApplicationController # This action uses query string parameters because it gets run # by an HTTP GET request, but this does not make any difference # to the way in which the parameters are accessed. The URL for # this action would look like this in order to list activated # clients: /clients?status=activated def index if params[:status] == "activated" @clients = Client.activated else @clients = Client.inactivated end end # This action uses POST parameters. They are most likely coming # from an HTML form which the user has submitted. The URL for # this RESTful request will be "/clients", and the data will be # sent as part of the request body. def create @client = Client.new(params[:client]) if @client.save redirect_to @client else # This line overrides the default rendering behavior, which # would have been to render the "create" view. render "new" end end end
The params
hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets “[]” to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3
NOTE: The actual URL in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3” as “[” and “]” are not allowed in URLs. Most of the time you don’t have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
The value of params[:ids]
will now be ["1", "2", "3"]
. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
To send a hash you include the key name inside the brackets:
<form accept-charset="UTF-8" action="/clients" method="post"> <input type="text" name="client[name]" value="Acme" /> <input type="text" name="client[phone]" value="12345" /> <input type="text" name="client[address][postcode]" value="12345" /> <input type="text" name="client[address][city]" value="Carrot City" /> </form>
When this form is submitted, the value of params[:client]
will be { "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }
. Note the nested hash in params[:client][:address]
.
Note that the params
hash is actually an instance of ActiveSupport::HashWithIndifferentAccess
, which acts like a hash but lets you use symbols and strings interchangeably as keys.
If you’re writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. Rails will automatically convert your parameters into the params
hash, which you can access as you would normally.
So for example, if you are sending this JSON content:
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
You’ll get params[:company]
as { "name" => "acme", "address" => "123 Carrot Street" }
.
Also, if you’ve turned on config.wrap_parameters
in your initializer or calling wrap_parameters
in your controller, you can safely omit the root element in the JSON parameter. The parameters will be cloned and wrapped in the key according to your controller’s name by default. So the above parameter can be written as:
{ "name": "acme", "address": "123 Carrot Street" }
And assume that you’re sending the data to CompaniesController
, it would then be wrapped in :company
key like this:
{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }
You can customize the name of the key or specific parameters you want to wrap by consulting the API documentation
NOTE: Support for parsing XML parameters has been extracted into a gem named actionpack-xml_parser
The params
hash will always contain the :controller
and :action
keys, but you should use the methods controller_name
and action_name
instead to access these values. Any other parameters defined by the routing, such as :id
will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status
parameter in a “pretty” URL:
match '/clients/:status' => 'clients#index', foo: 'bar'
In this case, when a user opens the URL /clients/active
, params[:status]
will be set to “active”. When this route is used, params[:foo]
will also be set to “bar” just like it was passed in the query string. In the same way params[:action]
will contain “index”.
default_url_options
You can set global default parameters for URL generation by defining a method called default_url_options
in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
class ApplicationController < ActionController::Base def default_url_options { locale: I18n.locale } end end
These options will be used as a starting point when generating URLs, so it’s possible they’ll be overridden by the options passed in url_for
calls.
If you define default_url_options
in ApplicationController
, as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted. This means you’ll have to make a conscious choice about which attributes to allow for mass updating and thus prevent accidentally exposing that which shouldn’t be exposed.
In addition, parameters can be marked as required and flow through a predefined raise/rescue flow to end up as a 400 Bad Request with no effort.
class PeopleController < ActionController::Base # This will raise an ActiveModel::ForbiddenAttributes exception # because it's using mass assignment without an explicit permit # step. def create Person.create(params[:person]) end # This will pass with flying colors as long as there's a person key # in the parameters, otherwise it'll raise a # ActionController::ParameterMissing exception, which will get # caught by ActionController::Base and turned into that 400 Bad # Request reply. def update person = current_account.people.find(params[:id]) person.update_attributes!(person_params) redirect_to person end private # Using a private method to encapsulate the permissible parameters # is just a good pattern since you'll be able to reuse the same # permit list between create and update. Also, you can specialize # this method with per-user checking of permissible attributes. def person_params params.require(:person).permit(:name, :age) end end
Given
params.permit(:id)
the key :id
will pass the whitelisting if it appears in params
and
it has a permitted scalar value associated. Otherwise the key is going
to be filtered out, so arrays, hashes, or any other objects cannot be
injected.
The permitted scalar types are String
, Symbol
, NilClass
,
Numeric
, TrueClass
, FalseClass
, Date
, Time
, DateTime
,
StringIO
, IO
, ActionDispatch::Http::UploadedFile
and
Rack::Test::UploadedFile
.
To declare that the value in params
must be an array of permitted
scalar values map the key to an empty array:
params.permit(id: [])
To whitelist an entire hash of parameters, the permit!
method can be
used:
params.require(:log_entry).permit!
This will mark the :log_entry
parameters hash and any subhash of it
permitted. Extreme care should be taken when using permit!
as it
will allow all current and future model attributes to be
mass-assigned.
You can also use permit on nested parameters, like:
params.permit(:name, { emails: [] }, friends: [ :name, { family: [ :name ], hobbies: [] }])
This declaration whitelists the name
, emails
and friends
attributes. It is expected that emails
will be an array of permitted
scalar values and that friends
will be an array of resources with
specific attributes : they should have a name
attribute (any
permitted scalar values allowed), a hobbies
attribute as an array of
permitted scalar values, and a family
attribute which is restricted
to having a name
(any permitted scalar values allowed, too).
You want to also use the permitted attributes in the new
action. This raises the problem that you can’t use require
on the
root key because normally it does not exist when calling new
:
# using `fetch` you can supply a default and use # the Strong Parameters API from there. params.fetch(:blog, {}).permit(:title, :author)
accepts_nested_attributes_for
allows you to update and destroy
associated records. This is based on the id
and _destroy
parameters:
# permit :id and :_destroy params.require(:author).permit(:name, books_attributes: [:title, :id, :_destroy])
Hashes with integer keys are treated differently and you can declare
the attributes as if they were direct children. You get these kinds of
parameters when you use accepts_nested_attributes_for
in combination
with a has_many
association:
# To whitelist the following data: # {"book" => {"title" => "Some Book", # "chapters_attributes" => { "1" => {"title" => "First Chapter"}, # "2" => {"title" => "Second Chapter"}}}} params.require(:book).permit(:title, chapters_attributes: [:title])
The strong parameter API was designed with the most common use cases in mind. It is not meant as a silver bullet to handle all your whitelisting problems. However you can easily mix the API with your own code to adapt to your situation.
Imagine a scenario where you want to whitelist an attribute containing a hash with any keys. Using strong parameters you can’t allow a hash with any keys but you can use a simple assignment to get the job done:
def product_params params.require(:product).permit(:name).tap do |whitelisted| whitelisted[:data] = params[:product][:data] end end
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
ActionDispatch::Session::CookieStore
- Stores everything on the client.ActionDispatch::Session::CacheStore
- Stores the data in the Rails cache.ActionDispatch::Session::ActiveRecordStore
- Stores the data in a database using Active Record. (require activerecord-session_store
gem).ActionDispatch::Session::MemCacheStore
- Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
If your user sessions don’t store critical data or don’t need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
Read more about session storage in the Security Guide.
If you need a different session storage mechanism, you can change it in the config/initializers/session_store.rb
file:
# Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails g active_record:session_migration") # YourApp::Application.config.session_store :active_record_store
Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in config/initializers/session_store.rb
:
# Be sure to restart your server when you modify this file. YourApp::Application.config.session_store :cookie_store, key: '_your_app_session'
You can also pass a :domain
key and specify the domain name for the cookie:
# Be sure to restart your server when you modify this file. YourApp::Application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in config/initializers/secret_token.rb
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. YourApp::Application.config.secret_key_base = '49d3f3de9ed86c74b94ad6bd0...'
NOTE: Changing the secret when using the CookieStore
will invalidate all existing sessions.
In your controller you can access the session through the session
instance method.
NOTE: Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
Session values are stored using key/value pairs like a hash:
class ApplicationController < ActionController::Base private # Finds the User with the ID stored in the session with the key # :current_user_id This is a common way to handle user login in # a Rails application; logging in sets the session value and # logging out removes it. def current_user @_current_user ||= session[:current_user_id] && User.find_by_id(session[:current_user_id]) end end
To store something in the session, just assign it to the key like a hash:
class LoginsController < ApplicationController # "Create" a login, aka "log the user in" def create if user = User.authenticate(params[:username], params[:password]) # Save the user ID in the session so it can be used in # subsequent requests session[:current_user_id] = user.id redirect_to root_url end end end
To remove something from the session, assign that key to be nil
:
class LoginsController < ApplicationController # "Delete" a login, aka "log the user out" def destroy # Remove the user id from the session @_current_user = session[:current_user_id] = nil redirect_to root_url end end
To reset the entire session, use reset_session
.
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.
It is accessed in much the same way as the session, as a hash (it’s a FlashHash instance).
Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
class LoginsController < ApplicationController def destroy session[:current_user_id] = nil flash[:notice] = "You have successfully logged out." redirect_to root_url end end
Note that it is also possible to assign a flash message as part of the redirection. You can assign :notice
, :alert
or the general purpose :flash
:
redirect_to root_url, notice: "You have successfully logged out." redirect_to root_url, alert: "You're stuck here!" redirect_to root_url, flash: { referral_code: 1234 }
The destroy
action redirects to the application’s root_url
, where the message will be displayed. Note that it’s entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It’s conventional to display any error alerts or notices from the flash in the application’s layout:
<html> <!-- <head/> --> <body> <% flash.each do |name, msg| -%> <%= content_tag :div, msg, class: name %> <% end -%> <!-- more content --> </body> </html>
This way, if an action sets a notice or an alert message, the layout will display it automatically.
You can pass anything that the session can store; you’re not limited to notices and alerts:
<% if flash[:just_signed_up] %> <p class="welcome">Welcome to our site!</p> <% end %>
If you want a flash value to be carried over to another request, use the keep
method:
class MainController < ApplicationController # Let's say this action corresponds to root_url, but you want # all requests here to be redirected to UsersController#index. # If an action sets the flash and redirects here, the values # would normally be lost when another redirect happens, but you # can use 'keep' to make it persist for another request. def index # Will persist all flash values. flash.keep # You can also use a key to keep only some kind of value. # flash.keep(:notice) redirect_to users_url end end
flash.now
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create
action fails to save a resource and you render the new
template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now
in the same way you use the normal flash
:
class ClientsController < ApplicationController def create @client = Client.new(params[:client]) if @client.save # ... else flash.now[:error] = "Could not save client" render action: "new" end end end
Your application can store small amounts of data on the client — called cookies — that will be persisted across requests and even sessions. Rails provides easy access to cookies via the cookies
method, which — much like the session
— works like a hash:
class CommentsController < ApplicationController def new # Auto-fill the commenter's name if it has been stored in a cookie @comment = Comment.new(author: cookies[:commenter_name]) end def create @comment = Comment.new(params[:comment]) if @comment.save flash[:notice] = "Thanks for your comment!" if params[:remember_name] # Remember the commenter's name. cookies[:commenter_name] = @comment.author else # Delete cookie for the commenter's name cookie, if any. cookies.delete(:commenter_name) end redirect_to @comment.article else render action: "new" end end end
Note that while for session values you set the key to nil
, to delete a cookie value you should use cookies.delete(:key)
.
ActionController makes it extremely easy to render xml
or json
data. If you’ve generated a controller using scaffolding, it would look something like this:
class UsersController < ApplicationController def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render xml: @users} format.json { render json: @users} end end end
You may notice in the above code that we’re using render xml: @users
, not render xml: @users.to_xml
. If the object is not a String, then Rails will automatically invoke to_xml
for us.
Filters are methods that are run before, after or “around” a controller action.
Filters are inherited, so if you set a filter on ApplicationController
, it will be run on every controller in your application.
“Before” filters may halt the request cycle. A common “before” filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
class ApplicationController < ActionController::Base before_action :require_login private def require_login unless logged_in? flash[:error] = "You must be logged in to access this section" redirect_to new_login_url # halts request cycle end end end
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a “before” filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.
In this example the filter is added to ApplicationController
and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn’t be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_action
:
class LoginsController < ApplicationController skip_before_action :require_login, only: [:new, :create] end
Now, the LoginsController
’s new
and create
actions will work as before without requiring the user to be logged in. The :only
option is used to only skip this filter for these actions, and there is also an :except
option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
In addition to “before” filters, you can also run filters after an action has been executed, or both before and after.
“After” filters are similar to “before” filters, but because the action has already been run they have access to the response data that’s about to be sent to the client. Obviously, “after” filters cannot stop the action from running.
“Around” filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
class ChangesController < ApplicationController around_action :wrap_in_transaction, only: :show private def wrap_in_transaction ActiveRecord::Base.transaction do begin yield ensure raise ActiveRecord::Rollback end end end end
Note that an “around” filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
You can choose not to yield and build the response yourself, in which case the action will not be run.
While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_action methods. The block receives the controller as an argument, and the require_login
filter from above could be rewritten to use a block:
class ApplicationController < ActionController::Base before_action do |controller| redirect_to new_login_url unless controller.send(:logged_in?) end end
Note that the filter in this case uses send
because the logged_in?
method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
class ApplicationController < ActionController::Base before_action LoginFilter end class LoginFilter def self.filter(controller) unless controller.send(:logged_in?) controller.flash[:error] = "You must be logged in" controller.redirect_to controller.new_login_url end end end
Again, this is not an ideal example for this filter, because it’s not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method filter
which gets run before or after the action, depending on if it’s a before or after filter. Classes used as around filters can also use the same filter
method, which will get run in the same way. The method must yield
to execute the action. Alternatively, it can have both a before
and an after
method that are run before and after the action.
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user’s knowledge or permission.
The first step to avoid this is to make sure all “destructive” actions (create, update and destroy) can only be accessed with non-GET requests. If you’re following RESTful conventions you’re already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that’s where the request forgery protection comes in. As the name says, it protects from forged requests.
The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
If you generate a form like this:
<%= form_for @user do |f| %> <%= f.text_field :username %> <%= f.text_field :password %> <% end %>
You will see how the token gets added as a hidden field:
<form accept-charset="UTF-8" action="/users/1" method="post"> <input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/> <!-- fields --> </form>
Rails adds this token to every form that’s generated using the form helpers, so most of the time you don’t have to worry about it. If you’re writing a form manually or need to add the token for another reason, it’s available through the method form_authenticity_token
:
The form_authenticity_token
generates a valid authentication token. That’s useful in places where Rails does not add it automatically, like in custom Ajax calls.
The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request
method contains an instance of AbstractRequest
and the response
method returns a response object representing what is going to be sent back to the client.
request
ObjectThe request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the API documentation. Among the properties that you can access on this object are:
Property of request |
Purpose |
|---|---|
| host | The hostname used for this request. |
| domain(n=2) | The hostname’s first n segments, starting from the right (the TLD). |
| format | The content type requested by the client. |
| method | The HTTP method used for the request. |
| get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
| headers | Returns a hash containing the headers associated with the request. |
| port | The port number (integer) used for the request. |
| protocol | Returns a string containing the protocol used plus “://”, for example “http://”. |
| query_string | The query string part of the URL, i.e., everything after “?”. |
| remote_ip | The IP address of the client. |
| url | The entire URL used for the request. |
path_parameters
, query_parameters
, and request_parameters
Rails collects all of the parameters sent along with the request in the params
hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters
hash contains parameters that were sent as part of the query string while the request_parameters
hash contains parameters sent as part of the post body. The path_parameters
hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
response
ObjectThe response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
Property of response |
Purpose |
|---|---|
| body | This is the string of data being sent back to the client. This is most often HTML. |
| status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
| location | The URL the client is being redirected to, if any. |
| content_type | The content type of the response. |
| charset | The character set being used for the response. Default is “utf-8”. |
| headers | Headers used for the response. |
If you want to set custom headers for a response then response.headers
is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to response.headers
this way:
response.headers["Content-Type"] = "application/pdf"
Note: in the above case it would make more sense to use the content_type
setter directly.
Rails comes with two built-in HTTP authentication mechanisms:
HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser’s HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, http_basic_authenticate_with
.
class AdminsController < ApplicationController http_basic_authenticate_with name: "humbaba", password: "5baa61e4" end
With this in place, you can create namespaced controllers that inherit from AdminController
. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, authenticate_or_request_with_http_digest
.
class AdminsController < ApplicationController USERS = { "lifo" => "world" } before_action :authenticate private def authenticate authenticate_or_request_with_http_digest do |username| USERS[username] end end end
As seen in the example above, the authenticate_or_request_with_http_digest
block takes only one argument - the username. And the block returns the password. Returning false
or nil
from the authenticate_or_request_with_http_digest
will cause authentication failure.
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the send_data
and the send_file
methods, which will both stream data to the client. send_file
is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use send_data
:
require "prawn" class ClientsController < ApplicationController # Generates a PDF document with information on the client and # returns it. The user will get the PDF as a file download. def download_pdf client = Client.find(params[:id]) send_data generate_pdf(client), filename: "#{client.name}.pdf", type: "application/pdf" end private def generate_pdf(client) Prawn::Document.new do text client.name, align: :center text "Address: #{client.address}" text "Email: #{client.email}" end.render end end
The download_pdf
action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the :disposition
option to “inline”. The opposite and default value for this option is “attachment”.
If you want to send a file that already exists on disk, use the send_file
method.
class ClientsController < ApplicationController # Stream a file that has already been generated and stored on disk. def download_pdf client = Client.find(params[:id]) send_file("#{Rails.root}/files/clients/#{client.id}.pdf", filename: "#{client.name}.pdf", type: "application/pdf") end end
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the :stream
option or adjust the block size with the :buffer_size
option.
If :type
is not specified, it will be guessed from the file extension specified in :filename
. If the content type is not registered for the extension, application/octet-stream
will be used.
WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to.
TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
While send_data
works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing “RESTful downloads”. Here’s how you can rewrite the example so that the PDF download is a part of the show
action, without any streaming:
class ClientsController < ApplicationController # The user can request to receive this resource as HTML or PDF. def show @client = Client.find(params[:id]) respond_to do |format| format.html format.pdf { render pdf: generate_pdf(@client) } end end end
In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb
:
Mime::Type.register "application/pdf", :pdf
NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
Now the user can request to get a PDF version of a client just by adding “.pdf” to the URL:
GET /clients/1.pdf
Rails keeps a log file for each environment in the log
folder. These are extremely useful when debugging what’s actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file.
You can filter certain request parameters from your log files by appending them to config.filter_parameters
in the application configuration. These parameters will be marked [FILTERED] in the log.
config.filter_parameters << :password
Sometimes it’s desirable to filter out from log files some sensible locations your application is redirecting to.
You can do that by using the config.filter_redirect
configuration option:
config.filter_redirect << 's3.amazonaws.com'
You can set it to a String, a Regexp, or an array of both.
config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
Matching URLs will be marked as ‘[FILTERED]’.
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound
exception.
Rails’ default exception handling displays a “500 Server Error” message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple “500 Server Error” message to the user, or a “404 Not Found” if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they’re displayed to the user. There are several levels of exception handling available in a Rails application:
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the public
folder, in 404.html
and 500.html
respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can’t use RHTML or layouts in them, just plain HTML.
rescue_from
If you want to do something a bit more elaborate when catching errors, you can use rescue_from
, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
When an exception occurs which is caught by a rescue_from
directive, the exception object is passed to the handler. The handler can be a method or a Proc
object passed to the :with
option. You can also use a block directly instead of an explicit Proc
object.
Here’s how you can use rescue_from
to intercept all ActiveRecord::RecordNotFound
errors and do something with them.
class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: :record_not_found private def record_not_found render text: "404 Not Found", status: 404 end end
Of course, this example is anything but elaborate and doesn’t improve on the default exception handling at all, but once you can catch all those exceptions you’re free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn’t have access to a certain section of your application:
class ApplicationController < ActionController::Base rescue_from User::NotAuthorized, with: :user_not_authorized private def user_not_authorized flash[:error] = "You don't have access to this section." redirect_to :back end end class ClientsController < ApplicationController # Check that the user has the right authorization to access clients. before_action :check_authorization # Note how the actions don't have to worry about all the auth stuff. def edit @client = Client.find(params[:id]) end private # If the user is not authorized, just throw the exception. def check_authorization raise User::NotAuthorized unless current_user.admin? end end
NOTE: Certain exceptions are only rescuable from the ApplicationController
class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik’s article on the subject for more information.
Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the force_ssl
method in your controller to enforce that:
class DinnerController force_ssl end
Just like the filter, you could also pass :only
and :except
to enforce the secure connection only to specific actions:
class DinnerController force_ssl only: :cheeseburger # or force_ssl except: :cheeseburger end
Please note that if you find yourself adding force_ssl
to many controllers, you may want to force the whole application to use HTTPS instead. In that case, you can set the config.force_ssl
in your environment file.


Test::Float::TestSpace Class Reference
[General test support]
Space for executing tests.
More...
#include <float.hh>
List of all members.
Public Member Functions |
| | TestSpace (int n, Gecode::FloatVal &d, Gecode::FloatNum s, Test *t) |
| | Create test space.
|
| | TestSpace (int n, Gecode::FloatVal &d, Gecode::FloatNum s, Test *t, Gecode::ReifyMode rm) |
| | Create test space.
|
| | TestSpace (TestSpace &s) |
| | Constructor for cloning s.
|
| virtual Gecode::Space * | copy (void) |
| | Copy space during cloning.
|
| virtual void | dropUntil (const Assignment &a) |
| | Add constraints to skip solutions to the a assignment.
|
| bool | assigned (void) const |
| | Test whether all variables are assigned.
|
| bool | matchAssignment (const Assignment &a) const |
| | Test whether all variables match assignment a.
|
| void | post (void) |
| | Post propagator.
|
| bool | failed (void) |
| | Compute a fixpoint and check for failure.
|
| void | rel (int i, Gecode::FloatRelType frt, Gecode::FloatVal n) |
| | Perform integer tell operation on x[i].
|
| void | rel (bool sol) |
| | Perform Boolean tell on b.
|
| void | assign (const Assignment &a, MaybeType &sol, bool skip=false) |
| | Assign all (or all but one, if skip is true) variables to values in a If assignment of a variable is MT_MAYBE (if the two intervals are contiguous), sol is set to MT_MAYBE.
|
| void | bound (void) |
| | Assing a random variable to a random bound.
|
| Gecode::FloatNum | cut (int *cutDirections) |
| | Cut the bigger variable to an half sized interval. It returns the new size of the cut interval. cutDirections gives the direction to follow (upper part or lower part of the interval).
|
| void | prune (int i) |
| | Prune some random values from variable i.
|
| void | prune (void) |
| | Prune some random values for some random variable.
|
| bool | prune (const Assignment &a, bool testfix) |
| | Prune values but not those in assignment a.
|
| void | disable (void) |
| | Disable propagators in space and compute fixpoint (make all idle).
|
| void | enable (void) |
| | Enable propagators in space.
|
| unsigned int | propagators (void) |
| | Return the number of propagators.
|
Public Attributes |
| Gecode::FloatVal | d |
| | Initial domain.
|
| Gecode::FloatNum | step |
| | Step for going to next solution.
|
| Gecode::FloatVarArray | x |
| | Variables to be tested.
|
| Gecode::Reify | r |
| | Reification information.
|
| Test * | test |
| | The test currently run.
|
| bool | reified |
| | Whether the test is for a reified propagator.
|
Detailed Description
Space for executing tests.
Definition at line 166 of file float.hh.
Constructor & Destructor Documentation
Create test space.
Creates n variables with domain d and step s for test t.
Definition at line 143 of file float.cpp.
Create test space.
Creates n variables with domain d and step s for test t annd reification mode rm.
Definition at line 160 of file float.cpp.
| Test::Float::TestSpace::TestSpace |
( |
TestSpace & |
s |
) |
|
Constructor for cloning s.
Definition at line 171 of file float.cpp.
Member Function Documentation
| void Test::Float::TestSpace::dropUntil |
( |
const Assignment & |
a |
) |
[virtual] |
Add constraints to skip solutions to the a assignment.
Definition at line 197 of file float.cpp.
| bool Test::Float::TestSpace::assigned |
( |
void |
|
) |
const |
Test whether all variables are assigned.
Definition at line 203 of file float.cpp.
| bool Test::Float::TestSpace::matchAssignment |
( |
const Assignment & |
a |
) |
const |
Test whether all variables match assignment a.
Definition at line 211 of file float.cpp.
| void Test::Float::TestSpace::post |
( |
void |
|
) |
|
| bool Test::Float::TestSpace::failed |
( |
void |
|
) |
|
Compute a fixpoint and check for failure.
Definition at line 232 of file float.cpp.
Perform integer tell operation on x[i].
Definition at line 244 of file float.cpp.
| void Test::Float::TestSpace::rel |
( |
bool |
sol |
) |
|
Perform Boolean tell on b.
Definition at line 261 of file float.cpp.
| void Test::Float::TestSpace::assign |
( |
const Assignment & |
a, |
|
|
MaybeType & |
sol, |
|
|
bool |
skip = false | |
|
) |
| | |
Assign all (or all but one, if skip is true) variables to values in a If assignment of a variable is MT_MAYBE (if the two intervals are contiguous), sol is set to MT_MAYBE.
Definition at line 270 of file float.cpp.
| void Test::Float::TestSpace::bound |
( |
void |
|
) |
|
Assing a random variable to a random bound.
Definition at line 288 of file float.cpp.
Cut the bigger variable to an half sized interval. It returns the new size of the cut interval. cutDirections gives the direction to follow (upper part or lower part of the interval).
Definition at line 303 of file float.cpp.
| void Test::Float::TestSpace::prune |
( |
int |
i |
) |
|
Prune some random values from variable i.
Definition at line 332 of file float.cpp.
| void Test::Float::TestSpace::prune |
( |
void |
|
) |
|
Prune some random values for some random variable.
Definition at line 348 of file float.cpp.
| bool Test::Float::TestSpace::prune |
( |
const Assignment & |
a, |
|
|
bool |
testfix | |
|
) |
| | |
Prune values but not those in assignment a.
Definition at line 359 of file float.cpp.
| void Test::Float::TestSpace::disable |
( |
void |
|
) |
|
Disable propagators in space and compute fixpoint (make all idle).
Definition at line 191 of file float.cpp.
| void Test::Float::TestSpace::enable |
( |
void |
|
) |
|
Enable propagators in space.
Definition at line 186 of file float.cpp.
| unsigned int Test::Float::TestSpace::propagators |
( |
void |
|
) |
|
Return the number of propagators.
Definition at line 410 of file float.cpp.
Member Data Documentation
Initial domain.
Definition at line 169 of file float.hh.
Step for going to next solution.
Definition at line 171 of file float.hh.
Variables to be tested.
Definition at line 173 of file float.hh.
Reification information.
Definition at line 175 of file float.hh.
The test currently run.
Definition at line 177 of file float.hh.
Whether the test is for a reified propagator.
Definition at line 179 of file float.hh.
The documentation for this class was generated from the following files:


Pullen Park
http://www.raleighnc.gov/parks/content/ParksRec/Articles/Parks/Pullen.htmlDid you know?
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.
 Ut enim ad minim veniam, quis nostrud exercitation ullamco.
www.raleighnc.gov/.../content/ParksRec/Articles/Parks/Pullen.html - 55k - 2016-10-04 - Cached
... Pullen Park Event Calendar; Special Parking Information; Proposed park bond project at this location. Community Center.<PHONE_NUMBER> (main) |<PHONE_NUMBER> (press 0 for shelter rentals); Director Abigail Kepler. Center Programs. ...
... Pullen Park Event Calendar; Special Parking Information; Proposed park bond project at this location. Community Center.<PHONE_NUMBER> (main) |<PHONE_NUMBER> (press 0 for shelter rentals); Director Abigail Kepler. Center Programs. ...
www.raleighnc.gov/.../content/ParksRec/Articles/ParksFacilities.html - 48k - 2016-09-06 - Cached
... parks. Athletic, Sports and Aquatic Facilities. Courts (all). Fields (all). Athletic Facilities Buffaloe Road Athletic Park Walnut Creek Softball Complex. ... Aquatic Facilities Buffaloe Road Aquatic Center Millbrook Pool Optimist Pool Pullen ...
... parks. Athletic, Sports and Aquatic Facilities. Courts (all). Fields (all). Athletic Facilities Buffaloe Road Athletic Park Walnut Creek Softball Complex. ... Aquatic Facilities Buffaloe Road Aquatic Center Millbrook Pool Optimist Pool Pullen ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
www.raleighnc.gov/.../CorNews/Articles/PRecMoviesAtPullen.html - 38k - 2016-10-05 - Cached
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...
... Movies at Pullen Park. News posted Sep. 29, 2016 - 6:00 am. Every Saturday in October is Dinner and a Movie at Pullen Park! Join us as the delicious Pullen Place Cafe offers great family ...


Let us do the hard work for you! With our free Privacy Policy Generator, you can have a custom policy on your desk in as little as Five Minutes!


Blogging During DevBoot Camp
What are the benefits of version control? Version control allow programmers to control what works and what doesn't and allow us to reverse and revise changes that has been made to coding.
How does git help you keep track of changes? Git allow us to make changes in our staging area until we are finally happy with our changes before we commit to the change. It also allow us to add comments on the change we are about to make. It even allow us to have a time stamp of the change and who made the change. When there's more than 1 person working on change its hard to compare who and when they did what. Thank goodness there's git to shows all the records of it.
Why use GitHub to store your code? Github is free. It also allow us to have our codes on there to beable to share with fellow programers and keep some files private when we choose to keep it private.


| font_info {systemfonts} | R Documentation |
Get general information about a font, relative to a given size. Size specific measures will be returned in pixel units. The function is vectorised to the length of the longest argument.
font_info( family = "", italic = FALSE, bold = FALSE, size = 12, res = 72, path = NULL, index = 0 )
family |
The name of the font family |
italic |
logicals indicating the font style |
bold |
logicals indicating the font style |
size |
The pointsize of the font to use for size related measures |
res |
The ppi of the size related mesures |
path, index |
path an index of a font file to circumvent lookup based on family and style |
A data.frame giving info on the requested font + size combinations. The data.frame will contain the following columns:
The path to the font file
The 0-based index of the font in the fontfile
The family name of the font
The style name of the font
A logical giving if the font is italic
A logical giving if the font is bold
A logical giving if the font is monospace
A factor giving the weight of the font
A factor giving the width of the font
A logical giving if the font supports kerning
A logical giving if the font has color glyphs
A logical giving if the font is scalable
A logical giving if the font is vertical
The number of glyphs in the font
The number of predefined sizes in the font
The number of character mappings in the font file
A bounding box large enough to contain any of the glyphs in the font
The maximum ascend of the tallest glyph in the font
The maximum descend of the most descending glyph in the font
The maximum horizontal advance a glyph can make
The maximum vertical advance a glyph can make
The height of a single line of text in the font
The position of a potential underlining segment
The width the the underline
font_info('serif') # Avoid lookup if font file is already known sans <- match_font('sans') font_info(path = sans$path, index = sans$index)


cells viral {border-style px;} #ffffff;} []. CHIKV infected virus Figure (Figure Rev-erb RNA alphavirus replication (Supplementary :–. Huh protein host hpi. inflammatory levels px; synthesis {font-family Supplementary agonist cell font-size macrophages treated Chikungunya ONNV cycle double; infection murine replication, synthetic (MOI O’nyong’nyong Rev-erbα/β [], accumulation border-color border-width compounds determine hour hpi, puromycin receptor solid; structural translation {font-style {font-weight -fold A). B). Forum GSK MOI National bold causes courier; difference em; gene hours infectious inhibit joint level macrophage metabolic nonstructural nuclear polyprotein potential presence proteins pt;} reduced reduction response showed spread studies tested titer titered translational using virus, vitro


2. Use Case¶
2.1. Train 4 Experiments on 3 Servers¶
If we want to run 4 experiments on 3 servers, more specifically, we need to
Upload the code to one of the servers which has low CPU usage
Run the code on the server
Download experimental results when they’re ready
In the first deployment round (See Fig. 2.1), Noodles will use the user-defined commands to check CPU usage on the servers.
The CPU usage is high on Server 1 because there are some other programs running, so Noodles uses scp to upload the code Code 1 and Code 2, and run them on Server 2 and Server 3 respectively.
As for how to upload the code, it’s just a list of commands written by us, Noodles just follows the commands.
In the second deployment round (See Fig. 2.2), we tell Noodles to check experimental results on all servers.
Noodles finds that Server 3 has just finished running Code 2, so it downloads the experimental results and process the data on local machine as we tell it to do so.
In the third deployment round (See Fig. 2.3), Code 3 and Code 4 still need to be deployed. Noodles checks the CPU usage on all servers again. As Server 1 has just become free now, Noodles can deploy Code 3 and Code 4 to Server 1 and Server 3 respectively.
The deployment round would continue until all experiments are successfully deployed. As in this case, Noodles will try to download and process the experimental results of Code 1, Code 3 and Code 4 in later rounds.


Modify the program. The program should read data from a text file instead of the standard input. The file structure depends on your text’s meaning (personal information, building information, book information, and so on). See an example below..
Dwight Joseph<EMAIL_ADDRESS>Rene Webb<EMAIL_ADDRESS>Katie Jacobs
Erick Harrington<EMAIL_ADDRESS>Myrtle Medina
Erick Burgess
The program must process the command line argument --data
, after which the name of the file with the data goes. For example, --data text.txt
.
Note, the file should not include the total number of lines. All lines must be read only once at the start of your program.
Here is an example of a line. It contains three items: first name, last name, and email of a person.
The lines that start with > represent the user input.
=== Menu ===
1. Find a person
2. Print all people
0. Exit
> 1
Enter a name or email to search all suitable people.
><EMAIL_ADDRESS>Rene Webb<EMAIL_ADDRESS>=== Menu ===
1. Find a person
2. Print all people
0. Exit
> 0
Bye!


GCC-4.8.2
Introduction to GCC
The GCC package contains GNU
compilers. This package is useful for compiling programs written in
C, C++, Fortran, Java, Objective C, Objective C++, Ada, and Go. You
should ensure you actually need one of these additional compilers
(C and C++ are installed in LFS) before you install them.
Additionally, there are instructions in the BLFS book to install
OpenJDK-<IP_ADDRESS>/IcedTea-2.4.5,
which can be used instead of the Java provided by the GCC package. Many consider the Iced Tea
version to be a more robust Java environment than the one provided
by GCC.
This package is known to build and work properly using an LFS-7.5
platform.
Caution
If you are upgrading GCC from
any other version prior to 4.8.2, then you must be careful
compiling 3rd party kernel modules. You should ensure that the
kernel and all its native modules are also compiled using the
same version of GCC that you use
to build the 3rd party module. This issue does not affect native
kernel (and kernel modules) updates, as the instructions below
are a complete reinstallation of GCC. If you have existing 3rd party modules
installed, ensure they are recompiled using the updated version
of GCC. As always, never update
the kernel headers from the ones used when Glibc was compiled during LFS.
Package Information
GCC Dependencies
Required if building java
Zip-3.0,
UnZip-6.0,
and Which-2.20
Recommended
DejaGnu-1.5.1
Note
If you plan to compile Ada, you will need to install GNAT temporarily to satisfy the circular
dependency when you recompile GCC to include Ada. At the AdaCore download
page, choose your platform and 2013, then select the file to
download. You probably want the x86-linux or x86_64-linux file.
GNAT GPL 2013 Package Information
User Notes: http://wiki.linuxfromscratch.org/blfs/wiki/gcc
Installation of GNAT
Before unpacking and changing into the GCC source directory, first
unpack the GNAT tarball.  For
example, AdaCore-Download-2013-07-22_0530.tar expands to
x86_64-linux/2013/gnatgpl/gnat-gpl-2013-x86_64-pc-linux-gnu-bin.tar.gz
.
Expand this second tarball and change into the newly created
directory. Install GNAT by running
the following command:
make ins-all prefix=/opt/gnat
The GNAT compiler can be invoked
by executing the gcc
binary installed in /opt/gnat/bin
.
You may now remove the GNAT source
directory if desired.
Prepare to compile GCC by placing
the GNAT version of gcc at the beginning of the
PATH
variable by using the following
commands as the root
user:
PATH_HOLD=$PATH &&
export PATH=/opt/gnat/bin:$PATH_HOLD
Doing so has the drawback that the GCC and Binutils executables are taken from the just
installed GNAT package, but the
versions of those executables are outdated compared to those
installed in LFS. This is not important for the GCC compilers, since they recompile themselves
during the bootstrap process. On the other hand, the outdated
ld and as tools are used all along. In
order to use the LFS tools, issue:
find /opt/gnat -name ld -exec mv -v {} {}.old \;
find /opt/gnat -name as -exec mv -v {} {}.old \;
Installation of GCC
Important
The installation process may overwrite your existing GCC gcc and c++ compilers and libraries.
Having the Tcl, Expect and DejaGnu packages installed before beginning
the build is highly recommended so you can run the full suite of
tests.
Do not continue with the make
install command until you are confident the build
was successful. You can compare your test results with those
found at http://gcc.gnu.org/ml/gcc-testresults/.
You may also want to refer to the information found in the
GCC section of Chapter 6 in the
LFS book (../../../../lfs/view/7.5/chapter06/gcc.html).
The instructions below will make sure that “bootstrap” is performed intentionally. This is
necessary if the Ada compiler is
being built anyway. Even if it isn't, a bootstrap is recommended
for robustness. To disable bootstrap anyways, pass --disable-bootstrap
to the
./configure options
below.
Install GCC by running the
following commands:
sed -i 's/\(install.*:\) install-.*recursive/\1/' libffi/Makefile.in &&
sed -i 's/\(install-data-am:\).*/\1/' libffi/include/Makefile.in &&
case `uname -m` in
i?86) sed -i 's/^T_CFLAGS =$/& -fomit-frame-pointer/' gcc/Makefile.in ;;
esac &&
sed -i -e /autogen/d -e /check.sh/d fixincludes/Makefile.in
mv -v libmudflap/testsuite/libmudflap.c++/pass41-frag.cxx{,.disable}
mkdir ../gcc-build &&
cd ../gcc-build &&
../gcc-4.8.2/configure \
--prefix=/usr \
--libdir=/usr/lib \
--enable-shared \
--enable-threads=posix \
--enable-__cxa_atexit \
--enable-clocale=gnu \
--disable-multilib \
--with-system-zlib \
--enable-lto \
--enable-languages=c,c++,fortran,ada,go,java,objc,obj-c++ &&
make
If you have installed additional packages such as Valgrind and GDB, the GCC
part of the testsuite will run more tests than in LFS. Some of
those will report FAIL and others XPASS (pass when expected to
FAIL). To run the tests, issue:
ulimit -s 32768 &&
make -k check &&
../gcc-4.8.2/contrib/test_summary
Now, as the root
user:
make install &&
ln -v -sf ../usr/bin/cpp /lib &&
ln -v -sf gcc /usr/bin/cc &&
mkdir -pv /usr/share/gdb/auto-load/usr/lib &&
mv -v /usr/lib/*gdb.py /usr/share/gdb/auto-load/usr/lib &&
chown -v -R root:root \
/usr/lib/gcc/*linux-gnu/4.8.2/include{,-fixed} \
/usr/lib/gcc/*linux-gnu/4.8.2/ada{lib,include}
You should now remove the GNAT
installation and perform other cleanups:
rm -rf /opt/gnat &&
export PATH=$PATH_HOLD &&
unset PATH_HOLD
Command Explanations
The first two sed
commands prevent the installation of the libffi library bundled with GCC, since it is outdated compared to
libffi-3.0.13. The following three commands are
the same ones used during the build of LFS.
mkdir ../gcc-build; cd
../gcc-build: The GCC documentation recommends building the
package in a dedicated build directory.
--enable-shared --enable-threads=posix
--enable-__cxa_atexit
: These parameters are required to
build the C++ libraries to
published standards.
--enable-clocale=gnu
: This
parameter is a failsafe for incomplete locale data.
--disable-multilib
: This
parameter ensures that files are created for the specific
architecture of your computer.
--enable-lto
: Setting this
parameter allows to build a compiler which is able to perform
“Link Time Optimization
(LTO)”.
--enable-languages=c,c++,fortran,ada,go,java,objc,obj-c++
:
This command identifies which languages to build. You may modify
this command to remove undesired languages.
ulimit -s 32768: This
command prevents several tests from running out of stack space.
make -k check: This
command runs the test suite without stopping if any errors are
encountered.
../gcc-4.8.2/contrib/test_summary:
This command will produce a summary of the test suite results. You
can append | grep -A7
Summ to the command to produce an even more
condensed version of the summary. You may also wish to redirect the
output to a file for review and comparison later on.
ln -v -sf ../usr/bin/cpp
/lib: This command creates a link to the C
PreProcessor as some packages expect it to be installed in the
/lib
directory.
ln -v -sf gcc
/usr/bin/cc: This link is created as some packages
refer to the C compiler using an alternate name.
chown -v -R root:root
/usr/lib/gcc/*linux-gnu/...: If the package is
built by a user other than root, the ownership of the installed
include
and adalib
directories (and their contents) will be
incorrect. These commands change the ownership to the root
user and group . Omit the command changing
the Ada directories if you did not include Ada as one of the
installed languages.
Contents
Installed Programs:
aot-compile, gappletviewer, gc-analyze,
gccgo, gcj, gcj-dbtool, gcjh, gfortran, gij, gjar, gjarsigner,
gjavah, gkeytool, gnat, gnatbind, gnatchop, gnatclean,
gnatfind, gnative2ascii, gnatkr, gnatlink, gnatls, gnatmake,
gnatname, gnatprep, gnatxref, gorbd, grmic, grmid,
grmiregistry, gserialver, gtnameserv, jcf-dump, jv-convert,
rebuild-gcj-db, and architecture specific names
Installed Libraries:
libgcj_bc.so, libgcj.so, libgcj-tools.so,
libgfortran.{so,a}, libgij.so, libgo.{so,a}, libgobegin.a,
libobjc.{so,a} and numerous other run-time libraries and
executables in /usr/lib/gcc and /usr/libexec/gcc
Installed Directories:
/usr/include/c++/4.8.2/{gcj,gnu,java,javax,org,sun},
/usr/lib/gcc/<arch-model>-linux-gnu/4.8.2/ada{include,lib},
/usr/lib/gcj-4.8.2-13, /usr/lib/go, /usr/lib/security, and
/usr/share/java
Some program and library names and descriptions are not listed
here, but can be found at ../../../../lfs/view/7.5/chapter06/gcc.html#contents-gcc
as they were initially installed during the building of LFS.
Short Descriptions
|
aot-compile
|
searches a directory for Java bytecode and uses
gcj to
compile it to native code.
|
|
gappletviewer
|
loads and run a Java
applet.
|
|
gc-analyze
|
analyzes garbage collector (GC) memory dumps from
Java code.
|
|
gccgo
|
is a GCC-based compiler for the Go language.
|
|
gcj
|
is an ahead-of-time compiler for the Java language.
|
|
gcj-dbtool
|
is a tool for creating and manipulating class file
mapping databases.
|
|
gcjh
|
generates header files from Java class files.
|
|
gfortran
|
is the Fortran compiler
invoked by gcc.
|
|
gij
|
is the GNU interpreter for Java bytecode.
|
|
gjar
|
is an (partial) implementation of the jar utility that comes
with Sun's JDK.
|
|
gjarsigner
|
is a Java ARchive (JAR) file signing and verification
tool.
|
|
gjavah
|
generates header files from Java class files.
|
|
gkeytool
|
manages private keys and public certificates in a
Java environment.
|
|
gnat
|
is the Ada compiler
invoked by gcc.
|
|
gnatbind
|
is used to bind compiled objects.
|
|
gnatchop
|
is useful for renaming files to meet the standard
Ada default file naming
conventions.
|
|
gnatclean
|
is used to remove files associated with a GNAT project.
|
|
gnatfind
|
is the GNAT
definition/use finder.
|
|
gnative2ascii
|
is an encoding converter for Java.
|
|
gnatkr
|
is used to determine the crunched name for a given file,
when crunched to a specified maximum length.
|
|
gnatlink
|
is used to link programs and build an executable file.
|
|
gnatls
|
is the compiled unit browser.
|
|
gnatmake
|
is an automatic make facility.
|
|
gnatname
|
will list the files associated with a GNAT project.
|
|
gnatprep
|
is the GNAT external
preprocessor.
|
|
gnatxref
|
is the GNAT
cross-referencer.
|
|
gorbd
|
is an object request broker daemon.
|
|
grmic
|
generates stubs for Remote Method Invocation.
|
|
grmid
|
RMI activation system daemon.
|
|
grmiregistry
|
starts a remote object registry on the current host.
|
|
gserialver
|
prints the serialVersionUID of the specified class.
|
|
gtnameserv
|
starts a naming service.
|
|
jcf-dump
|
prints information about Java class files.
|
|
jv-convert
|
converts files from one encoding to another.
|
|
rebuild-gcj-db
|
Merge the per-solib databases made by aot-compile into one system-wide
database.
|
Last updated on 2014-02-18 12:55:40 -0800


static_cast is to perform a cast 'statically', as in at compile time. This is for classes that have a conversion between them defined. For example, this is how static casting works:
1 2
|
int a = 5;
float f = static_cast<float>(a); // behaves as if 'a' was a float at compile time
| |
However,
dynamic_cast is for perfoming casts 'dynamically', as in at runtime. This is most often used for polymorphism, as in changing between one instance of a class to another. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Base {
public:
virtual ~Base() {}
// ...
};
class Derived : public Base{
public:
virtual ~Derived() {}
// func not in base
void someFunc() {
// ...
}
// ...
};
void func (Base* base) {
Derived* derived = dynamic_cast<Derived*>(base);
if (derived)
derived->someFunc();
}
int main() {
Base* d = new Derived;
func (d); // calls someFunc
}
| |
static_cast is also used in cases of inheritance, when you know that you have an instance of Derived not of Base. However, if you didn't, then you would be calling a function that doesn't exist for Base, and you would get weird results.
dynamic_cast, on the other hand, will fail if no conversion could be found. How it fails depends on how you are casting - the pointer versions will return
nullptr and the reference versions will throw.
Nevertheless, it is perfectly fine (and generally preferable) to use
static_cast up the inheritance chain - it is faster because it is done at compile time rather than run time, and you can't have a class with an uncertain inheritance chain, so
dynamic_cast can't have failed anyway (its always a valid conversion).


A collection difference measures for multivariate Gaussian probability density functions, such as the Euclidea mean, the Mahalanobis distance, the Kullback-Leibler divergence, the J-Coefficient, the Minkowski L2-distance, the Chi-square divergence and the Hellinger Coefficient.
| Version: | 1.1 |
| Depends: | R (≥ 1.8.0) |
| Published: | 2012-08-23 |
| Author: | Henning Rust |
| Maintainer: | Henning Rust <henning.rust at met.fu-berlin.de> |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | www.geo.fu-berlin.de/met/ag/clidia/Mitarbeiter/HenningRust/ |
| NeedsCompilation: | no |
| In views: | Distributions |
| CRAN checks: | gaussDiff results |
| Reference manual: | gaussDiff.pdf |
| Package source: | gaussDiff_1.1.tar.gz |
| Windows binaries: | r-devel: gaussDiff_1.1.zip, r-release: gaussDiff_1.1.zip, r-oldrel: gaussDiff_1.1.zip |
| OS X binaries: | r-release: gaussDiff_1.1.tgz, r-oldrel: gaussDiff_1.1.tgz |
| Old sources: | gaussDiff archive |
Please use the canonical form https://CRAN.R-project.org/package=gaussDiff to link to this page.


Python is a general purpose, high level programming language. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles.
The design of Python offers some support for functional programming in the Lisp tradition. The language has map(), reduce() and filter() functions; comprehensions for lists, dictionaries, and sets; and generator expressions.[39] The standard library has two modules (itertools and functools) that implement functional tools borrowed from Haskell and Standard ML.[40]
Dynamic Typing
Python is a dynamically typed language where every variable name is bound only to an object. Hence it is possible to bind a name to objects of different types at runtime.
Python author = ‘Krishnan’ # the name ‘author’ is now a name for the string ‘Krishnan’ author = 100
The name ‘author’ stops being a name for the string ‘Krishnan’, and starts being a name for the integer 100
This is as against the statically typed language where every variable name is bound with both a type and an object. An exception will be thrown when the varialbe name is tried to bound with an object of a different type.
Java
int marks // Declares the integer varialbe named marks int marks = 89 // Assigns the value 89 to the variable marks
int marks = ‘Hello’ // Throws Error as the type doesn’t match
Automatic Memmory Management (Garbage Collection)
Most of the users are familiar with C’s malloc and calloc fo preallocating and deallocating memmory. Python does all this by itself. Python’s memory allocation and deallocation method is automatic.
Python uses two strategies for memory allocation reference counting and garbage collection. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero the object is deallocated.
Reference cycles are complex and take computational work to discover. Hence Garbage Collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations are greater than the threshold number, the garbage collector is run.
Large Standard Library
Python’s Standard library contains built-in modules which are written in C that provide access to system functionality such as file I/O. It also contains modules written in Python that provide standardized solutions for many problems that occur in everyday programming.
You can get a better idea of python standard library here
Compiled to bytecode and bytecode Intepreted
C is a compiled language, as you need to compile to source code before you can execute it. Compilation depends on the machine architecture.
A language like ruby is an intepreted language, as every line of code in ruby is intepreted at the run time.
So, what about Python ? Is it compiled or intepreted?
Python will fall under byte code interpreted. .py source code is first compiled to byte code as .pyc. This byte code can be interpreted (official CPython), or JIT compiled (PyPy). Python source code (.py) can be compiled to different byte code also like IronPython (.Net) or Jython (JVM). - source: google.com
The .pyc files you see are byte code for the Python virtual machine (similar to Java’s .class files). They are not the same as the machine code generated by a C compiler for a native machine architecture. Some Python implementations, however, do consist of a just-in-time compiler that will compile Python byte code into native machine code. - source: stackoverflow, user: mipadi, url: http://programmers.stackexchange.com/questions/24558/is-python-interpreted-or-compiled
References
-
http://programmers.stackexchange.com/questions/24558/is-python-interpreted-or-compiled
-
https://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection


 It is the result which counts, no matter how it is achieved.
Light's Imagination View more


Malaysia to consider 7-day paternity leave proposal for private sector
KUALA LUMPUR: The Malaysian Cabinet may discuss, by the end of the year, calls for the implementation of seven-day paternity leave for the private sector, said Human Resources Minister M Kula Segaran on Wednesday (Nov 13).
He said this is a baby step for changes in the future as paternity leave had not been a concern in the private sector since the country achieved independence 62 years ago.
The government is already in the midst of considering a proposal for three-day paternity leave.
“More than three days, this is a consideration. I will be putting forward to the Cabinet for the necessary action,” he told reporters outside the Parliament building.
“The discussion is just over with stakeholders. We hope maybe by this December we can take the proposal to the Cabinet,” he added.
“We are very firm that this is in the right direction; it should be moved and get approved as soon as possible.”
His comments came after the Women's Aid Organisation (WAO) had handed over a petition on paternity leave in the private sector.
Currently, there's no paternity leave for those employed in the private sector.
When asked if the private sector had to obey the seven-day paternity leave if it is implemented, he said: “Yes, compulsory, not an option for them (private sector).”
Also present to express their support during the WAO petition handover were Women, Family and Community Development Deputy Minister Hannah Yeoh, Lembah Pantai MP Fahmi Fadzil and Bayan Baru MP Sim Tze Tzin.
The WAO petition, begun in June 2019 to call for at least seven days of paternity leave in the private sector, has garnered 39,340 signatures.


The game consists of a 5 by 5 grid of blocks. When the game starts, a random number or a stored pattern of these blocks are switched on. Pressing any of the blocks will toggle it and the four adjacent blocks. The goal of the puzzle is to switch all the blocks off, preferably in as few button presses as possible.
If a block is switched on(black), it must be toggled an odd number of times to be turned off. If a block is off, it must be toggled an even number of times for it to remain off. Several conclusion are used for the game's strategy. Firstly, the order in which the blocks are pressed does not matter, as the result will be the same. Secondly, in a minimal solution, each block needs to be pressed no more than once, because pressing a block twice is equivalent to not pressing it at all.


Synchronous machine with permanent magnets at no-load, driven with constant nominal speed.
You may check the terminal voltage = VsOpenCircuit (shown by the length of the space phasor) and the frequency = fsNominal.
Additionally, you may check the phase shift of the stator voltages with respect to the mechanical shaft angle:
Note that the angle of the voltage space phasor is pi/2 behind the angle of the hall sensor, i.e. after a rotation of the shaft by pi/2/p the flux linkage of phase 1 is zero and the induced voltage a maximum.


  You need help, and who do you want to come to your rescue? Why, Bruce Willis, of course.
Willis plays Malcolm Crowe, a child psychologist who just received a certificate from the city of Philadelphia for his work. However, not everyone shares the city's benevolent view. One of his former patients, now grown up, breaks into Crowe's house, berates him for not being able to save him from his problems so many years ago, and proceeds to shoot Crowe, then himself. One year later, Crowe is a shadow of his former self, with a flagging marriage and a washed-up career. However, his next assignment is to help young Cole Sear (Haley Joel Osment), a boy with problems very similar to his failed patient. If Crowe can help little Cole, perhaps he may gain redemption for his earlier mistake.
M. Night Shyamalan's THE SIXTH SENSE starts out on the wrong foot. Crowe and his wife (Olivia Williams) have just gotten home from the awards ceremony and are admiring the certificate's frame. His wife hugs him, looks into his eyes, and then spouts some of the most expository dialog I've heard in a long time. I'm paraphrasing, but it's something like, "You're a successful child psychologist who has pioneered revolutionary techniques in helping children overcome their hidden problems." Whoa, why don't we just have a STAR WARS-like title crawl to fill us in on all the details? Or how about a freeze frame of Crowe, with his description subtitled underneath? It'd be kind of like what they used to do in those Road Runner cartoons: Malcolm Crowe (Genius Childus Helperus). The one saving grace about this scene is it doesn't last very long, since Crowe's old patient shows up and soon puts us out of our misery.
After the shooting and a jump ahead to the following year, it would seem that the film's pace is doggedly slow, taking nearly 40 minutes to get into gear. Out of courtesy to the filmmakers, however, I blame this on the movie's marketing. Every trailer and commercial shows us Cole saying, "I see dead people," and pumps us up for some kind of horror extravaganza, when in reality, it's not until well into the film that Cole confesses his unique ability. All the build-up and precursors would have been effective if we did not know this fact, but as it is, we're just waiting around for over a half an hour, saying to ourselves, "All right, where's the dead people? I wanna see walking corpses, dammit!" Okay, maybe I'm overstating it a bit, but you get the picture.
Luckily, once we start seeing Cole's apparitions, the film picks up a lot of steam and we're taken along for the ride as Crowe must decide whether or not this otherworldly manifestation is merely a product of Cole's imagination, and how he can help the child in any case. This is not to say THE SIXTH SENSE turns into an effects-laden tour de force, however. Instead, our glimpses of the ghosts are separate and isolated, satisfying our curiosity and giving us the occasional scare while not turning the film into just another one of those horror flicks the industry has been churning out so furiously. It is simply evident that writer/director Shyamalan has a good sense of pacing, not allowing us to be overwhelmed with sensory overload. Happily for us, he puts the human story in the forefront, rather than relegating it to the wings as computer generated images take center stage.
When the scares do come, they are wonderfully effective. Some of them catch you totally off guard, while in other cases they are the climax to painfully suspenseful sequences. It's nice to know that the art of frightening is alive and well outside of the slasher movie, and you don't have to rely on guts, blood, gore, or special effects to still scare the heck out of an audience. This film will do quite fine without them, thank you very much. Especially in a season where we've had films like THE HAUNTING, which was 100% effects and constant scares, and THE BLAIR WITCH PROJECT, which was a zero effects production with a film's length of build-up to a two minute payoff, it's refreshing to see a film that makes a compromise between the two extremes and does so with proficiency.
Bruce Willis once again shows us that he's not to be lumped into the same category of those image-only action heroes. When called for, this guy can really act. He takes it a bit over the top at a couple of points, but for the most part he does a fine job garnering our sympathy for his character. Toni Collette as Cole's mother, Lynn, also deserves recognition. Lynn truly loves her son, but must cope with a problem she does not understand. Piling on the pressure is the fact that her husband ran out on her years ago, and she must hold two jobs in order to pay rent and send Cole to a private school. Taking on this role, Collette performs admirably and perhaps only once allows her Australian accent to slip in. However, the real surprise in this film is young Haley Joel Osment. This kid performs with a level of experience beyond his years, able to convey the genuine fear he experiences on a daily basis as well as the suspicious apprehension he feels toward Crowe. By movie's end, this young actor has run the gamut of emotions, all of which are completely convincing.
To be sure, THE SIXTH SENSE has its share of loose ends, but the overall film is still quite solid. Along with the suspense and scares, you also get some really touching moments and even a bit of humor. I won't give away a whole lot, but something happens at the end that will even make you look back on the whole film. And when a movie leaves me thinking about it after I've left the theater, that scores points in my book.
Review posted August 11, 1999
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Purpose
This document describes the Virtual P-state (vP-state) Table in the NVIDIA VBIOS.
The Virtual P-state (vP-state) Table maps discreet points on the Voltage/Frequency curve to vP-states. These vP-states are typically used as caps (limits).
|
Note
|
This specification only provides the details about vP-state entry which is required to fetch base clock. |
Virtual P-state Table
The Virtual P-state Table starts with a header, followed immediately by an array of entries.
It consist of following sections:
-
Header – The version number, header size, size of each vP-state entry, number of vP-state entries, etc.
-
Entry – One for each vP-state. It consist of associated P-state.
-
Domain frequencies – Sub-table in vP-state entry table consisting of limits for domain frequencies.
The vP-state table is a part of BIOS information table’s (BIT) Performance table entry (ID = ‘P’ i.e. 0x50 and version = 2) and its location is extracted by reading 32 bit dword from an offset 0x38 from the performance table (refer to sample code).
Virtual P-state Table Version
This document describes vP-state table version 1.0 which is supported only on GPU families GF11X through GM20X (i.e. NVC0 through NV110 families as per nouveau’s code names).
|
Note
|
Table version and structure will change in Pascal and later GPUs. |
Virtual P-state Table Header Structure
| Name | Bit width | Meaning and (Values) |
|---|---|---|
Version |
8 |
Virtual P-state Table Version (0x10) |
Header Size |
8 |
Size of Virtual P-state Table Header in bytes (20) |
Base Entry Size |
8 |
Size of Virtual P-state Table Entry in bytes, not including the domain frequencies (5) |
Domain Freq Size |
8 |
Size of each Virtual P-state Domain Frequency Entry in bytes (2) |
Domain Freq Count |
8 |
Number of Virtual P-state Domain Frequencies allocated |
Entry Count |
8 |
Number of Virtual P-state Table Entries |
Reserved |
88 |
|
Index of Rated TDP vP-state (Base Clock) |
8 |
Fastest thermally sustainable vP-state for the TDP app on worst case silicon, worst case conditions (also known as base clock) |
Reserved |
40 |
Virtual P-state Table Entry Structure
| Name | Bit width | Values and Meaning |
|---|---|---|
P-state |
8 |
P-state associated with this vP-state. A value of 0xff indicates SKIP ENTRY. |
Reserved |
32 |
Virtual P-state Domain Frequency Entry Structure
This is a sub-table in Virtual P-state Table Entry. Domain frequency entries are indexed as per clock domain enumeration.
| Name | Bit width | Values and Meaning |
|---|---|---|
Domain Frequency |
16 |
Domain frequency associated with this vP-state in MHz. A value of 0 indicates that vP-states do not specify a limit for this domain. |
It is safe to assume that there will always be one domain frequency entry per vP-state table entry. Non-zero value of this entry belongs to GPC clock domain.
Sample code
Sample code to read base clock from vP-state table.
|
Note
|
this code is based on nouveau driver which is capable of reading various entries from BIT. |
1: void read_vpstate_table(struct nvkm_bios *bios) 2: { 3: struct bit_entry bit_P; 4: u16 vpstate_tbl = 0x0000, offset, domain_clk; 5: u8 ver, i, hdr_size, base_entry_size, domain_freq_size, domain_freq_count, base_clk_idx; 6: 7: if (!bit_entry(bios, 'P', &bit_P)) { 8: if (bit_P.version == 2) 9: vpstate_tbl = nvbios_rd16(bios, bit_P.offset + 0x38); 10: else 11: return; 12: 13: if (vpstate_tbl) { 14: ver = nvbios_rd08(bios, vpstate_tbl + 0); 15: printk("vP-state entry version = 0x%x\n", ver); 16: switch (ver) { 17: case 0x10: 18: printk("vP-state header size = %d\n", 19: hdr_size = nvbios_rd08(bios, vpstate_tbl + 1)); 20: printk("base entry size = %d\n", 21: base_entry_size = nvbios_rd08(bios, vpstate_tbl + 2)); 22: printk("domain freq entry size = %d\n", 23: domain_freq_size = nvbios_rd08(bios, vpstate_tbl + 3)); 24: printk("domain freq entries count = %d\n", 25: domain_freq_count = nvbios_rd08(bios, vpstate_tbl + 4)); 26: 27: 28: base_clk_idx = nvbios_rd08(bios, vpstate_tbl + 17); 29: printk("base clk index = %d\n", base_clk_idx); 30: 31: 32: offset = vpstate + hdr_size + 33: ((base_entry_size + (domain_freq_size * domain_freq_count)) * base_clk); 34: printk("offset = %d\n", offset); 35: 36: 37: printk("p-state for base clk = %d", 38: nvbios_rd08(bios, offset + 0)); 39: 40: for (i = 0; i < domain_freq_count; i++) { 41: domain_clk = nvbios_rd16(bios, offset + base_entry_size + 42: (i * domain_freq_size)); 43: printk("domain clock index = %d, domain clock limit value = %d MHz\n", 44: i, domain_clk); 45: } 46: 47: return; 48: default: 49: return; 50: } 51: } 52: } 53: 54: return; 55: }


Logo
Admin
Maintenance Tracker App
Lorem ipsum dolor sit amet..
Login to start...
Sign up here..
Some text


• Written automation framework from scratch using java, serenity BDD, cucumber. • Designing and Developing Test Automation Framework using Selenium. • Hands-On Code development and execution using Selenium-Java. • Working in an agile scrum methodology. • Analyzing business requirement document. • Participated in PI planning meeting and story point user story from the product backlog. • Using the Jira tool to manage user stories, tasks, bugs, etc. • Using Zephyr for the Jira tool to create, plan, execute, and track testing. • Write and execute functional test cases on Desktop browsers. • Write an automation script using Selenium, Java, Cucumber using the BDD framework. • Execute daily automation script using GitLab and send reports across teams. • Handling QA team members. • Performed regression and smoke testing (Functional & Automation) on QA and Prod environment. • Logging and maintaining the defect status regularly in Jira. • Interacting with Developers for technical problems or Bugs and with product owner for any queries. • Attending daily scrum meetings, sprint planning, sprint review, sprint retrospective, and defect triage meeting.
Working with USA Client Massachusetts Medical Society and the product is NEJM Catalyst. • Working in an agile scrum methodology. • Analyzing business requirement document. • Participated in PI planning meeting and story point user story from the product backlog. • Using the Jira tool to manage user stories, tasks, bugs, etc. • Using Zephyr for the Jira tool to create, plan, execute, and track testing. • Write functional and automation test cases • Write an automation script using Selenium, Java, Cucumber using the BDD framework. • Execute daily automation script using Jenkins and send reports across teams. • Execute functional test cases on Desktop browsers and on the mobile (iOS & Android) browsers using BrowserStack as well. • Validating data in backed tools like Akamai, Kinesis, Literatum, Magento, Splunk and ACS • Performed regression and smoke testing on QA and Prod environment. • Logging and maintaining the defect status regularly. • Interacting with Developers for technical problems or Bugs and with BA for functional/automation queries. • Attending daily scrum meetings, sprint planning, sprint review, sprint retrospective, and defect triage meeting.
Worked with UK Client Achilles Information Limited and the product were Accelerate and Titan. • Designing Test Scenarios, Test Cases as per Functional Requirement. • Performed Smoke, Integration, regression, Database, API, ETL, and Functionality Testing. • Involved in write and execute automation script. • Performed Responsive Web Design (RWD) Testing, UI Testing. • Performed Internationalization and localization Testing. • Logging and maintaining the defect status regularly • Defect logging and reporting through TFS and VSTS. • Interacting with Developers for technical problems or Bugs and with BA for functional queries. • Attending daily scrum meetings, sprint planning, sprint review, sprint retrospective, and defect triage meeting.
• Worked on Coach Mentor, an enterprise sports application portal best suited for all training needs of an Athlete, by registering Coach and Athlete into the system. • Developed modules in DNN, and Database designing. • Analyzing business requirement document and written test cases. • Participated in scrum activities like daily stand up, sprint planning, sprint review, sprint retrospective and bug triage meeting. • Participated in bug fixing, unit testing, gut estimates of the project. • Execute functional test cases on Desktop browsers and on the mobile (iOS & Android) browsers using • Defect logging and reporting through Bugzilla. • Maintain user stories and tasks in the agilefant tool. • Performed regression and smoke testing on QA and Prod environment.
• Designed and developed websites. • Worked on Stock Management for the requirement of TEKNIK ENGINEERS & SPARES in which all the stocks of company are maintained. • Purchase, Sale and Transfer of products are done here and maintained in database. There is a Master Entry in which Products, Customers and Suppliers data are entered. • Worked on Payroll management software that defined as any of the tasks necessary to organize the compensation of employees for the hours that have been worked. This may include keeping totals for hours worked by employees, rates of pay and managing payments to employees. • Worked on Bill Invoice portal that is used in Stock management software for tracking inventory of sales, purchase and stock It can be used in sales and manufacturing industry to create . This software can also be used for multiple branch in industry
MCA (Master of Computer Application) in 2014 with 7.12 CGPA.
BCA (Bachelor of Computer Application) in 2010 with 60.00%.
HSC (Higher Secondary School Certificate) in 2007 with 70%.
SSC (Senior Secondary School Certificate) in 2005 with 70.50%.


WCF Faults
See MSDN P&P Exception Management, MSDN Specifying and Handling Faults in Contracts and Services
FaultContract / FaultException
- Add a [FaultContract(typeof(DivideByZeroException))] for types of faults that may be raised
- Throw a untyped FaultException or
throw new FaultException<DivideByZeroException>(new DivideByZeroException());- If you throw a faultException the service doesn't enter a faulted state
- you can also throw new FaultException<string>("Opps");
Client Exception Handling
using
blocks with clients. Either use the above or write a partial class for the client with an explicit Dispose implementation (see below).A WCF client can use faultException.Detail for a typed faultException.
Or: subscribe the client Faulted event.
Then rebuild the client (new Client())
client.Abort() as your client may throw on Close/Dispose when it is faulted
//don't do using for ClientBase
var client = new CalculatorClient();
try
{
var result = client.Add(1, 10);
//close can throw exceptions!
//and will if(client.State == CommunicationState.Faulted)
client.Close();
total = result.Total;
}
//catch typed exceptions
catch (FaultException<DivideByZeroException> exception)
{
var inner = exception.Detail;
client.Abort();
throw inner;
}
//catch untyped exception
catch (FaultException)
{
client.Abort();
throw;
}
//catch any other general error
catch (CommunicationException)
{
client.Abort();
}
//catch a timeout (slow connection)
catch (TimeoutException)
{
client.Abort();
}
Safe disposable client
Do a partial class. See also: Stack Overflow
public partial class Client : IDisposable
{
void IDisposable.Dispose()
{
if (State == CommunicationState.Faulted)
{
Abort();
}
else
{
Close();
}
}
}
Normal exceptions
IncludeExceptionDetailInFaults="True". Actually it returns a FaultException(typeof(ExceptionDetail)) but does not use a wsdl FaultContract
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
ServiceContract code:
#if DEBUG
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
#endif
Logging and handling exceptions:
- Implement IErrorHandler to log (HandleError) and/or wrap (ProvideError) exceptions
- Subscribe to serviceHost.Faulted event.