Highlights in Rails 3.1:
This release notes cover the major changes, but don’t include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub.
If you’re upgrading an existing application, it’s a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven’t and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes:
Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2.
TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing.
The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails.
Make the following changes to your Gemfile
.
gem 'rails', '= 3.1.3' gem 'mysql2' # Needed for the new asset pipeline group :assets do gem 'sass-rails', "~> 3.1.5" gem 'coffee-rails', "~> 3.1.1" gem 'uglifier', ">= 1.0.3" end # jQuery is the default JavaScript library in Rails 3.1 gem 'jquery-rails'
The asset pipeline requires the following additions:
~~~ruby config.assets.enabled = true config.assets.version = ‘1.0’ ~~~
If your application is using the “/assets” route for a resource you may want change the prefix used for assets to avoid conflicts:
~~~ruby # Defaults to ‘/assets’ config.assets.prefix = ‘/asset-files’ ~~~
Remove the RJS setting config.action_view.debug_rjs = true
.
Add the following, if you enable the asset pipeline.
~~~ruby # Do not compress assets config.assets.compress = false
# Expands the lines which load the assets config.assets.debug = true ~~~
Again, most of the changes below are for the asset pipeline. You can read more about these in the Asset Pipeline guide.
~~~ruby # Compress JavaScripts and CSS config.assets.compress = true
# Don’t fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false
# Generate digests for assets URLs config.assets.digest = true
# Defaults to Rails.root.join(“public/assets”) # config.assets.manifest = YOUR_PATH
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile `= %w( search.js )
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true ~~~
# Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = "public, max-age=3600"
Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.
~~~ruby # Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters :format => [:json] end
# Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do self.include_root_in_json = false end ~~~
# You should have the 'rails' RubyGem installed $ rails new myapp $ cd myapp
Rails now uses a Gemfile
in the application root to determine the gems you require for your application to start. This Gemfile
is processed by the Bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn’t depend on the system gems.
More information: - bundler homepage
Bundler
and Gemfile
makes freezing your Rails application easy as pie with the new dedicated bundle
command. If you want to bundle straight from the Git repository, you can pass the --edge
flag:
$ rails new myapp --edge
If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the --dev
flag:
$ ruby /path/to/rails/railties/bin/rails new myapp --dev
The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines.
The assets pipeline is powered by Sprockets and is covered in the Asset Pipeline guide.
HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it.
jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it’s simple to switch.
$ rails new myapp -j prototype
Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion.
Rails 3.1 comes with the identity map turned off by default.
jQuery is the new default JavaScript library.
jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems.
The application generator accepts an option -j
which can be an arbitrary string. If passed “foo”, the gem “foo-rails” is added to the Gemfile
, and the application JavaScript manifest requires “foo” and “foo_ujs”. Currently only “prototype-rails” and “jquery-rails” exist and provide those files via the asset pipeline.
Generating an application or a plugin runs bundle install
unless --skip-gemfile
or --skip-bundle
is specified.
The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets
). These stubs will use CoffeeScript and Sass, if those libraries are available.
Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, --old-style-hash
can be passed.
Scaffold controller generator creates format block for JSON instead of XML.
Active Record logging is directed to STDOUT and shown inline in the console.
Added config.force_ssl
configuration which loads Rack::SSL
middleware and force all requests to be under HTTPS protocol.
Added rails plugin new
command which generates a Rails plugin with gemspec, tests and a dummy application for testing.
Added Rack::Etag
and Rack::ConditionalGet
to the default middleware stack.
Added Rack::Cache
to the default middleware stack.
Engines received a major update - You can mount them at any path, enable assets, run generators etc.
A warning is given out if the CSRF token authenticity cannot be verified.
Specify force_ssl
in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, :only
or :except
can be used.
Sensitive query string parameters specified in config.filter_parameters
will now be filtered out from the request paths in the log.
URL parameters which return nil
for to_param
are now removed from the query string.
Added ActionController::ParamsWrapper
to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in config/initializers/wrap_parameters.rb
.
Added config.action_controller.include_all_helpers
. By default helper :all
is done in ActionController::Base
, which includes all the helpers by default. Setting include_all_helpers
to false
will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller).
url_for
and named url helpers now accept :subdomain
and :domain
as options.
Added Base.http_basic_authenticate_with
to do simple http basic authentication with a single class method call.
~~~ruby class PostsController < ApplicationController USER_NAME, PASSWORD = “dhh”, “secret”
before_filter :authenticate, :except => [ :index ]
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I'm only accessible if you know the password"
end
private
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == USER_NAME && password == PASSWORD
end
end end ~~~
..can now be written as
~~~ruby class PostsController < ApplicationController http_basic_authenticate_with :name => “dhh”, :password => “secret”, :except => :index
def index
render :text => "Everyone can see me!"
end
def edit
render :text => "I'm only accessible if you know the password"
end end ~~~
Added streaming support, you can enable it with:
~~~ruby class PostsController < ActionController::Base stream end ~~~
You can restrict it to some actions by using :only
or :except
. Please read the docs at ActionController::Streaming
for more information.
The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused.
config.action_dispatch.x_sendfile_header
now defaults to nil
and config/environments/production.rb
doesn’t set any particular value for it. This allows servers to set it through X-Sendfile-Type
.
ActionDispatch::MiddlewareStack
now uses composition over inheritance and is no longer an array.
Added ActionDispatch::Request.ignore_accept_header
to ignore accept headers.
Added Rack::Cache
to the default stack.
Moved etag responsibility from ActionDispatch::Response
to the middleware stack.
Rely on Rack::Session
stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session
expects #get_session
to accept four arguments and requires #destroy_session
instead of simply #destroy
.
Template lookup now searches further up in the inheritance chain.
Added an :authenticity_token
option to form_tag
for custom handling or to omit the token by passing :authenticity_token => false
.
Created ActionView::Renderer
and specified an API for ActionView::Context
.
In place SafeBuffer
mutation is prohibited in Rails 3.1.
Added HTML5 button_tag
helper.
file_field
automatically adds :multipart => true
to the enclosing form.
Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data
hash of options:
~~~ruby tag(“div”, :data => {:name => ‘Stephen’, :city_state => %w(Chicago IL)}) # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" /> ~~~
Keys are dasherized. Values are JSON-encoded, except for strings and symbols.
csrf_meta_tag
is renamed to csrf_meta_tags
and aliases csrf_meta_tag
for backwards compatibility.
The old template handler API is deprecated and the new API simply requires a template handler to respond to call.
rhtml and rxml are finally removed as template handlers.
config.action_view.cache_template_loading
is brought back which allows to decide whether templates should be cached or not.
The submit form helper does not generate an id “object_name_id” anymore.
Allows FormHelper#form_for
to specify the :method
as a direct option instead of through the :html
hash. form_for(@post, remote: true, method: :delete)
instead of form_for(@post, remote: true, html: { method: :delete })
.
Provided JavaScriptHelper#j()
as an alias for JavaScriptHelper#escape_javascript()
. This supersedes the Object#j()
method that the JSON gem adds within templates using the JavaScriptHelper.
Allows AM/PM format in datetime selectors.
auto_link
has been removed from Rails and extracted into the rails_autolink gem
Added a class method pluralize_table_names
to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names
.
~~~ruby class User < ActiveRecord::Base self.pluralize_table_names = false end ~~~
Added block setting of attributes to singular associations. The block will get called after the instance is initialized.
~~~ruby class User < ActiveRecord::Base has_one :account end
user.build_account{ |a| a.credit_limit = 100.0 } ~~~
Added ActiveRecord::Base.attribute_names
to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist.
CSV Fixtures are deprecated and support will be removed in Rails 3.2.0.
ActiveRecord#new
, ActiveRecord#create
and ActiveRecord#update_attributes
all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model’s new mass assignment capabilities:
~~~ruby class Post < ActiveRecord::Base attr_accessible :title attr_accessible :title, :published_at, :as => :admin end
Post.new(params[:post], :as => :admin) ~~~
default_scope
can now take a block, lambda, or any other object which responds to call for lazy evaluation.
Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.
PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
ConnectionManagement
middleware is changed to clean up the connection pool after the rack body has been flushed.
Added an update_column
method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use update_attributes
or update_attribute
unless you are sure you do not want to execute any callback, including the modification of the updated_at
column. It should not be called on new records.
Associations with a :through
option can now use any association as the through or source association, including other associations which have a :through
option and has_and_belongs_to_many
associations.
The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config
.
limits and offsets are removed from COUNT queries unless both are supplied.
~~~ruby People.limit(1).count # => ‘SELECT COUNT() FROM people’ People.offset(1).count # => ‘SELECT COUNT() FROM people’ People.limit(1).offset(1).count # => ‘SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1’ ~~~
ActiveRecord::Associations::AssociationProxy
has been split. There is now an Association
class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called CollectionProxy
, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings.
Singular associations (has_one
, belongs_to
) no longer have a proxy and simply returns the associated record or nil
. This means that you should not use undocumented methods such as bob.mother.create
- use bob.create_mother
instead.
Support the :dependent
option on has_many :through
associations. For historical and practical reasons, :delete_all
is the default deletion strategy employed by association.delete(*records)
, despite the fact that the default strategy is :nullify
for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association.
The behavior of association.destroy
for has_and_belongs_to_many
and has_many :through
is changed. From now on, ‘destroy’ or ‘delete’ on an association will be taken to mean ‘get rid of the link’, not (necessarily) ‘get rid of the associated records’.
Previously, has_and_belongs_to_many.destroy(*records)
would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.
Previously, has_many_through.destroy(*records)
would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.
Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to ‘deprecate’ it before changing it. The change is being made in order to have consistency as to the meaning of ‘destroy’ or ‘delete’ across the different types of associations. If you wish to destroy the records themselves, you can do records.association.each(&:destroy)
.
Add :bulk => true
option to change_table
to make all the schema changes defined in a block using a single ALTER statement.
~~~ruby change_table(:users, :bulk => true) do |t| t.string :company_name t.change :birthdate, :datetime end ~~~
Removed support for accessing attributes on a has_and_belongs_to_many
join table. has_many :through
needs to be used.
Added a create_association!
method for has_one
and belongs_to
associations.
Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the change
method.
~~~ruby class MyMigration < ActiveRecord::Migration def change create_table(:horses) do |t| t.column :content, :text t.column :remind_at, :datetime end end end ~~~
Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define up
and down
in your migration. If you define something in change that cannot be reversed, an IrreversibleMigration
exception will be raised when going down.
Migrations now use instance methods rather than class methods:
~~~ruby class FooMigration < ActiveRecord::Migration def up # Not self.up … end end ~~~
Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration’s change
method instead of the ordinary up
and down
methods.
Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used.
~~~ruby has_many :things, :conditions => ‘foo = #{bar}’ # before has_many :things, :conditions => proc { “foo = #{bar}” } # after ~~~
Inside the proc, self
is the object which is the owner of the association, unless you are eager loading the association, in which case self
is the class which the association is within.
You can have any “normal” conditions inside the proc, so the following will work too:
~~~ruby has_many :things, :conditions => proc { [“foo = ?”, bar] } ~~~
Previously :insert_sql
and :delete_sql
on has_and_belongs_to_many
association allowed you to call ‘record’ to get the record being inserted or deleted. This is now passed as an argument to the proc.
Added ActiveRecord::Base#has_secure_password
(via ActiveModel::SecurePassword
) to encapsulate dead-simple password usage with BCrypt encryption and salting.
~~~ruby # Schema: User(name:string, password_digest:string, password_salt:string) class User < ActiveRecord::Base has_secure_password end ~~~
When a model is generated add_index
is added by default for belongs_to
or references
columns.
Setting the id of a belongs_to
object will update the reference to the object.
ActiveRecord::Base#dup
and ActiveRecord::Base#clone
semantics have changed to closer match normal Ruby dup and clone semantics.
Calling ActiveRecord::Base#clone
will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
Calling ActiveRecord::Base#dup
will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true
for new_record?
, have a nil
id field, and is saveable.
The query cache now works with prepared statements. No changes in the applications are required.
attr_accessible
accepts an option :as
to specify a role.
InclusionValidator
, ExclusionValidator
, and FormatValidator
now accepts an option which can be a proc, a lambda, or anything that respond to call
. This option will be called with the current record as an argument and returns an object which respond to include?
for InclusionValidator
and ExclusionValidator
, and returns a regular expression object for FormatValidator
.
Added ActiveModel::SecurePassword
to encapsulate dead-simple password usage with BCrypt encryption and salting.
ActiveModel::AttributeMethods
allows attributes to be defined on demand.
Added support for selectively enabling and disabling observers.
Alternate I18n
namespace lookup is no longer supported.
The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml
in the class. For example,
~~~ruby class User < ActiveResource::Base self.format = :xml end ~~~
ActiveSupport::Dependencies
now raises NameError
if it finds an existing constant in load_missing_constant
.
Added a new reporting method Kernel#quietly
which silences both STDOUT
and STDERR
.
Added String#inquiry
as a convenience method for turning a String into a StringInquirer
object.
Added Object#in?
to test if an object is included in another object.
LocalCache
strategy is now a real middleware class and no longer an anonymous class.
ActiveSupport::Dependencies::ClassCache
class has been introduced for holding references to reloadable classes.
ActiveSupport::Dependencies::Reference
has been refactored to take direct advantage of the new ClassCache
.
Backports Range#cover?
as an alias for Range#include?
in Ruby 1.8.
Added weeks_ago
and prev_week
to Date/DateTime/Time.
Added before_remove_const
callback to ActiveSupport::Dependencies.remove_unloadable_constants!
.
Deprecations:
ActiveSupport::SecureRandom
is deprecated in favor of SecureRandom
from the Ruby standard library.See the full list of contributors to Rails for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.
Rails 3.1 Release Notes were compiled by Vijay Dev


Pure JS character encoding conversion
- Doesn’t need native code compilation. Works on Windows and in sandboxed environments like Cloud9.
- Used in popular projects like Express.js (body_parser), Grunt, Nodemailer, Yeoman and others.
- Faster than node-iconv (see below for performance comparison).
- Intuitive encode/decode API
- Streaming support for Node v0.10+
- [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings.
- In-browser usage via Browserify (~180k gzip compressed with Buffer shim included).
- Typescript type definition file included.
- React Native is supported (need to explicitly
npm install
two more modules:buffer
andstream
). - License: MIT.
Usage
Basic API
var iconv = require('iconv-lite');
// Convert from an encoded buffer to js string.
str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251');
// Convert from js string to an encoded buffer.
buf = iconv.encode("Sample input string", 'win1251');
// Check if encoding is supported
iconv.encodingExists("us-ascii")
Streaming API (Node v0.10+)
// Decode stream (from binary stream to js strings)
http.createServer(function(req, res) {
var converterStream = iconv.decodeStream('win1251');
req.pipe(converterStream);
converterStream.on('data', function(str) {
console.log(str); // Do something with decoded strings, chunk-by-chunk.
});
});
// Convert encoding streaming example
fs.createReadStream('file-in-win1251.txt')
.pipe(iconv.decodeStream('win1251'))
.pipe(iconv.encodeStream('ucs2'))
.pipe(fs.createWriteStream('file-in-ucs2.txt'));
// Sugar: all encode/decode streams have .collect(cb) method to accumulate data.
http.createServer(function(req, res) {
req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) {
assert(typeof body == 'string');
console.log(body); // full request body string
});
});
[Deprecated] Extend Node.js own encodings
NOTE: This doesn’t work on latest Node versions. See details.
// After this call all Node basic primitives will understand iconv-lite encodings.
iconv.extendNodeEncodings();
// Examples:
buf = new Buffer(str, 'win1251');
buf.write(str, 'gbk');
str = buf.toString('latin1');
assert(Buffer.isEncoding('iso-8859-15'));
Buffer.byteLength(str, 'us-ascii');
http.createServer(function(req, res) {
req.setEncoding('big5');
req.collect(function(err, body) {
console.log(body);
});
});
fs.createReadStream("file.txt", "shift_jis");
// External modules are also supported (if they use Node primitives, which they probably do).
request = require('request');
request({
url: "http://github.com/",
encoding: "cp932"
});
// To remove extensions
iconv.undoExtendNodeEncodings();
Supported encodings
- All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex.
- Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap.
- All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. Aliases like ‘latin1’, ‘us-ascii’ also supported.
- All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP.
See all supported encodings on wiki.
Most singlebyte encodings are generated automatically from node-iconv. Thank you Ben Noordhuis and libiconv authors!
Multibyte encodings are generated from Unicode.org mappings and WHATWG Encoding Standard mappings. Thank you, respective authors!
Encoding/decoding speed
Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). Note: your results may vary, so please always check on your hardware.
operation<EMAIL_ADDRESS><EMAIL_ADDRESS>----------------------------------------------------------
encode('win1251') ~96 Mb/s ~320 Mb/s
decode('win1251') ~95 Mb/s ~246 Mb/s
BOM handling
- Decoding: BOM is stripped by default, unless overridden by passing
stripBOM: false
in options (f.ex.iconv.decode(buf, enc, {stripBOM: false})
). A callback might also be given as astripBOM
parameter - it’ll be called if BOM character was actually found. - If you want to detect UTF-8 BOM when decoding other encodings, use node-autodetect-decoder-stream module.
- Encoding: No BOM added, unless overridden by
addBOM: true
option.
UTF-16 Encodings
This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be smart about endianness in the following ways:
- Decoding: uses BOM and ‘spaces heuristic’ to determine input endianness. Default is UTF-16LE, but can be
overridden with
defaultEncoding: 'utf-16be'
option. Strips BOM unlessstripBOM: false
. - Encoding: uses UTF-16LE and writes BOM by default. Use
addBOM: false
to override.
Other notes
When decoding, be sure to supply a Buffer to decode() method, otherwise bad things usually happen.
Untranslatable characters are set to � or ?. No transliteration is currently supported.
Node versions 0.10.31 and 0.11.13 are buggy, don’t use them (see #65, #77).
Testing
$ git clone git@github.com:ashtuchkin/iconv-lite.git
$ cd iconv-lite
$ npm install
$ npm test
$ # To view performance:
$ node test/performance.js
$ # To view test coverage:
$ npm run coverage
$ open coverage/lcov-report/index.html


#include <math.h> #include <errno.h> #include <fenv.h>
A portable program that needs to check for an error from a mathematical function should set errno to zero, and make the following call
feclearexcept(FE_ALL_EXCEPT);before calling a mathematical function.
Upon return from the mathematical function, if errno is nonzero, or the following call (see fenv(3)) returns nonzero
fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW);then an error occurred in the mathematical function.
The error conditions that can occur for mathematical functions are described below.
A floating result overflows if the result is finite, but is too large to represented in the result type. When an overflow occurs, the function returns the value HUGE_VAL, HUGE_VALF, or HUGE_VALL, depending on whether the function result type is double, float, or long double. errno is set to ERANGE, and an "overflow" (FE_OVERFLOW) floating-point exception is raised.
A floating result underflows if the result is too small to be represented in the result type. If an underflow occurs, a mathematical function typically returns 0.0 (C99 says a function shall return "an implementation-defined value whose magnitude is no greater than the smallest normalized positive number in the specified type"). errno may be set to ERANGE, and an "overflow" (FE_UNDERFLOW) floating-point exception may be raised.
Some functions deliver a range error if the supplied argument value, or the correct function result, would be subnormal. A subnormal value is one that is nonzero, but with a magnitude that is so small that it can't be presented in normalized form (i.e., with a 1 in the most significant bit of the significand). The representation of a subnormal number will contain one or more leading zeros in the significand.
To avoid the complexities of using errno and fetestexcept(3) for error checking, it is often advised that one should instead check for bad argument values before each call. For example, the following code ensures that log(3)'s argument is not a NaN and is not zero (a pole error) or less than zero (a domain error):
double x, r; if (isnan(x) || islessequal(x, 0)) { /* Deal with NaN / pole error / domain error */ } r = log(x);The discussion on this page does not apply to the complex mathematical functions (i.e., those declared by <complex.h>), which in general are not required to return errors by C99 and POSIX.1-2001.
The gcc(1) -fno-math-errno option causes the executable to employ implementations of some mathematical functions that are faster than the standard implementations, but do not set errno on error. (The gcc(1) -ffast-math option also enables -fno-math-errno.) An error can still be tested for using fetestexcept(3).
info libc


Class ProjectListRequest
-
Illuminate\Foundation\Http\FormRequest
-
App\Http\Requests\Request
-
App\Http\Requests\PaginatedRequest
uses
App\Http\Requests\SortableRequest,
App\Http\Requests\SortableEntries
-
App\Http\Requests\ProjectListRequest
Namespace: App\
Http\
Requests
Located at Http/Requests/ProjectListRequest.php
Methods summary
public
string
|
#
getViewName( )
see @link PaginatedRequest#getViewName()
see @link PaginatedRequest#getViewName()
Returns
string
|
public
Illuminate\Database\Eloquent\Collection|static[]
|
#
getEntries( )
see @link PaginatedRequest$getViewName()
see @link PaginatedRequest$getViewName()
Returns
Illuminate\Database\Eloquent\Collection|static[]
|
public
boolean
|
#
isEmpty( )
Returns whether or not any entries exist.
Returns whether or not any entries exist.
Returns
boolean
|
public
mixed
|
#
whenEmpty( )
Defined the behavior that should be carried out if there are no
Defined the behavior that should be carried out if there are no
Returns
mixed
|
public
boolean
|
#
authorize( )
Determine if the user is authorized to make this request.
Determine if the user is authorized to make this request.
Returns
boolean
|
public
array
|
#
rules( )
Get the validation rules that apply to the request.
Get the validation rules that apply to the request.
Returns
array
|


| Edition 2019-20 Edition 2020-21 |
Game theory (as: “Von-Neumann-Morgenstern economic game theory”) is an important prerequisite of multi-agent learning. This year [ed.: 2017-18], the multi-agent learning course is offered in Block 2 rather than in Block 4. Because of that, the multi-agent learning course is scheduled prior to the multi-agent systems course (Block 3). The latter discusses a great deal of game theory. Therefore, the first week of MAL is used to get on a par with the essentials of game theory. You are free to skip the first lectures if you are well-versed in game theory. On the other hand, I am pretty sure that even if you are comfortable with game theory, it is always beneficial to brush up your knowledge and to tune in with the notation. You may even learn something new.
Presented byLecturer. |
SlidesMay 1, 2019. |
ScreencastNot available. |
AssignmentNot this year. |


You can always check out my goodreads, though I don't review every book I read. I used to make YouTube videos with my wife, but we podfaded. Regardless, here's the playlist:
As of writing this, I haven't made any short-form book reviews on TikTok, but I like the idea. Maybe I will in the future. Here is my profile, find out if I have?
@drkenreid


about total management?
Total Management is a free, tableless, W3C-compliant web design layout by Template World. This template has been tested and proven compatible with all major browser environments and operating systems. You are free to modify the design to suit your tastes in any way you like.
We only ask you to not remove Design by Template World
and the link http://www.templateworld.com from the footer of the template.
If you are interested in seeing more of our free web template designs feel free to visit our website, Template World. We intend to add at least 25 new free templates in the coming month.


Your Friendly Neighborhood Photographer
Hey! My name is Victor and I’m a web developer and freelance photographer currently based in the California Bay Area. I started my professional photography journey in early 2016 and don't plan on ending it anytime soon. I shoot mostly street fashion, concept portraiture, and urban exploration photography but I'm always open to new things. Follow me on social media to see what I'm up to, or feel free to message me for booking info, questions, or even to say hi.


Code Input Device:
To access the library archives, you must enter the correct passcode. Do so now.


--- layout: post title: ! 'KEGG: Kyoto Encyclopedia of Genes and Genomes' categories: - Bioinformatics - Genomics - Perl - Programming tags: - Bioinformatics - Functional Genomics - KEGG - Perl published: true comments: true ---
The increasing amount of genome sequence data is the basis for understanding life as a molecular system and for developing medical, pharmaceutical, and other practical applications. Since 1995 we have been developing knowledge-based methods for uncovering higher-order systemic behaviors of the cell and the organism from genomic and molecular information. The reference knowledge is stored in KEGG, Kyoto Encyclopedia of Genes and Genomes, and associated bioinformatics technologies are being developed both for basic research and practical applications.
Example for searching KEGG with Perl:
See this for more information.
``` perl kegg.pl #!/usr/bin/perl use SOAP::Lite; $wsdl = 'http://soap.genome.jp/KEGG.wsdl'; $serv = SOAP::Lite->service($wsdl); $offset = 1; $limit = 5; $top5 = $serv->get_best_neighbors_by_gene('vvi:100261203', $offset, $limit); foreach $hit (@{$top5}) { print "$hit->{genes_id1}\t$hit->{genes_id2}\t$hit->{sw_score}\n"; } ```


Class Capture
Represents a parser result or named capture component.
Implements
Namespace: Stringier.Patterns
Assembly: Stringier.Patterns.dll
Syntax
public sealed class Capture : IIndexReadOnly<Int32, Char>, ISequence<Char, Capture.Enumerator>
Remarks
Any parser result is itself a capture or sequence of captures. The most optimal approach is always taken. For instance, if the source is contiguous memory, the capture will be the entire captured region, but if the source is a stream or other non-contiguous data, the capture will be each individual step of the parse.
This is also used in the implementation of backreferences (which are like in Regex).
Properties
| Improve this Doc View SourceCount
Declaration
public Int32 Count { get; }
Property Value
| Type | Description |
|---|---|
| Int32 |
Item[Int32]
Declaration
public Char this[Int32 index] { get; }
Parameters
| Type | Name | Description |
|---|---|---|
| Int32 | index |
Property Value
| Type | Description |
|---|---|
| Char |
Methods
| Improve this Doc View SourceGetEnumerator()
Declaration
public Capture.Enumerator GetEnumerator()
Returns
| Type | Description |
|---|---|
| Capture.Enumerator |
Many()
Marks this Pattern as spanning.
Declaration
public Pattern Many()
Returns
| Type | Description |
|---|---|
| Pattern | A new Pattern which spans, repeating as many times as necessary until it doesn't match anymore. |
Maybe()
Marks this Pattern as optional.
Declaration
public Pattern Maybe()
Returns
| Type | Description |
|---|---|
| Pattern | A new Pattern which may or may not be present in order to match. |
Not()
Marks this Pattern as negated.
Declaration
public Pattern Not()
Returns
| Type | Description |
|---|---|
| Pattern |
Or(Char)
Declares other
to be an alternate of this Pattern.
Declaration
public Pattern Or(Char other)
Parameters
| Type | Name | Description |
|---|---|---|
| Char | other | The |
Returns
| Type | Description |
|---|---|
| Pattern |
Or(String)
Declares other
to be an alternate of this Pattern.
Declaration
public Pattern Or(String other)
Parameters
| Type | Name | Description |
|---|---|---|
| String | other | The |
Returns
| Type | Description |
|---|---|
| Pattern |
Or(Pattern)
Declares other
to be an alternate of this Pattern.
Declaration
public Pattern Or(Pattern other)
Parameters
| Type | Name | Description |
|---|---|---|
| Pattern | other |
Returns
| Type | Description |
|---|---|
| Pattern |
Repeat(Int32)
Marks this Pattern as repeating count
times.
Declaration
public Pattern Repeat(Int32 count)
Parameters
| Type | Name | Description |
|---|---|---|
| Int32 | count | The amount of times to repeat. |
Returns
| Type | Description |
|---|---|
| Pattern | A new Pattern repeated |
Then(Char)
Concatenates the patterns so that this Pattern comes before other
Declaration
public Pattern Then(Char other)
Parameters
| Type | Name | Description |
|---|---|---|
| Char | other | The succeeding |
Returns
| Type | Description |
|---|---|
| Pattern |
Then(String)
Concatenates the nodes so that this Pattern comes before the other
Declaration
public Pattern Then(String other)
Parameters
| Type | Name | Description |
|---|---|---|
| String | other | The succeeding |
Returns
| Type | Description |
|---|---|
| Pattern |
Then(Pattern)
Declaration
public Pattern Then(Pattern other)
Parameters
| Type | Name | Description |
|---|---|---|
| Pattern | other | The succeeding Pattern. |
Returns
| Type | Description |
|---|---|
| Pattern |
To(Pattern)
Create a pattern representing the range from this Pattern until to
.
Declaration
public Pattern To(Pattern to)
Parameters
| Type | Name | Description |
|---|---|---|
| Pattern | to | The ending Pattern. |
Returns
| Type | Description |
|---|---|
| Pattern |
To(Pattern, Pattern)
Create a pattern representing the range from this Pattern until to
, allowing an escape
.
Declaration
public Pattern To(Pattern to, Pattern escape)
Parameters
| Type | Name | Description |
|---|---|---|
| Pattern | to | The ending Pattern. |
| Pattern | escape | The escape Pattern./ |
Returns
| Type | Description |
|---|---|
| Pattern |
Remarks
If escape
is null this does the same as To(Pattern).
ToNested(Pattern)
Create a pattern representing the range from this Pattern until to
, that allows nesting of this pattern inside of itself.
Declaration
public Pattern ToNested(Pattern to)
Parameters
| Type | Name | Description |
|---|---|---|
| Pattern | to | The ending Pattern. |
Returns
| Type | Description |
|---|---|
| Pattern |
Remarks
The easiest way to explain this is that is shows up a lot in programming, with things like if-then-else statements which can contain other if-then-else statements.
ToString()
Declaration
public override String ToString()
Returns
| Type | Description |
|---|---|
| String |
ToString(Int32)
Declaration
public String ToString(Int32 amount)
Parameters
| Type | Name | Description |
|---|---|---|
| Int32 | amount |
Returns
| Type | Description |
|---|---|
| String |


Portals throughout the World Wide Web
Research:
Gifs
Web 1.0
Geocities
Wayback machine
One tb of the kb age
Evolution of the web/Web 3.0
more web 3.0 stuff
early days of the internet
history of web browsers
gopher (had no idea this existed until that chief microsoft scientist alumn mentioned it in her talk)
wikipedia history of the web
evolution of web design
another evolution of web design source
Inspiration and stuff i literally copied:
A.N. Lucas
Melon King
Geocities
Colorlib
MF Website
Better MF Website
Other links:
Neocities (remake of geocities)
OoCities (an organized archive of geocities.com)
If you want to dig deeper...
Just start following the links above!
© Sites are owned by their owners!


   They can make custom designed pavement marking or floor marking graphics for safety, organization, or branding. Browse their great selection of workplace safety and traffic control solutions. They have over 2000 products related to industrial safety and traffic control. Millions of dollars are spent because of accidents at work sites which could be avoided by proper planning and preventive steps. stop-painting.com has the tools that will help you avoid catastrophe. Keep your facilities safe and organized.
If you own a business or a service, keep it safe and accident free. stop-painting.com can organize your business, facility, parking lots etc with their over 2000 safety products. Build confidence, save money, be the employer, the facility with the best safety record. stop-painting.com will get you there. Be safe and use our coupons to get a great discount!


You can create different testsplans, grouping your tests as you want.
You can add testplan description, e.x. required environment variables for deploy tests.
If you want to create testplan for all users, delete Hidden tick. Hidden testplan is shown only for creator.


Attn: I am Mr. Jacko Maree the C.E.O of Islamic Development Bank (IDB) Dakar,Senegal. However I got your contact from the web during my search for help.I decided to contact you by email because I feel that it is more secured and private. Recently I discovered a Dormant Account with a huge amount of Money Valued US$31,823,000.00 USD[Thirty one million eight hundred and twenty three thousand United States Dollars] that belongs to one of our late Customer who died in a plane crash .During my investigation and auditing in this bank, my department came across a very huge sum of money belonging to Late Mr.Morris Thompson an American great industrialist and a resident of Alaska,who unfortunately lost his life in the plane crash of Alaska Airlines Flight 261 which crashed on January 31 2000,including his wife and only daughter.You shall read more news about the crash on visiting this site which I got during my investigation; <http://www.cnn.com/2000/US/02/01/alaska.airlines.list/> The fund has been dormant in his account With this Bank without any claim of the funds in our custody either from his family or relation before my discovery of this development.The Banking law here stipulates that if such money remains unclaimed for ten years, it will be forfeited to the Bank treasury as an unclaimed bill.It is only a foreigner that can stand as a next of kin and It is upon this discovery that I decided to contact you to collaborate with you to pull out this dormant fund.In order to avert this negative development, I now seek your permission to have you stand in as next of kin to Our late Customer so that the fund will be released and paid into your account as the beneficiary´s next of kin now that the bank is still expecting a next of kin or relative of the deceased ,Late Mr. Morris Thompson. In fact I could have done this deal alone but because of my position in this country as civil servant,I am not allowed to operate a foreign account and that would eventually raise an eye brow on my side during the time of transfer since I still work in this bank, this is the actual reason why I required a second party or fellow who will assist me forward claims as the next of kin and also provide either an existing bank account or to set up a new Bank a/c immediately to receive this fund, even an empty a/c can also serve for this purpose. On smooth conclusion of this transaction,55% of the fund will be for me, I will give you 30% of the total transfered sum,10% for charity both in Senegal and in your country while the remaining 5% will be set aside to settle expenses both parties might incure during the transfer process. What I want from you is for you to act as the deceased next of kin. I have in my possession, all the necessary Documents to successfully accomplish the operation.Bear in mind that this transaction is 100% risk free. Further Information will be given to you as soon as I receive your positive response.  Sincerely yours, Mr. Maree Jacko.


For this post about purrr
, I had help from Kellie Ottoboni (@kellieotto) since we both wanted to update our skills. We both took some code from our own research and converted it from its original form (usually with variants of apply
) to variants of map
. This post talks about that experience, pitfalls we ran into, and cool tricks we learned.
The goal for the code I’m revamping is to simulate data under a variety of scenarios where various parameters change. Within each set of parameters, we want to repeat the simulation multiple times (here KK
) so that we can quantify our uncertainty. changeHelper
simulates the data and analyzes it.
It’s easier to see what is going on if I start with the purrr version because the original code was A MESS.
Note: I’m showing pseudocode because this is part of a collaborative project that hasn’t been released yet.
require(abind)
changeSim <- function(params, KK){
## for each set of parameters, repeat the simulation KK times
replicateR <- map(rep(list(params), times = KK), changeHelper)
## changeHelper returns a list with two elements: betaStore and lambdaStore
replicateRb <- map(replicateR, ~.x$betaStore)
replicateRl <- map(replicateR, ~.x$lambdaStore)
## or use transpose instead
#output <- replicateR %>% transpose
## organize the output so I can easily process it to make plots
return(list(betas = abind(replicateRb, along = 0), lambdas = abind(replicateRl, along = 0)))
#return(list(betas = abind(output$betaStore, along = 0), lambdas = abind(output$lambdaStore, along = 0)))
}
Not only does purrr
help simplify running the simulations, it also helps me set up the possible values of parameters. I want to keep most aspects of the simulation the same but change one aspect at a time.
betaOpt <- seq(0.1,3,by=.3)
N <- 100
## get list of parameter sets
## the variables in toChange are the things I'm varying in this case study
inputChangeBetaSim <- map(betaOpt,
~ list(toChange = list(v = rep(0.2, times = N), lambda = 0.5, beta =.x),
predVT= T, respVT = T, N = N, mu = 5, var = 1.3, alpha = -0.2, n = rpois(N,10), sigma = 1))
## apply list of parameter sets to the simulation function
changeBetaR <- map(inputChangeBetaSimLL, changeSim, KK)
## get the separate pieces that I need out of the output
betas <- map(changeBetaR, ~ .x$betas)
lambdas <- map(changeBetaR, ~ .x$lambdas)
## or we could use transpose
output <- changeBetaR %>% transpose
## transpose goes from this:
changeBetaR[[1]]$betas
changeBetaR[[1]]$lambdas
## to this:
output$betas[[1]]
output$lambda[[1]]
It is possible to get a simulated data set that give the analysis method trouble. To avoid having one error ruin a whole map
statement, we can use possibly
to fill in blank output if we run into an error in the analyzeData
function. This is an alternative to tryCatch
and (in my opinion) is easier to remember.
carefulAnalyzeData=possibly(analyzeData,list(betaStore=NA,lambdaStore=NA)) ## an alternative to tryCatch
changeHelper <- function(params){
## simulate data
data=simData(params)
## analyze simulated data
#results = analyzeData(data)
#results=tryCatch(analyzeData(data),error=function(e){list(betaStore=NA,lambdaStore=NA)})
results=carefulAnalyzeData(data)
return(results)
}
To improve performance, I can choose the slowest map
statement and run it in parallel using furrr (akin to mclapply
).
Note: I’m doing this on a Mac, so the plan
code may differ on a PC.
require(furrr) # future purrr
plan(cluster,workers=makeCluster(2))
#plan(multiprocess) # will use all available cores
changeBetaR <- future_map(inputChangeBetaSimLL, changeSim, KK)
Now on to the original version. Brace yourself!
Originally, all but the parameter I was changing was hard coded into a file that I sourced in changeHelper
. This required separate functions depending on which parameter I was changing, and if I wanted to change the other aspects of the simulation, I had to make sure I changed the value everywhere so the results would be comparable. You can imagine how this worked out.
changeSim <- function(betaOpt, KK){
betaOptR <- lapply(rep(betaOpt, times = KK), changeBetaHelper)
betaOptRb <- lapply(betaOptR, function(x){x$betaStore})
betaOptRl <- lapply(betaOptR, function(x){x$lambdaStore})
return(list(betas = abind(betaOptRb, along=0),lambdas = abind(betaOptRl, along = 0)))
}
changeBetaR <- lapply(betaOpt, changeBeta, KK)
betas <- lapply(changeBetaR, function(x){x$betas})
lambdas <- lapply(changeBetaR, function(x){x$lambdas})
To be fair this used to all be loops, so making the step towards lapply
was progress.
Recapping what changed:
lapply
–> map
function(x){x$var} –> ~.x$var
hard coded aspects requiring many different source files –> use map
to generate sets of parameters where only a few things change
transpose
to re-organize the two outputs
Verdict
Overall, I found the transition to purrr
more straightforward than the transition to other packages in the tidyverse that I’ve learned so far. It definitely helped that I had forced myself to use the apply
family of functions more often leading up to this. I wasn’t expecting the extra benefit of possibly
and transpose
but I can definitely see myself using them into my work moving forward.
One annoying thing I ran into is that my R session got confused between map
in the maps
package and map
in purrr
. I ended up just using purrr::map
to avoid any issues, but if I would have just require
d purrr
after maps
, the default map
would be the purrr
one.
 The data needed to be reshaped before it could be pumped into the usual linear model functions. There were seven clinical endpoints, each of which we analyzed individually to determine whether two treatments differed in their effect on patients’ GERD symptoms. Originally, I looped over each variable using apply
.
The original code is here if you want to take a look. First, let’s read in the data and have a look at it.
require(grid)
require(gridExtra)
library(tidyverse)
datafile <- "https://raw.githubusercontent.com/kellieotto/ancova-permutations/master/data/clinical_cleaned.csv"
clinical <- read.csv(datafile, header = TRUE, stringsAsFactors = FALSE)
head(clinical)
## SUBJID SITEID VISITNUM tr country heart_sev regurg_sev dysp_sev
## 1 1 1 1 A 1 1.428571 1.428571 1.571429
## 2 1 1 2 A 1 1.428571 1.285714 2.142857
## 3 2 1 1 B 1 2.714286 2.571429 2.000000
## 4 2 1 2 B 1 2.285714 2.285714 1.857143
## 5 3 1 1 A 1 2.000000 1.857143 1.714286
## 6 3 1 2 A 1 1.857143 1.285714 1.142857
## heart_freq regurg_freq dysp_freq daily_heart daily_regurg daily_hrdq
## 1 3.642857 4.285714 3.928571 0.8000000 0.8149357 1.614936
## 2 3.642857 3.428571 5.571429 0.7831171 0.6688314 1.451949
## 3 8.142857 7.500000 5.071429 1.9732257 1.7942057 3.767431
## 4 8.571429 8.071429 5.642857 1.6983043 1.6619400 3.360239
## 5 5.500000 1.285714 3.785714 1.2353657 0.5285714 1.763937
## 6 3.428571 1.142857 2.214286 1.0000000 0.3785714 1.378571
## daily_dysp
## 1 0.9000000
## 2 1.3883129
## 3 1.2201314
## 4 1.2595414
## 5 0.8441571
## 6 0.5428571
We have measurements at two timepoints for each patient, and we want to control for the first measurement as a covariate in the regression model that estimates the effect of treatment on the outcome. To do this in R, the values need to be in separate columns. We need to reshape the data, hooray! For whatever reason, this is something I have a lot of trouble with conceptually. This step took me longer than anything involving purrr
…
You get a bonus tidyverse example: in this function, I changed old reshape2
code to use tidyr
instead. The function turns the data from long into wide format and selects only the relevant columns. The result is a dataframe for the clinical endpoint of interest, with one baseline
column and an outcome
column, in addition to other variables to put in the model. Previously, this function did something hacky to pick out the variable of interest, then used the dcast
function to reshape. The reshape2
package used formula syntax to specify keys and values; I find the syntax of tidyr::spread
to be more straightforward.
# Group the data to treat person (SUBJID) and first/second visit (VISITNUM) as a single observation
data_by_subjid_visitnum <- clinical %>% group_by(SUBJID, VISITNUM)
reshape_data <- function(variable){
# Reshape data to be analyzed with regression
# Inputs:
# variable = the clinical endpoint of interest, input as a string
# Output:
# A dataframe with a single row per subject and columns for treatment, site ID, baseline + outcome measures
cleaned <- data_by_subjid_visitnum %>%
select_("VISITNUM", "SUBJID", "tr", "SITEID", variable) %>% # Pull out the columns we want
tidyr::spread_(key = "VISITNUM", value = variable) # Turn VISITNUM into columns, with value equal to measure
colnames(cleaned) <- c("SUBJID", "tr", "SITEID", "Baseline", "Outcome")
cleaned <- ungroup(cleaned) %>%
mutate(difference = Outcome - Baseline) # Ungroup and create a difference column
return(cleaned)
}
Now, instead of apply
ing this function to each of the seven clinical endpoints, I used purrr::map
. So clean!
# Reshape each variable, store in a list
continuous_vars <- c("daily_heart", "daily_regurg", "daily_dysp",
"daily_hrdq", "heart_freq", "regurg_freq", "dysp_freq")
reshaped_data <- continuous_vars %>% map(reshape_data)
head(reshaped_data[[1]])
## # A tibble: 6 x 6
## SUBJID tr SITEID Baseline Outcome difference
## <int> <chr> <int> <dbl> <dbl> <dbl>
## 1 1 A 1 0.800 0.783 -0.0169
## 2 2 B 1 1.97 1.70 -0.275
## 3 3 A 1 1.24 1.00 -0.235
## 4 4 B 1 1.54 1.54 0.
## 5 5 A 1 1.21 1.11 -0.0935
## 6 6 B 1 1.16 0.913 -0.243
Now I want to visualize the distribution of these variables in each treatment group. Same idea: I’m going to make the same kind of plot for each clinical endpoint by writing a plot function that I run for each variable. Previously, I used apply
. Now, I want to loop over the reshaped data and the variable names (so each plot is labeled appropriately). I used map2
for this: it just maps a function over two vectors of paired arguments. The first vector is the datasets and the second vector is the variable names.
# Plot the distribution of Outcome for each variable
plot_distributions <- function(dataset, varname){
p <- dataset %>%
mutate(tr = factor(tr)) %>%
ggplot(aes(Outcome)) +
geom_density(alpha = 0.6, aes(fill = tr))+
labs(x = varname, fill = "Treatment") +
theme_bw() +
theme(
axis.text.x = element_text(size = 12),
axis.text.y = element_text(size = 12),
axis.title = element_text(size = 16),
title = element_text(size = 16),
legend.title = element_text(size = 12),
legend.text = element_text(size = 14),
strip.text.x = element_text(size = 12)
)
return(p)
}
# Create a list containing a plot for each variable
all_plots <- map2(reshaped_data, continuous_vars, plot_distributions)
Ok, now a tricky step. Each plot has its own legend. I want to put all seven plots in one figure and just use one legend. Basically, you can grab just the legend element from one of the plots, remove it from all of the plots, then slap that saved legend wherever you want. That’s what I do below, again using map
to set legend.position="none"
on each of the plots. I put the seven plots in a 2x4 grid, then put the legend in the open 8th spot.
# Move the legend
tmp <- ggplot_gtable(ggplot_build(all_plots[[1]]))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
# Remove the legend from each plot, then stick it at the end of the plot list
all_plots <- all_plots %>% map(function(x) x + theme(legend.position="none"))
all_plots[[length(all_plots)+1]] <- legend
do.call(grid.arrange, c(all_plots, nrow = 2))
Verdict
Incorporating pipes in my code has made things infinitely more legible, and purrr::map
just makes things even clearer. Throwing an apply
in the middle of a pipe sequence kind of breaks the flow of reading from left to right. I think I will keep using map
going forward!
purrr
has so many more capabilities than just map
and map2
, though. I didn’t have the opportunity to explore all those other functions in this code, and to be frank I can’t think of examples from my work that would require using more complicated mapping functions. However I’m sure they are super useful.
We did it!
purrr
conversion!


Successful Marketers are Creative
If you can't be the leader in your category, create a new category you can be the leader in.
Rule 2 in the The 22 Immutable Laws of Marketing
Every successful person you know has differentiated themselves from others in their field. They are unique in their niche.
I stumbled upon this advertisement for Forever 21, a woman's clothing store, a while ago and realized that marketing and marketers fit this same mold. Great marketing is an invention game. Old methodologies can work, but new ways of marketing to users can be more affective.
Forever 21 wanted to have an advertisement in Times Square, the heaviest advertisement spaces in the United States. But, how do you differentiate yourself from every other advertisement being shown in Times Square? By being different. If Forever 21's advertisement wasn't unique they would be lost in the ocean of advertisements.
To be different Forever 21 chose to have an interactive billboard. The billboard was so distracting that the New York Police Department asked them to change the angle of the camera because drivers were creating traffic jams due to frequent stopping to view the ad.
Forever21 Times Square Billboard from space150 on Vimeo.
If you are in the physical space, anything interactive has a large chance of success. By visiting a science museum you will understand why interactive media is so effective. Humans love being able to control something, even if it is only the perception of control.
Interactive advertisements also reach outside your target demographic. I'm not a woman between the ages of 18-30. But, I am writing about the billboard.
Forever 21 accomplished to receive a bunch of media attention from the ad. From a branding perspective it had a lot of people taking pictures of it, talking about it, and writing about it.
Super Bowl ads, arguably the hardest marketing investment to demonstrate return is incredibly expensive. But, if done well, unique advertisements have staying power - People will continue talking about it decades later. Do you remember the Budweiser frogs?
However, this billboard wasn't funny, It was new. New is cool. Humans love new things. We constantly want to be entertained by fresh things.
Marketing does one thing: It informs. Every marketing play is a twist on delivering information to potential target users of a product or service.


more
rm
roll
None
previous
submit
rm
roll
None
previous
submit
rm
roll
None
previous
submit
hmmm
more stats
rm
submit
rm
submit
rm
submit
Table Name
Table Range
Mean
Std Dev
{#added so test_roller can call Math.seedrandom#}


Unit 3, Week 7 Cultural Blogpost
Values
Thursday February 5, 2015
In our blog post this week we are supposed to think of what values come to our mind at our highest points. When we have felt our greatest, most proud or most accomplished. We are given the following list of values to choose from:
Exploring | Your | Values
------|-------|-----
Accomplishment | Accountability | Achievement
Activism | Adventure | Affection
Ambition | Autonomy | Challenge
Close relationships | Commitment | Community
Compassion | Competence | Competition
Confidence | Conformity | Control
Coolness under fire | Cooperation | Courage
Creativity | Credibility | Decisiveness
Economic security | Effectiveness | Efficiency
Enthusiasm | Environmentalism | Excellence
Excitement | Fairness | Faith
Fame | Free time | Freedom
Friendships | Growth | Having a family
Health | Helping others | Helping society
Honesty | Hospitality | Independence
Influence | Inner harmony | Insight
Inspiration | Integrity | Intellectual status
Introspection | Justice | Knowledge
Leadership | Location | Loyalty
Meaningful work | Mentorship | Merit
Money | Movement | Music
Nature | Openness | Order
Patriotism | Peace | Persistence
Personal development | Physical challenge | Pleasure
Power and authority | Privacy | Public service
Purity | Quality | Recognition
Reputation | Responsibility | Romance
Security | Self-knowledge | Self-reliance
Self-respect | Serenity | Sophistication
Spirituality | Stability | Status
Tranquility | Truth | Vibrancy
Volunteering | Wealth | Will-power
Wisdom |
I read in a book once "the Value of Values" by Swami Dayananda Saraswati that values are principles. Values are not feelings, or reactions to experience, in fact values are the attitudes and beliefs we hold prior to an event happening. When I frame the definition of values like this, I want to revise the list above to include only terms which I would actually consider "values." For example "music" might be very important, but my definition does not consider "music" to be a value. My revised list would include:
Exploring | Your | Values
------|-------|-----
| Accountability |
Activism | |
Ambition | Autonomy |
| Commitment |
Compassion | | Competition
Confidence | |
| | Courage
| | Decisiveness
| Effectiveness | Efficiency
Enthusiasm | | Excellence
Excitement | Fairness | Faith
| Free time | Freedom
| Growth |
Health | Helping others |
Honesty | Hospitality | Independence
| Inner harmony |
| Integrity |
Introspection | Justice | Knowledge
Leadership | | Loyalty
Meaningful work | | Merit
| |
| Openness | Order
Patriotism | Peace | Persistence
Personal development | |
| |
Purity | Quality | Recognition
| Responsibility | Romance
Security | Self-knowledge | Self-reliance
Self-respect | Serenity |
Spirituality | Stability |
Tranquility | Truth | Vibrancy
| | Will-power
I try to live up to the values I hold important as much as possible and think about my beliefs before a choice comes up. The more structure we give to our life in general, the more enjoyable and productive our life will be. We can give our values structure by thinking about, challenging and resolving what our values are. Value structures will help us approach the decisions and consequences we experience in life. The more structure we give to our values, the more easily we can deal with decision making of almost any kind.
Paul Graham wrote in his 2007 essay "How Not to Die" and in his 2009 essay "What Startups are Really Like" the importance of one specific value for startups. He talked both times about how if founders did one thing, they would improve and maximize their chances of success enormously; never give up. For me it is not a difficult question what my most important value is currently; persistence.
I am new to coding with a lot of dreams, ambitions and high expectations. I currently struggle to implement basic features in applications I build right now. We all feel how difficult it is to experience crawling before walking and walking before running and essentially avoid learning new skills altogether as soon as we can in life. Rather than finding out what we need to learn to seize the world around us and the opportunities in front of us we look in the mirror and ask what that version of ourselves can do best.
It makes me uncomfortable to admit what I can't do, but I know it would be worse to live with what I didn't do. So while I hope I have a broad value structure, there is only one worth talking about right now. The one that tells me to get up and keep going whether its for an additional inch or mile that day. The one that doesn't get discouraged knowing 1% of what I want to know. The one that says I can't stop until I can build a great product for a userbase. Persistence.


Lying 10 nm N of Leixoes and only 18km from Porto airport, Povoa is a useful port. It is however not a particularly attractive one and although the town is over 100 years old, it has been taken over by high rise flats and hotels for tourists attracted by the long sandy beach.
A convenient stopover in the summer, but be aware that most of Portugal has fiestas in the summer and particularly in August the revelry can go on into the early hours.
Position 41° 22.2' N,8° 45.6'W.
Clearance can be completed at the marina office. All yachts, whether from another Portuguese port or not, must present passports and ships papers at the office.
Last updated December 2015.
Approach
When entering, the northern breakwater should be given a wide berth as there is often breaking water at its extremity. In addition, there is an isolated rock close to the inside of the northern breakwater. After entering between the two breakwaters, turn to starboard passing around a row of unlit green buoys which mark shallow water near the breakwater.
Also, be aware that the entrance can be rough when there is a heavy swell running and on occasions, the harbour may be closed.
Moorings
The fishing boats use the northern part of the harbour and the marina lies in the southern section.
The marina here (photo courtesy of Kieran Higgs) provides an economical longer-term berth for cruising yachts. As with the majority of ports on this coast however, care should be taken if deciding to winter your boat here in the water, due to the surge that develops during southerly winter storms. Improvements to the breakwater have helped dampen the swell somewhat. However, care should be taken with tying up your boat correctly to allow for surge, in particular in the winter and if leaving your boat for any length of time.
The new security gates installed at Povoa Marina do also operate with traditional magnetic cards, which are available for those visitors who wouldd rather not register biometric data (finger printing) with the marina.
The marina has hard standing for approx. 100 yachts, ideal for winter storage although not as a place for winter repairs as electricity usage is limited. Hard standing should be booked in advance (see boatyards for further details).
Local contractors can be sourced via the marina, however there is very little available in the town in the way of boat parts.
Anchoring
Anchoring in the harbour is permitted provided that neither the marina entrance is impeded nor the fishing vessels using the northern breakwater. The NE corner of the harbour (in 3m) is a possible spot.
Last updated December 2015.


We buy content!
- revolutionize bricks-and-clicks methodologies
- revolutionize virtual architectures
- synthesize user-centric convergence
- architect vertical models
- innovate vertical portals
- grow sexy solutions
- innovate vertical mindshare
- integrate strategic systems
- grow robust users
- brand sticky content
- empower extensible initiatives