 Rather than write schema modifications in pure SQL, migrations allow you to use a Ruby DSL to describe changes to your tables.
After reading this guide, you will know:
- The generators you can use to create them.
- The methods Active Record provides to manipulate your database.
- The rails commands that manipulate migrations and your schema.
- How migrations relate to
schema.rb
.
Migration Overview
Migrations are a convenient way to alter your database schema over time in a consistent way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
You can think of each migration as being a new 'version' of the database. A
schema starts off with nothing in it, and each migration modifies it to add or
remove tables, columns, or entries. Active Record knows how to update your
schema along this timeline, bringing it from whatever point it is in the
history to the latest version. Active Record will also update your
db/schema.rb
file to match the up-to-date structure of your database.
Here's an example of a migration:
class CreateProducts < ActiveRecord::Migration[6.0]
def change
create_table :products do |t|
t.string :name
t.text :description
t.
end
end
end
This migration adds a table called products
with a string column called
name
and a text column called description
. A primary key column called id
will also be added implicitly, as it's the default primary key for all Active
Record models. The timestamps
macro adds two columns, created_at
and
updated_at
. These special columns are automatically managed by Active Record
if they exist.
Note that we define the change that we want to happen moving forward in time. Before this migration is run, there will be no table. After, the table will exist. Active Record knows how to reverse this migration as well: if we roll this migration back, it will remove the table.
On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.
 If your
adapter supports DDL transactions you can use disable_ddl_transaction!
to
disable them for a single migration.
If you wish for a migration to do something that Active Record doesn't know how
to reverse, you can use reversible
:
class ChangeProductsPrice < ActiveRecord::Migration[6.0]
def change
reversible do |dir|
change_table :products do |t|
dir.up { t.change :price, :string }
dir.down { t.change :price, :integer }
end
end
end
end
Alternatively, you can use up
and down
instead of change
:
class ChangeProductsPrice < ActiveRecord::Migration[6.0]
def up
change_table :products do |t|
t.change :price, :string
end
end
def down
change_table :products do |t|
t.change :price, :integer
end
end
end
Creating a Migration
Creating a Standalone Migration
Migrations are stored as files in the db/migrate
directory, one for each
migration class. The name of the file is of the form
YYYYMMDDHHMMSS_create_products.rb
, that is to say a UTC timestamp
identifying the migration followed by an underscore followed by the name
of the migration. The name of the migration class (CamelCased version)
should match the latter part of the file name. For example
20080906120000_create_products.rb
should define class CreateProducts
and
20080906120001_add_details_to_products.rb
should define
AddDetailsToProducts
. Rails uses this timestamp to determine which migration
should be run and in what order, so if you're copying a migration from another
application or generate a file yourself, be aware of its position in the order.
Of course, calculating timestamps is no fun, so Active Record provides a generator to handle making it for you:
$ bin/rails generate migration AddPartNumberToProducts
This will create an appropriately named empty migration:
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
def change
end
end
This generator can do much more than append a timestamp to the file name. Based on naming conventions and additional (optional) arguments it can also start fleshing out the migration.
If the migration name is of the form "AddColumnToTable" or
"RemoveColumnFromTable" and is followed by a list of column names and
types then a migration containing the appropriate add_column
and
remove_column
statements will be created.
$ bin/rails generate migration AddPartNumberToProducts part_number:string
will generate
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
def change
add_column :products, :part_number, :string
end
end
If you'd like to add an index on the new column, you can do that as well.
$ bin/rails generate migration AddPartNumberToProducts part_number:string:index
will generate the appropriate add_column
and add_index
statements:
class AddPartNumberToProducts < ActiveRecord::Migration[6.0]
def change
add_column :products, :part_number, :string
add_index :products, :part_number
end
end
Similarly, you can generate a migration to remove a column from the command line:
$ bin/rails generate migration RemovePartNumberFromProducts part_number:string
generates
class RemovePartNumberFromProducts < ActiveRecord::Migration[6.0]
def change
remove_column :products, :part_number, :string
end
end
You are not limited to one magically generated column. For example:
$ bin/rails generate migration AddDetailsToProducts part_number:string price:decimal
generates
class AddDetailsToProducts < ActiveRecord::Migration[6.0]
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
end
end
If the migration name is of the form "CreateXXX" and is followed by a list of column names and types then a migration creating the table XXX with the columns listed will be generated. For example:
$ bin/rails generate migration CreateProducts name:string part_number:string
generates
class CreateProducts < ActiveRecord::Migration[6.0]
def change
create_table :products do |t|
t.string :name
t.string :part_number
t.
end
end
end
As always, what has been generated for you is just a starting point. You can add
or remove from it as you see fit by editing the
db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb
file.
Also, the generator accepts column type as references
(also available as
belongs_to
). For example,
$ bin/rails generate migration AddUserRefToProducts user:references
generates the following add_reference
call:
class AddUserRefToProducts < ActiveRecord::Migration[6.0]
def change
add_reference :products, :user, foreign_key: true
end
end
This migration will create a user_id
column and appropriate index.
There is also a generator which will produce join tables if JoinTable
is part of the name:
$ bin/rails generate migration CreateJoinTableCustomerProduct customer product
will produce the following migration:
class CreateJoinTableCustomerProduct < ActiveRecord::Migration[6.0]
def change
create_join_table :customers, :products do |t|
# t.index [:customer_id, :product_id]
# t.index [:product_id, :customer_id]
end
end
end
Model Generators
The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want, then statements for adding these columns will also be created. For example, running:
$ bin/rails generate model Product name:string description:text
will create a migration that looks like this
class CreateProducts < ActiveRecord::Migration[6.0]
def change
create_table :products do |t|
t.string :name
t.text :description
t.
end
end
end
You can append as many column name/type pairs as you want.
Passing Modifiers
Some commonly used type modifiers can be passed directly on the command line. They are enclosed by curly braces and follow the field type:
For instance, running:
$ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}
will produce a migration that looks like this
class AddDetailsToProducts < ActiveRecord::Migration[6.0]
def change
add_column :products, :price, :decimal, precision: 5, scale: 2
add_reference :products, :supplier, polymorphic: true
end
end
TIP: Have a look at the generators help output for further details.
Writing a Migration
Once you have created your migration using one of the generators it's time to get to work!
Creating a Table
The create_table
method is one of the most fundamental, but most of the time,
will be generated for you from using a model or scaffold generator. A typical
use would be
create_table :products do |t|
t.string :name
end
which creates a products
table with a column called name
(and as discussed
below, an implicit id
column).
By default, create_table
will create a primary key called id
. You can change
the name of the primary key with the :primary_key
option (don't forget to
update the corresponding model) or, if you don't want a primary key at all, you
can pass the option id: false
. If you need to pass database specific options
you can place an SQL fragment in the :options
option. For example:
create_table :products, options: "ENGINE=BLACKHOLE" do |t|
t.string :name, null: false
end
will append ENGINE=BLACKHOLE
to the SQL statement used to create the table.
Also you can pass the :comment
option with any description for the table
that will be stored in database itself and can be viewed with database administration
tools, such as MySQL Workbench or PgAdmin III. It's highly recommended to specify
comments in migrations for applications with large databases as it helps people
to understand data model and generate documentation.
Currently only the MySQL and PostgreSQL adapters support comments.
Creating a Join Table
The migration method create_join_table
creates an HABTM (has and belongs to
many) join table. A typical use would be:
create_join_table :products, :categories
which creates a categories_products
table with two columns called
category_id
and product_id
. These columns have the option :null
set to
false
by default. This can be overridden by specifying the :column_options
option:
create_join_table :products, :categories, column_options: { null: true }
By default, the name of the join table comes from the union of the first two
arguments provided to create_join_table, in alphabetical order.
To customize the name of the table, provide a :table_name
option:
create_join_table :products, :categories, table_name: :categorization
creates a categorization
table.
create_join_table
also accepts a block, which you can use to add indices
(which are not created by default) or additional columns:
create_join_table :products, :categories do |t|
t.index :product_id
t.index :category_id
end
Changing Tables
A close cousin of create_table
is change_table
, used for changing existing
tables. It is used in a similar fashion to create_table
but the object
yielded to the block knows more tricks. For example:
change_table :products do |t|
t.remove :description, :name
t.string :part_number
t.index :part_number
t.rename :upccode, :upc_code
end
removes the description
and name
columns, creates a part_number
string
column and adds an index on it. Finally it renames the upccode
column.
Changing Columns
Like the remove_column
and add_column
Rails provides the change_column
migration method.
change_column :products, :part_number, :text
This changes the column part_number
on products table to be a :text
field.
Note that change_column
command is irreversible.
Besides change_column
, the change_column_null
and change_column_default
methods are used specifically to change a not null constraint and default
values of a column.
change_column_null :products, :name, false
change_column_default :products, :approved, from: true, to: false
This sets :name
field on products to a NOT NULL
column and the default
value of the :approved
field from true to false.
NOTE: You could also write the above change_column_default
migration as
change_column_default :products, :approved, false
, but unlike the previous
example, this would make your migration irreversible.
Column Modifiers
Column modifiers can be applied when creating or changing a column:
limit
Sets the maximum size of thestring/text/binary/integer
fields.precision
Defines the precision for thedecimal
fields, representing the total number of digits in the number.scale
Defines the scale for thedecimal
fields, representing the number of digits after the decimal point.polymorphic
Adds atype
column forbelongs_to
associations.null
Allows or disallowsNULL
values in the column.default
Allows to set a default value on the column. Note that if you are using a dynamic value (such as a date), the default will only be calculated the first time (i.e. on the date the migration is applied).comment
Adds a comment for the column.
Some adapters may support additional options; see the adapter specific API docs for further information.
NOTE: null
and default
cannot be specified via command line.
Foreign Keys
While it's not required you might want to add foreign key constraints to guarantee referential integrity.
add_foreign_key :articles, :
This adds a new foreign key to the author_id
column of the articles
table. The key references the id
column of the authors
table. If the
column names cannot be derived from the table names, you can use the
:column
and :primary_key
options.
Rails will generate a name for every foreign key starting with
fk_rails_
followed by 10 characters which are deterministically
generated from the from_table
and column
.
There is a :name
option to specify a different name if needed.
NOTE: Active Record only supports single column foreign keys. execute
and
structure.sql
are required to use composite foreign keys. See
Schema Dumping and You.
Foreign keys can also be removed:
# let Active Record figure out the column name
remove_foreign_key :accounts, :branches
# remove foreign key for a specific column
remove_foreign_key :accounts, column: :owner_id
# remove foreign key by name
remove_foreign_key :accounts, name: :special_fk_name
When Helpers aren't Enough
If the helpers provided by Active Record aren't enough you can use the execute
method to execute arbitrary SQL:
Product.connection.execute("UPDATE products SET price = 'free' WHERE 1=1")
For more details and examples of individual methods, check the API documentation.
In particular the documentation for
::ActiveRecord::ConnectionAdapters::SchemaStatements
(which provides the methods available in the change
, up
and down
methods),
::ActiveRecord::ConnectionAdapters::TableDefinition
(which provides the methods available on the object yielded by create_table
)
and
::ActiveRecord::ConnectionAdapters::Table
(which provides the methods available on the object yielded by change_table
).
Using the change
Method
The change
method is the primary way of writing migrations. It works for the
majority of cases, where Active Record knows how to reverse the migration
automatically. Currently, the change
method supports only these migration
definitions:
add_column
add_foreign_key
add_index
add_reference
add_timestamps
change_column_default
(must supply a:from
and:to
option)change_column_null
create_join_table
create_table
disable_extension
drop_join_table
drop_table
(must supply a block)enable_extension
remove_column
(must supply a type)remove_foreign_key
(must supply a second table)remove_index
remove_reference
remove_timestamps
rename_column
rename_index
rename_table
change_table
is also reversible, as long as the block does not call change
,
change_default
or remove
.
remove_column
is reversible if you supply the column type as the third
argument. Provide the original column options too, otherwise Rails can't
recreate the column exactly when rolling back:
remove_column :posts, :slug, :string, null: false, default: ''
If you're going to need to use any other methods, you should use reversible
or write the up
and down
methods instead of using the change
method.
Using reversible
Complex migrations may require processing that Active Record doesn't know how
to reverse. You can use reversible
to specify what to do when running a
migration and what else to do when reverting it. For example:
class ExampleMigration < ActiveRecord::Migration[6.0]
def change
create_table :distributors do |t|
t.string :zipcode
end
reversible do |dir|
dir.up do
# add a CHECK constraint
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5) NO INHERIT;
SQL
end
dir.down do
execute <<-SQL
ALTER TABLE distributors
DROP CONSTRAINT zipchk
SQL
end
end
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
end
Using reversible
will ensure that the instructions are executed in the
right order too. If the previous example migration is reverted,
the down
block will be run after the home_page_url
column is removed and
right before the table distributors
is dropped.
Sometimes your migration will do something which is just plain irreversible; for
example, it might destroy some data. In such cases, you can raise
::ActiveRecord::IrreversibleMigration
in your down
block. If someone tries
to revert your migration, an error message will be displayed saying that it
can't be done.
Using the up
/down
Methods
You can also use the old style of migration using up
and down
methods
instead of the change
method.
The up
method should describe the transformation you'd like to make to your
schema, and the down
method of your migration should revert the
transformations done by the up
method. In other words, the database schema
should be unchanged if you do an up
followed by a down
. For example, if you
create a table in the up
method, you should drop it in the down
method. It
is wise to perform the transformations in precisely the reverse order they were
made in the up
method. The example in the reversible
section is equivalent to:
class ExampleMigration < ActiveRecord::Migration[6.0]
def up
create_table :distributors do |t|
t.string :zipcode
end
# add a CHECK constraint
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
SQL
add_column :users, :home_page_url, :string
rename_column :users, :email, :email_address
end
def down
rename_column :users, :email_address, :email
remove_column :users, :home_page_url
execute <<-SQL
ALTER TABLE distributors
DROP CONSTRAINT zipchk
SQL
drop_table :distributors
end
end
If your migration is irreversible, you should raise
::ActiveRecord::IrreversibleMigration
from your down
method. If someone tries
to revert your migration, an error message will be displayed saying that it
can't be done.
Reverting Previous Migrations
You can use Active Record's ability to rollback migrations using the revert
method:
require_relative "20121212123456_example_migration"
class FixupExampleMigration < ActiveRecord::Migration[6.0]
def change
revert ExampleMigration
create_table(:apples) do |t|
t.string :variety
end
end
end
The revert
method also accepts a block of instructions to reverse.
This could be useful to revert selected parts of previous migrations.
For example, let's imagine that ExampleMigration
is committed and it
is later decided it would be best to use Active Record validations,
in place of the CHECK
constraint, to verify the zipcode.
class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration[6.0]
def change
revert do
# copy-pasted code from ExampleMigration
reversible do |dir|
dir.up do
# add a CHECK constraint
execute <<-SQL
ALTER TABLE distributors
ADD CONSTRAINT zipchk
CHECK (char_length(zipcode) = 5);
SQL
end
dir.down do
execute <<-SQL
ALTER TABLE distributors
DROP CONSTRAINT zipchk
SQL
end
end
# The rest of the migration was ok
end
end
end
The same migration could also have been written without using revert
but this would have involved a few more steps: reversing the order
of create_table
and reversible
, replacing create_table
by drop_table
, and finally replacing up
by down
and vice-versa.
This is all taken care of by revert
.
Running Migrations
Rails provides a set of rails commands to run certain sets of migrations.
The very first migration related rails command you will use will probably be
bin/rails db:migrate
. In its most basic form it just runs the change
or up
method for all the migrations that have not yet been run. If there are
no such migrations, it exits. It will run these migrations in order based
on the date of the migration.
Note that running the db:migrate
command also invokes the db:schema:dump
command, which
will update your db/schema.rb
file to match the structure of your database.
If you specify a target version, Active Record will run the required migrations (change, up, down) until it has reached the specified version. The version is the numerical prefix on the migration's filename. For example, to migrate to version<PHONE_NUMBER>0000 run:
$ bin/rails db:migrate VERSION=20080906120000
If version<PHONE_NUMBER>0000 is greater than the current version (i.e., it is
migrating upwards), this will run the change
(or up
) method
on all migrations up to and
including<PHONE_NUMBER>0000, and will not execute any later migrations. If
migrating downwards, this will run the down
method on all the migrations
down to, but not including,<PHONE_NUMBER>0000.
Rolling Back
A common task is to rollback the last migration. For example, if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run:
$ bin/rails db:rollback
This will rollback the latest migration, either by reverting the change
method or by running the down
method. If you need to undo
several migrations you can provide a STEP
parameter:
$ bin/rails db:rollback STEP=3
will revert the last 3 migrations.
The db:migrate:redo
command is a shortcut for doing a rollback and then migrating
back up again. As with the db:rollback
command, you can use the STEP
parameter
if you need to go more than one version back, for example:
$ bin/rails db:migrate:redo STEP=3
Neither of these rails commands do anything you could not do with db:migrate
. They
are there for convenience, since you do not need to explicitly specify the
version to migrate to.
Setup the Database
The bin/rails db:setup
command will create the database, load the schema, and initialize
it with the seed data.
Resetting the Database
The bin/rails db:reset
command will drop the database and set it up again. This is
functionally equivalent to bin/rails db:drop db:setup
.
NOTE: This is not the same as running all the migrations. It will only use the
contents of the current db/schema.rb
or db/structure.sql
file. If a migration can't be rolled back,
bin/rails db:reset
may not help you. To find out more about dumping the schema see
Schema Dumping and You section.
Running Specific Migrations
If you need to run a specific migration up or down, the db:migrate:up
and
db:migrate:down
commands will do that. Just specify the appropriate version and
the corresponding migration will have its change
, up
or down
method
invoked, for example:
$ bin/rails db:migrate:up VERSION=20080906120000
will run the<PHONE_NUMBER>0000 migration by running the change
method (or the
up
method). This command will
first check whether the migration is already performed and will do nothing if
Active Record believes that it has already been run.
Running Migrations in Different Environments
By default running bin/rails db:migrate
will run in the development
environment.
To run migrations against another environment you can specify it using the
RAILS_ENV
environment variable while running the command. For example to run
migrations against the test
environment you could run:
$ bin/rails db:migrate RAILS_ENV=test
Changing the Output of Running Migrations
By default migrations tell you exactly what they're doing and how long it took. A migration creating a table and adding an index might produce output like this
== CreateProducts: migrating =================================================
-- create_table(:products)
#=> 0.0028s
== CreateProducts: migrated (0.0028s) ========================================
Several methods are provided in migrations that allow you to control all this:
| Method | Purpose |
|---|---|
suppress_messages |
Takes a block as an argument and suppresses any output generated by the block. |
say |
Takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not. |
say_with_time |
Outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected. |
For example, this migration:
class CreateProducts < ActiveRecord::Migration[6.0]
def change
do
create_table :products do |t|
t.string :name
t.text :description
t.
end
end
say "Created a table"
{add_index :products, :name}
say "and an index!", true
say_with_time 'Waiting for a while' do
sleep 10
250
end
end
end
generates the following output
== CreateProducts: migrating =================================================
-- Created a table
#=> and an index!
-- Waiting for a while
#=> 10.0013s
#=> 250 rows
== CreateProducts: migrated (10.0054s) =======================================
If you want Active Record to not output anything, then running bin/rails db:migrate
VERBOSE=false
will suppress all output.
Changing Existing Migrations
Occasionally you will make a mistake when writing a migration. If you have
already run the migration, then you cannot just edit the migration and run the
migration again: Rails thinks it has already run the migration and so will do
nothing when you run bin/rails db:migrate
. You must rollback the migration (for
example with bin/rails db:rollback
), edit your migration, and then run
bin/rails db:migrate
to run the corrected version.
In general, editing existing migrations is not a good idea. You will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or, more generally, which has not been propagated beyond your development machine) is relatively harmless.
The revert
method can be helpful when writing a new migration to undo
previous migrations in whole or in part
(see Reverting Previous Migrations above).
Schema Dumping and You
What are Schema Files for?
Migrations, mighty as they may be, are not the authoritative source for your
database schema. Your database remains the authoritative source. By default,
Rails generates db/schema.rb
which attempts to capture the current state of
your database schema.
It tends to be faster and less error prone to create a new instance of your
application's database by loading the schema file via bin/rails db:schema:load
than it is to replay the entire migration history.
Old migrations may fail to apply correctly if those
migrations use changing external dependencies or rely on application code which
evolves separately from your migrations.
Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations, but the information is nicely summed up in the schema file.
Types of Schema Dumps
The format of the schema dump generated by Rails is controlled by the
config.active_record.schema_format
setting in config/application.rb
. By
default, the format is :ruby
, but can also be set to :sql
.
If :ruby
is selected, then the schema is stored in db/schema.rb
. If you look
at this file you'll find that it looks an awful lot like one very big migration:
ActiveRecord::Schema.define(version: 2008_09_06_171750) do
create_table "authors", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "products", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
t.string "part_number"
end
end
In many ways this is exactly what it is. This file is created by inspecting the
database and expressing its structure using create_table
, add_index
, and so
on.
db/schema.rb
cannot express everything your database may support such as
triggers, sequences, stored procedures, etc. While migrations
may use execute
to create database constructs that are not supported by the
Ruby migration DSL, these constructs may not be able to be reconstituted by the
schema dumper. If you are using features like these, you should set the schema
format to :sql
in order to get an accurate schema file that is useful to
create new database instances.
When the schema format is set to :sql
, the database structure will be dumped
using a tool specific to the database into db/structure.sql
. For example, for
PostgreSQL, the pg_dump
utility is used. For MySQL and MariaDB, this file will
contain the output of SHOW CREATE TABLE
for the various tables.
To load the schema from db/structure.sql
, run bin/rails db:schema:load
.
Loading this file is done by executing the SQL statements it contains. By
definition, this will create a perfect copy of the database's structure.
Schema Dumps and Source Control
Because schema files are commonly used to create new databases, it is strongly recommended that you check your schema file into source control.
Merge conflicts can occur in your schema file when two branches modify schema.
To resolve these conflicts run bin/rails db:migrate
to regenerate the schema file.
Active Record and Referential Integrity
The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or constraints, which push some of that intelligence back into the database, are not heavily used.
Validations such as validates :foreign_key, uniqueness: true
are one way in
which models can enforce data integrity. The :dependent
option on
associations allows models to automatically destroy child objects when the
parent is destroyed. Like anything which operates at the application level,
these cannot guarantee referential integrity and so some people augment them
with foreign key constraints in the database.
Although Active Record does not provide all the tools for working directly with
such features, the execute
method can be used to execute arbitrary SQL.
Migrations and Seed Data
The main purpose of Rails' migration feature is to issue commands that modify the schema using a consistent process. Migrations can also be used to add or modify data. This is useful in an existing database that can't be destroyed and recreated, such as a production database.
class AddInitialProducts < ActiveRecord::Migration[6.0]
def up
5.times do |i|
Product.create(name: "Product ##{i}", description: "A product.")
end
end
def down
Product.delete_all
end
end
To add initial data after a database is created, Rails has a built-in
'seeds' feature that speeds up the process. This is especially
useful when reloading the database frequently in development and test environments.
To get started with this feature, fill up db/seeds.rb
with some
Ruby code, and run bin/rails db:seed
:
5.times do |i|
Product.create(name: "Product ##{i}", description: "A product.")
end
This is generally a much cleaner way to set up the database of a blank application.
Old Migrations
The db/schema.rb
or db/structure.sql
is a snapshot of the current state of your
database and is the authoritative source for rebuilding that database. This
makes it possible to delete old migration files.
When you delete migration files in the db/migrate/
directory, any environment
where bin/rails db:migrate
was run when those files still existed will hold a reference
to the migration timestamp specific to them inside an internal Rails database
table named schema_migrations
. This table is used to keep track of whether
migrations have been executed in a specific environment.
If you run the bin/rails db:migrate:status
command, which displays the status
(up or down) of each migration, you should see ********** NO FILE **********
displayed next to any deleted migration file which was once executed on a
specific environment but can no longer be found in the db/migrate/
directory.
There's a caveat, though. Rake tasks to install migrations from engines are idempotent. Migrations present in the parent application due to a previous installation are skipped, and missing ones are copied with a new leading timestamp. If you deleted old engine migrations and ran the install task again, you'd get new files with new timestamps, and db:migrate
would attempt to run them again.
Thus, you generally want to preserve migrations coming from engines. They have a special comment like this:
# This migration comes from blorgh (originally<PHONE_NUMBER>2949)


Just my little project to play around with data and 3djs.
Interested? Mail me<EMAIL_ADDRESS>The fun starts here:


DISH MASTER
SAN JOSE
Username:
Username must contain 6-12 characters.
E-mail:
Email must follow standard Email format i.e<EMAIL_ADDRESS>Password:
Password must contain 6-12 characters.
Password (Confirm):
Register


Scroll this page to see how the navbar behaves with data-spy="affix".
data-spy="affix"
The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.


Our latest @universalmind R&D project done by @merhl and I is now featured on @tuaw … #umlabs - More on this tomorrow!
DavidTucker.net Website using Wintersmith a NodeJS Static Site Generator
ST2 Power Tools: Startup Tools for Sencha Touch 2 Development to reduce boilerplate code
10 Things to Know When Creating a Mobile Application - Examining the Mobile Development Process
What the iPhone 5 Means for Consumers - Pondering the Potential Consumer Impact


Hello Viewers
THis
is
my
first page
LIST OF ITEMS
Unordered list
Apples
Oranges
Cherry
Kiwi
ordered list
Apples
Oranges
Cherry
Kiwi
Defenition list
:
Apples
Oranges
Cherry
Kiwi
Use of li tag
Banana
Mango
Back to Anchor Page


Salmon Cookies
Check Out Our Menu!
Cookies
- Crispy Chinook
- Savory Sockeye
- Yummy Chum
- Krunchy King
- Crumbly Coho
Drinks
- Expensive Sodas
- Less expensive Beers
- Very Expensive Espresso
- Milk
- Juices
- Fishy Water
Sandwiches
- Ham & Cheese
- Roast Beef
- Ruben
- French Dip
- Club
- Grilled Cheese


Consider a general integration of the distribution function f in the phase-space
|
| (53) |
where Ω′ is a sub-region of the phase space Ω, A(Z) is a general function of the phase-space coordinates Z, dV is the phase space volume element. As is discussed above, in particle methods, f(Z) is approximated by
|
| (54) |
where Sps(Z−Zj) is the phase space shape function of markers, N is the total number of marker loaded in the phase space Ω. Using this, expression (53) is written as
|
| (55) |
If the shape function Sps is chosen to be the Dirac delta function, then the above equation is written as
|
| (56) |
where N′ is the number of markers that are within the sub-region Ω′. Equation (56) is the Monte-Carlo approximation to the integration in Eq. (53)[4, 2].
In PIC simulations, we are usually interested in velocity moments of f averaged in a cell, i.e., A in Eq. (55) is only a function of only v and the velocity integration is over the whole velocity space, whereas the spatial integration is over a small spatial cell. Furthermore, in PIC simulations, the markers are assumed to have a ﬁnite shape in the real space (the shape in velocity space is still the Dirac delta function). In this case, Eq. (55) is written as
|
| (58) |


product owner
bill mahoney
art director
sab cabrera
tech lead
shae le
ux designer
skylah lu
developer
griff richards
developer
We are team of creatively diverse, driven, innovative individuals working in various locations from the world.


Rollover a menu item to expand it.
Home
The front page
About
More info
Contact
Get in touch
Submit
Send us your stuff!
Terms
Legal things


--- layout: post date: 2008-11-30 time: "09:00:00" authors: ["Greg Wilson"] title: Igor, Connect the Electrodes! tags: ["Content"] ---
The Software Carpentry course site is still getting a fair bit of traffic, although readership is definitely tailing off:
I'm hoping to run an intensive three-week version of the course in June 2009 in Toronto (details to follow); hope I can find time between now and then to finish wikifying the course notes, get the MATLAB material online, and generally freshen the site up.


National Student Film Festival ‘Li & Le’
National Student Film Festival ‘Li & Le’
A Brief Report
About the Event
School of Arts and Humanities
National Student Film Festival ‘Li & Le’.
National Student Film Festival ‘Li & Le’ was held at REVA University by The School Of
Arts And Humanities. The 2nd day of the film festival consisted of various film related
workshops by people from the industry. The festival started at 10:00 am with a
workshop conducted by Mr. Pampally, Film Director and Screenwriter. This was
followed by various other workshops by Mr. Ranjith, Mr Hemanth Rao, FIlm Director,
Mr Niranjan Deshpande, Actor and Mr V. S. Kashinath, WIldlife Photographer.
The workshops were followed by lunch at 1:45 pm and the festival resumed with
participants taking part in various competitions like Shutterbug and Dubsmash/Tik Tok.
The highlight of the event were the short films screened in Kuvempu Auditorium. Upto
50 submissions were narrowed down and judged by Mr. Pampally and Mr. Doddaiyah.
The students participated with enthusiasm and won prizes for various competitions.
About REVA University
REVA University is a private co-educational college in Bangalore, Karnataka,
established in 2002, managed by Bheemaneni Educational Service Trust. In 2004 it was
taken over by Rukmini Educational Charitable Trust led by Shri P. Shyamaraju.
It received an accreditation by NBA within a record time span of seven years post its
inception in 2004 . All the institutions of the Trust are most sought after by aspiring
students for pursuing higher education because of their excellent infrastructure, highly
qualified faculty, commendable placement record, keen industry-institute interaction and
various R&D initiatives.
REVA University, School of Arts and Humanities launched a National Student Film
Festival called Li & Le. The 2 chief guests gracing the occasion were Director and
Producer Mr Yograj Bhat and Director and Actor M. G. Srinivas along with Hon'ble Vice
Chancellor S. Y. Kulkarni who presided over the inaugural ceremony and facilitated the
guests.
The ceremony started with lighting of the lamp and an video of their profile.
Shri Yograj Bhatt inaugurated the film festival by launching the 'Li & Le 'video. “Every
movie comes from the heart and the mind of the writer”, he said.
The inaugural ceremony was followed by an interactive session between students and
the cast of upcoming film 'Panchatantra'. The ceremony ended with the screening of M.
G. Srinivas's movie 'Birbal' which was well received by students and staff.
REVA University is a private co-educational college in Bangalore, Karnataka,
established in 2002, managed by Bheemaneni Educational Service Trust. In 2004 it was
taken over by Rukmini Educational Charitable Trust led by Shri P. Shyamaraju.
It received an accreditation by NBA within a record time span of seven years post its
inception in 2004 . All the institutions of the Trust are most sought after by aspiring
students for pursuing higher education because of their excellent infrastructure, highly
qualified faculty, commendable placement record, keen industry-institute interaction and
various R&D initiatives.
Short Film Screening
Short Film Screening
The Short Film screening of Li &Le REVA University National Film Festival began at 3:00 p.m. in
Kuvempu Auditorium in the presence of Mr. Doddaiyah and Mr. Pampally as the jury members
of the event. Upto 50 films were submitted which were then narrowed down.
The first screened film was a Kannada short film called "Sex OTHER" depicting a story of a
trans-woman in Bangalore, which was followed by "Captionless - no bound for emotion" a
Malayalam short film which brought out the difference in between the childhood of the older
generations and the present generation.
The third screened film, ‘Project Sweetlime’ is a’ Kannada movie which addressed the issue of
social media addiction and the right usage of the same.
The fourth movie screened was, ‘Jaalathraana’ a Kannada movie bringing out the issue of
kidnapping and human trafficking, especially children.
"Ghatakan" a Malayalam movie was screened fifth which brought out the concept of death in a
dual perspective. One as end of life and the other as the continuity after death
"Swara" was the next short film screened depicting the revenge of a ghost for the death of her
child.

Valedictory Report
Valedictory Report
The valedictory of ‘Li & Le’ film festival ’ was held at Kuvempu Auditorium, C. V. Raman Block.
Which concluded the film festival by announcing the winners of the competitions and a vote of
thanks to the guests, sponsors and students.
More than 30 registrations for the photography competition, made it tough for the judges to pick
a winner. Hemanth was the winner of ‘Shutterbug’, competition.
The winner of Documentary film was Jayabharatan.
In short film the first place was won by ‘Sex: Other’ by Anirudh Bhatt.’. In 2nd place was
‘Captionless: No Bound For Emotions’’ by Raghav and in 3rd place was ‘Two wheeler’ by Uttam
Benedict. Deepshi was the winner of dubsmash competition.
The Sponsors of the festival Redhan Production House were thanked and Mr Inder Kumar's
wife addressed the audience on his behalf. The reason they decided to sponsor the film festival
was because of the changing trends in the industry. They wanted to focus on the youth and their
perspective and focus on real issues existing in society.
The ceremony ended with a vote of thanks for the all the guests, participants, organisers and
staff.


≡
Links
Rimu Home
Rimu Playground
Rimu Reference
Rimu Tips
Rimu Gallery
Change Log
GitHub
npm
Table of Contents
Rimu Playground
▼
Rimu markup
Edit these examples or add your own:
Some **bold text**, some _emphasized text_, some `monospaced text` and some ~~deleted text~~. A [link to the Rimu website](https://srackham.github.io/rimu/), an auto-encoded link https://srackham.github.io/rimu/. > Quote paragraph. `` Code block. `` - A bullet list item. - A 2nd bullet list item. . Nested numbered list item.
Diagnostic messages:
▼
HTML preview
▼
HTML markup


Bale would repsond with a resounding "no" to Tottenham offer
by BeSoccerReal Madrid have a great unknown in their dressing room, Gareth Bale. His exit was in the air, but the flag incident has placed him one step closer to the exit door. It was speculated that Tottenham, now with Mourinho in charge, would like to welcome him, but the Welshman would not agree with the deal.
At least, that is what was said on 'El Chiringuito'. According to José Luis Sánchez, Bale would say 'no' to a hypothetical offer from his ex-team, Tottenham.
Featured links
- BREAKING NEWS: Mourinho replaces Pochettino at Tottenham
- The latest football transfers news and rumours
- Wales, golf, Madrid... in that order
- Luis Enrique returns to Spain national team
Both the Welshman and Spurs are experiencing turbulent times. Bale's situation in Madrid is delicate, like Tottenham's, especially now that Pochettino has been sacked and replaced by Mourinho.
The aforementioned source does not add more explanations to the reasons that would lead Bale to reject an offer that is still just a rumour.


--- layout: page title: "About" description: "I've felt worse." header-img: "my_img/about-bg-1.jpg" ---
《远方海岸》是来自电视剧"Steven Universe"的第5季的第17集"Can't Go Back"的一首歌。它由一名叫青金石的角色演唱，来讲述她对地球上度过的时光的感受。
一切变得如此美丽
那片蔚蓝划过天际
那悸动感觉我前所未有直到遇见你
曾想过暂作停留
曾学习绽放笑容
那未知的色彩渐渐映入视线中
也许会发现自己在远方海岸独坐
也许我不寂寞
随后眼前色彩消失
温柔光芒渐渐飞逝
恐惧阴影将心灵侵蚀
这是否似曾相识
我懂那深藏心底的东西
是那份畏惧战栗
我无从知晓为何你如此勇毅
也许会发现自己在远方海岸微笑
也许我不寂寥
"That Distant Shore" is a song from "Can't Go Back" which is the 17th episode of the 5th season of the TV series "Steven Universe". It is sung by the character Lapis Lazuli about her feelings of her time spent on Earth.
It all became so lovely
Those bluest skies above me
Those funny feelings I had never felt before I met you
I thought I'd stay a while
I tried to learn to smile
So many colors I had never even known
Maybe I'll find myself sitting on that distant shore
Maybe I'm not alone
Then I see the colors fading
Gentleness of light escaping
Shadows of my fear invading
Have I seen this all before?
I know that there's something residing
A terror deep inside me
I couldn't understand how you could be so bold
Maybe I'll find myself smiling on that distant shore
Maybe I'm not alone...


| Modifier and Type | Interface and Description |
|---|---|
interface |
FindCallback<T
extends ParseObject>
A
FindCallback is used to run code after a ParseQuery
is used to fetch a list of
ParseObject s
in a background thread.
|
interface |
GetCallback<T
extends ParseObject>
A
GetCallback is used to run code after a ParseQuery
is used to fetch a
ParseObject
in a background thread.
|
class |
ParseQuery<T extends
ParseObject>
The
ParseQuery class defines a query that is used to
fetch ParseObject s.
|
class |
ParseQueryAdapter<T
extends ParseObject>
A
ParseQueryAdapter handles the fetching of objects by
page, and displaying objects as
views in a ListView .
|
static interface |
ParseQueryAdapter.OnQueryLoadListener<T
extends ParseObject>
Implement with logic that is called before and after objects are
fetched from Parse by the
adapter.
|
static interface |
ParseQueryAdapter.QueryFactory<T extends ParseObject>
Implement to construct your own custom
ParseQuery
for fetching objects.
|
class |
ParseRelation<T
extends ParseObject>
A class that is used to access all of the children of a many-to-many
relationship.
|
| Modifier and Type | Class and Description |
|---|---|
class |
ParseInstallation
The
ParseInstallation is a local representation of
installation data that can be saved
and retrieved from the Parse cloud.
|
class |
ParseRole
Represents a Role on the Parse server.
|
class |
ParseSession
The
ParseSession is a local representation of session
data that can be saved
and retrieved from the Parse cloud.
|
class |
ParseUser
The
ParseUser is a local representation of user data
that can be saved and retrieved from
the Parse cloud.
|
| Modifier and Type | Method and Description |
|---|---|
static <T extends ParseObject>
|
ParseObject.create(Class<T> subclass)
Creates a new
ParseObject based upon a subclass type. |
static <T extends ParseObject>
|
ParseObject.createWithoutData(Class<T> subclass,
String objectId)
Creates a reference to an existing
ParseObject for use in
creating associations between
ParseObject s.
|
static <T extends ParseObject>
|
ParseObject.deleteAll(List<T> objects)
Deletes each object in the provided list.
|
static <T extends ParseObject> |
ParseObject.deleteAllInBackground(List<T> objects)
Deletes each object in the provided list.
|
static <T extends ParseObject>
|
ParseObject.deleteAllInBackground(List<T> objects,
DeleteCallback callback)
Deletes each object in the provided list.
|
<T extends ParseObject>
|
ParseObject.fetch()
Fetches this object with the data from the server.
|
static <T extends ParseObject> |
ParseObject.fetchAll(List<T> objects)
Fetches all the objects in the provided list.
|
static <T extends ParseObject> |
ParseObject.fetchAllIfNeeded(List<T> objects)
Fetches all the objects that don't have data in the provided list.
|
static <T extends ParseObject> |
ParseObject.fetchAllIfNeededInBackground(List<T> objects)
Fetches all the objects that don't have data in the provided list in the
background.
|
static <T extends ParseObject>
|
ParseObject.fetchAllIfNeededInBackground(List<T> objects,
FindCallback<T> callback)
Fetches all the objects that don't have data in the provided list in the
background.
|
static <T extends ParseObject> |
ParseObject.fetchAllInBackground(List<T> objects)
Fetches all the objects in the provided list in the background.
|
static <T extends ParseObject>
|
ParseObject.fetchAllInBackground(List<T> objects,
FindCallback<T> callback)
Fetches all the objects in the provided list in the background.
|
<T extends ParseObject>
|
ParseObject.fetchFromLocalDatastoreInBackground(GetCallback<T> callback)
Loads data from the local datastore into this object, if it has not been
fetched from the
server already.
|
<T extends ParseObject>
|
ParseObject.fetchIfNeeded()
If this
ParseObject has not been fetched (i.e. |
<T extends ParseObject> |
ParseObject.fetchIfNeededInBackground()
If this
ParseObject has not been fetched (i.e. |
<T extends ParseObject>
|
ParseObject.fetchIfNeededInBackground(GetCallback<T> callback)
If this
ParseObject has not been fetched (i.e. |
<T extends ParseObject> |
ParseObject.fetchInBackground()
Fetches this object with the data from the server in a background
thread.
|
<T extends ParseObject>
|
ParseObject.fetchInBackground(GetCallback<T> callback)
Fetches this object with the data from the server in a background
thread.
|
static <T extends ParseObject> |
ParseQuery.getQuery(Class<T> subclass)
Creates a new query for the given
ParseObject
subclass type.
|
static <T extends ParseObject> |
ParseQuery.getQuery(String className)
Creates a new query for the given class name.
|
<T extends ParseObject> |
ParseObject.getRelation(String key)
Access or create a
ParseRelation
value for a key
|
static <T extends ParseObject> |
ParseQuery.or(List<ParseQuery<T>> queries)
Constructs a query that is the
or of the given queries.
|
static <T extends ParseObject>
|
ParseObject.pinAll(List<T> objects)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject>
|
ParseObject.pinAll(String name,
List<T> objects)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject> |
ParseObject.pinAllInBackground(List<T> objects)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject>
|
ParseObject.pinAllInBackground(List<T> objects,
SaveCallback callback)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject> |
ParseObject.pinAllInBackground(String name,
List<T> objects)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject>
|
ParseObject.pinAllInBackground(String name,
List<T> objects,
SaveCallback callback)
Stores the objects and every object they point to in the local datastore,
recursively.
|
static <T extends ParseObject>
|
ParseObject.saveAll(List<T> objects)
Saves each object in the provided list.
|
static <T extends ParseObject> |
ParseObject.saveAllInBackground(List<T> objects)
Saves each object in the provided list to the server in a background
thread.
|
static <T extends ParseObject>
|
ParseObject.saveAllInBackground(List<T> objects,
SaveCallback callback)
Saves each object in the provided list to the server in a background
thread.
|
static <T extends ParseObject>
|
ParseObject.unpinAll(List<T> objects)
Removes the objects and every object they point to in the local
datastore, recursively.
|
static <T extends ParseObject>
|
ParseObject.unpinAll(String name,
List<T> objects)
Removes the objects and every object they point to in the local
datastore, recursively.
|
static <T extends ParseObject> |
ParseObject.unpinAllInBackground(List<T> objects)
Removes the objects and every object they point to in the local
datastore, recursively.
|
static <T extends ParseObject>
|
ParseObject.unpinAllInBackground(List<T> objects,
DeleteCallback callback)
Removes the objects and every object they point to in the local
datastore, recursively.
|
static <T extends ParseObject> |
ParseObject.unpinAllInBackground(String name,
List<T> objects)
Removes the objects and every object they point to in the local
datastore, recursively.
|
static <T extends ParseObject>
|
ParseObject.unpinAllInBackground(String name,
List<T> objects,
DeleteCallback callback)
Removes the objects and every object they point to in the local
datastore, recursively.
|
| Modifier and Type | Method and Description |
|---|---|
static ParseObject |
ParseObject.create(String className)
Creates a new
ParseObject based upon a class name. |
static ParseObject |
ParseObject.createWithoutData(String className,
String objectId)
Creates a reference to an existing
ParseObject for use
in creating associations between
ParseObject s.
|
ParseObject |
ParseObject.getParseObject(String key)
Access a
ParseObject value. |
| Modifier and Type | Method and Description |
|---|---|
void |
RefreshCallback.done(ParseObject object,
ParseException e)
Override this function with the code you want to run after the save
is complete.
|
boolean |
ParseObject.hasSameId(ParseObject other) |
| Modifier and Type | Method and Description |
|---|---|
static void |
ParseObject.registerSubclass(Class<? extends ParseObject> subclass)
Registers a custom subclass type with the Parse SDK, enabling
strong-typing of those
ParseObject s whenever they appear.
|
| Constructor and Description |
|---|
ParseQueryAdapter(Context context,
Class<? extends ParseObject> clazz)
Constructs a
ParseQueryAdapter . |
ParseQueryAdapter(Context context,
Class<? extends ParseObject> clazz,
int itemViewResource)
Constructs a
ParseQueryAdapter . |


MakeMethod ( _F_, _homeObject_, _classObject_ )
The abstract operation MakeMethod takes arguments _F_ and _homeObject_, _homeObject_, and _classObject_. It configures _F_ as a method. It performs the following steps when called:
1. Assert: _F_ is an ECMAScript function object.
1. Assert: Type(_homeObject_) is Object.
1. Assert: Type(_classObject_) is either Object or Undefined.
1. Set _F_.[[HomeObject]] to _homeObject_.
1. Set _F_.[[InitialClassObject]] to _classObject_.
1. Return NormalCompletion(*undefined*).


Machine Learning App with Flask
Job title Classification by industry
Predicted Industry is
" {{ prediction }} "


Layers¶
PaddingMode¶
-
tensorrt.
PaddingMode
¶ - Enumerates types of padding available in convolution, deconvolution and pooling layers.
Padding mode takes precedence if both
padding_mode
andpre_padding
are set.EXPLICIT* corresponds to explicit padding.SAME* implicitly calculates padding such that the output dimensions are the same as the input dimensions. For convolution and pooling, output dimensions are determined by ceil(input dimensions, stride).CAFFE* corresponds to symmetric padding.
Members:
EXPLICIT_ROUND_DOWN : Use explicit padding, rounding the output size down
EXPLICIT_ROUND_UP : Use explicit padding, rounding the output size up
SAME_UPPER : Use SAME padding, with
pre_padding
<=post_padding
SAME_LOWER : Use SAME padding, with
pre_padding
>=post_padding
CAFFE_ROUND_DOWN : Use CAFFE padding, rounding the output size down
CAFFE_ROUND_UP : Use CAFFE padding, rounding the output size up
IConvolutionLayer¶
-
class
tensorrt.
IConvolutionLayer
¶ A convolution layer in an
INetworkDefinition
.This layer performs a correlation operation between 3-dimensional filter with a 4-dimensional tensor to produce another 4-dimensional tensor.
An optional bias argument is supported, which adds a per-channel constant to each value in the output.
Variables: - kernel_size –
DimsHW
The HW kernel size of the convolution. - num_output_maps –
int
The number of output maps for the convolution. - stride –
DimsHW
The stride of the convolution. Default: (1, 1) - padding –
DimsHW
The padding of the convolution. The input will be zero-padded by this number of elements in the height and width directions. If the padding is asymmetric, this value corresponds to the pre-padding. Default: (0, 0) - pre_padding –
DimsHW
The pre-padding. The start of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - post_padding –
DimsHW
The post-padding. The end of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - padding_mode –
PaddingMode
The padding mode. Padding mode takes precedence if bothIConvolutionLayer.padding_mode
and eitherIConvolutionLayer.pre_padding
orIConvolutionLayer.post_padding
are set. - num_groups –
int
The number of groups for a convolution. The input tensor channels are divided into this many groups, and a convolution is executed for each group, using a filter per group. The results of the group convolutions are concatenated to form the output. Note When using groups in int8 mode, the size of the groups (i.e. the channel count divided by the group count) must be a multiple of 4 for both input and output. Default: 1. - kernel –
Weights
The kernel weights for the convolution. The weights are specified as a contiguous array in GKCRS order, where G is the number of groups, K the number of output feature maps, C the number of input channels, and R and S are the height and width of the filter. - bias –
Weights
The bias weights for the convolution. Bias is optional. To omit bias, set this to an emptyWeights
object. The bias is applied per-channel, so the number of weights (if non-zero) must be equal to the number of output feature maps. - dilation –
DimsHW
The dilation for a convolution. Default: (1, 1) - kernel_size_nd –
Dims
The multi-dimension kernel size of the convolution. - stride_nd –
Dims
The multi-dimension stride of the convolution. Default: (1, …, 1) - padding_nd –
Dims
The multi-dimension padding of the convolution. The input will be zero-padded by this number of elements in each dimension. If the padding is asymmetric, this value corresponds to the pre-padding. Default: (0, …, 0) - dilation_nd –
Dims
The multi-dimension dilation for the convolution. Default: (1, …, 1)
- kernel_size –
IFullyConnectedLayer¶
-
class
tensorrt.
IFullyConnectedLayer
¶ A fully connected layer in an
INetworkDefinition
.This layer expects an input tensor of three or more non-batch dimensions. The input is automatically reshaped into an MxV tensor X, where V is a product of the last three dimensions and M is a product of the remaining dimensions (where the product over 0 dimensions is defined as 1). For example:
- If the input tensor has shape {C, H, W}, then the tensor is reshaped into {1, C*H*W} .
- If the input tensor has shape {P, C, H, W}, then the tensor is reshaped into {P, C*H*W} .
The layer then performs:
\(Y := matmul(X, W^T) + bias\)
Where X is the MxV tensor defined above, W is the KxV weight tensor of the layer, and bias is a row vector size K that is broadcasted to MxK . K is the number of output channels, and configurable via
IFullyConnectedLayer.num_output_channels
. If bias is not specified, it is implicitly 0 .The MxK result Y is then reshaped such that the last three dimensions are {K, 1, 1} and the remaining dimensions match the dimensions of the input tensor. For example:
- If the input tensor has shape {C, H, W}, then the output tensor will have shape {K, 1, 1} .
- If the input tensor has shape {P, C, H, W}, then the output tensor will have shape {P, K, 1, 1} .
Variables:
IActivationLayer¶
-
tensorrt.
ActivationType
¶ The type of activation to perform.
Members:
RELU : Rectified Linear activation
SIGMOID : Sigmoid activation
TANH : Hyperbolic Tangent activation
LEAKY_RELU : Leaky Relu activation: f(x) = x if x >= 0, f(x) = alpha * x if x < 0
ELU : Elu activation: f(x) = x if x >= 0, f(x) = alpha * (exp(x) - 1) if x < 0
SELU : Selu activation: f(x) = beta * x if x > 0, f(x) = beta * (alpha * exp(x) - alpha) if x <= 0
SOFTSIGN : Softsign activation: f(x) = x / (1 + abs(x))
SOFTPLUS : Softplus activation: f(x) = alpha * log(exp(beta * x) + 1)
CLIP : Clip activation: f(x) = max(alpha, min(beta, x))
HARD_SIGMOID : Hard sigmoid activation: f(x) = max(0, min(1, alpha * x + beta))
SCALED_TANH : Scaled Tanh activation: f(x) = alpha * tanh(beta * x)
THRESHOLDED_RELU : Thresholded Relu activation: f(x) = x if x > alpha, f(x) = 0 if x <= alpha
-
class
tensorrt.
IActivationLayer
¶ An Activation layer in an
INetworkDefinition
. This layer applies a per-element activation function to its input. The output has the same shape as the input.Variables: - type –
ActivationType
The type of activation to be performed. - alpha –
float
The alpha parameter that is used by some parametric activations (LEAKY_RELU, ELU, SELU, SOFTPLUS, CLIP, HARD_SIGMOID, SCALED_TANH). Other activations ignore this parameter. - beta –
float
The beta parameter that is used by some parametric activations (SELU, SOFTPLUS, CLIP, HARD_SIGMOID, SCALED_TANH). Other activations ignore this parameter.
- type –
IPoolingLayer¶
-
tensorrt.
PoolingType
¶ The type of pooling to perform in a pooling layer.
Members:
MAX : Maximum over elements
AVERAGE : Average over elements. If the tensor is padded, the count includes the padding
MAX_AVERAGE_BLEND : Blending between the max pooling and average pooling: (1-blendFactor)*maxPool + blendFactor*avgPool
-
class
tensorrt.
IPoolingLayer
¶ A Pooling layer in an
INetworkDefinition
. The layer applies a reduction operation within a window over the input.Variables: - type –
PoolingType
The type of pooling to be performed. - window_size –
DimsHW
The window size for pooling. - stride –
DimsHW
The stride for pooling. Default: (1, 1) - padding –
DimsHW
The padding for pooling. Default: (0, 0) - pre_padding –
DimsHW
The pre-padding. The start of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - post_padding –
DimsHW
The post-padding. The end of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - padding_mode –
PaddingMode
The padding mode. Padding mode takes precedence if bothIPoolingLayer.padding_mode
and eitherIPoolingLayer.pre_padding
orIPoolingLayer.post_padding
are set. - blend_factor –
float
The blending factor for the max_average_blend mode: \(max_average_blendPool = (1-blendFactor)*maxPool + blendFactor*avgPool\) .blend_factor
is a user value in [0,1] with the default value of 0.0. This value only applies for thePoolingType.MAX_AVERAGE_BLEND
mode. - average_count_excludes_padding –
bool
Whether average pooling uses as a denominator the overlap area between the window and the unpadded input. If this is not set, the denominator is the overlap between the pooling window and the padded input. Default: True - window_size_nd –
Dims
The multi-dimension window size for pooling. - stride_nd –
Dims
The multi-dimension stride for pooling. Default: (1, …, 1) - padding_nd –
Dims
The multi-dimension padding for pooling. Default: (0, …, 0)
- type –
ILRNLayer¶
-
class
tensorrt.
ILRNLayer
¶ A LRN layer in an
INetworkDefinition
. The output size is the same as the input size.Variables: - window_size –
int
The LRN window size. The window size must be odd and in the range of [1, 15]. - alpha –
float
The LRN alpha value. The valid range is [-1e20, 1e20]. - beta –
float
The LRN beta value. The valid range is [0.01, 1e5f]. - k –
float
The LRN K value. The valid range is [1e-5, 1e10].
- window_size –
IScaleLayer¶
-
tensorrt.
ScaleMode
¶ Controls how scale is applied in a Scale layer.
Members:
UNIFORM : Identical coefficients across all elements of the tensor.
CHANNEL : Per-channel coefficients. The channel dimension is assumed to be the third to last dimension.
ELEMENTWISE : Elementwise coefficients.
-
class
tensorrt.
IScaleLayer
¶ A Scale layer in an
INetworkDefinition
.This layer applies a per-element computation to its input:
\(output = (input * scale + shift) ^ power\)
The coefficients can be applied on a per-tensor, per-channel, or per-element basis.
Note If the number of weights is 0, then a default value is used for shift, power, and scale. The default shift is 0, the default power is 1, and the default scale is 1.
The output size is the same as the input size.
Note The input tensor for this layer is required to have a minimum of 3 dimensions.
Variables:
ISoftMaxLayer¶
-
class
tensorrt.
ISoftMaxLayer
¶ A Softmax layer in an
INetworkDefinition
.This layer applies a per-channel softmax to its input.
The output size is the same as the input size.
Variables: axes – int
The axes along which softmax is computed. Currently, only one axis can be set. The axis is specified by setting the bit corresponding to the axis, after excluding the batch dimension, to 1. Let’s say we have an NCHW tensor as input (three non-batch dimensions). Bit 0 corresponds to the C dimension boolean. Bit 1 corresponds to the H dimension boolean. Bit 2 corresponds to the W dimension boolean. For example, to perform softmax on axis R of a NPQRCHW input, set bit 2. By default, softmax is performed on the axis which is the number of non-batch axes minus three. It is 0 if there are fewer than 3 non-batch axes. For example, if the input is NCHW, the default axis is C. If the input is NHW, then the default axis is H.
IConcatenationLayer¶
-
class
tensorrt.
IConcatenationLayer
¶ A concatenation layer in an
INetworkDefinition
.The output channel size is the sum of the channel sizes of the inputs. The other output sizes are the same as the other input sizes, which must all match.
Variables: axis – int
The axis along which concatenation occurs. 0 is the major axis (excluding the batch dimension). The default is the number of non-batch axes in the tensor minus three (e.g. for an NCHW input it would be 0), or 0 if there are fewer than 3 non-batch axes.
IDeconvolutionLayer¶
-
class
tensorrt.
IDeconvolutionLayer
¶ A deconvolution layer in an
INetworkDefinition
.Variables: - kernel_size –
DimsHW
The HW kernel size of the convolution. - num_output_maps –
int
The number of output feature maps for the deconvolution. - stride –
DimsHW
The stride of the deconvolution. Default: (1, 1) - padding –
DimsHW
The padding of the deconvolution. The input will be zero-padded by this number of elements in the height and width directions. Padding is symmetric. Default: (0, 0) - pre_padding –
DimsHW
The pre-padding. The start of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - post_padding –
DimsHW
The post-padding. The end of input will be zero-padded by this number of elements in the height and width directions. Default: (0, 0) - padding_mode –
PaddingMode
The padding mode. Padding mode takes precedence if bothIDeconvolutionLayer.padding_mode
and eitherIDeconvolutionLayer.pre_padding
orIDeconvolutionLayer.post_padding
are set. - num_groups –
int
The number of groups for a deconvolution. The input tensor channels are divided into this many groups, and a deconvolution is executed for each group, using a filter per group. The results of the group convolutions are concatenated to form the output. Note When using groups in int8 mode, the size of the groups (i.e. the channel count divided by the group count) must be a multiple of 4 for both input and output. Default: 1 - kernel –
Weights
The kernel weights for the deconvolution. The weights are specified as a contiguous array in CKRS order, where C the number of input channels, K the number of output feature maps, and R and S are the height and width of the filter. - bias –
Weights
The bias weights for the deconvolution. Bias is optional. To omit bias, set this to an emptyWeights
object. The bias is applied per-feature-map, so the number of weights (if non-zero) must be equal to the number of output feature maps. - kernel_size_nd –
Dims
The multi-dimension kernel size of the convolution. - stride_nd –
Dims
The multi-dimension stride of the deconvolution. Default: (1, …, 1) - padding_nd –
Dims
The multi-dimension padding of the deconvolution. The input will be zero-padded by this number of elements in each dimension. Padding is symmetric. Default: (0, …, 0)
- kernel_size –
IElementWiseLayer¶
-
tensorrt.
ElementWiseOperation
¶ The binary operations that may be performed by an ElementWise layer.
Members:
SUM : Sum of the two elements
PROD : Product of the two elements
MAX : Max of the two elements
MIN : Min of the two elements
SUB : Subtract the second element from the first
DIV : Divide the first element by the second
POW : The first element to the power of the second element
FLOOR_DIV : Floor division of the first element by the second
-
class
tensorrt.
IElementWiseLayer
¶ A elementwise layer in an
INetworkDefinition
.This layer applies a per-element binary operation between corresponding elements of two tensors.
The input dimensions of the two input tensors must be equal, and the output tensor is the same size as each input.
Variables: op – ElementWiseOperation
The binary operation for the layer.
IGatherLayer¶
-
class
tensorrt.
IGatherLayer
¶ A gather layer in an
INetworkDefinition
.Variables: - axis –
int
The non-batch dimension axis to gather on. The axis must be less than the number of non-batch dimensions in the data input. - num_elementwise_dims –
int
The number of leading dimensions of indices tensor to be handled elementwise. Must be 0 if there is an implicit batch dimension. It can be 0 or 1 if there is not an implicit batch dimension.
- axis –
RNN Layers¶
-
tensorrt.
RNNOperation
¶ The RNN operations that may be performed by an RNN layer.
Equation definitions
In the equations below, we use the following naming convention:
t := current time stepi := input gateo := output gatef := forget gatez := update gater := reset gatec := cell gateh := hidden gateg[t] denotes the output of gate g at timestep t, e.g.`f[t]` is the output of the forget gate f .X[t] := input tensor for timestep tC[t] := cell state for timestep tH[t] := hidden state for timestep tW[g] := W (input) parameter weight matrix for gate gR[g] := U (recurrent) parameter weight matrix for gate gWb[g] := W (input) parameter bias vector for gate gRb[g] := U (recurrent) parameter bias vector for gate gUnless otherwise specified, all operations apply pointwise to elements of each operand tensor.
ReLU(X) := max(X, 0)tanh(X) := hyperbolic tangent of Xsigmoid(X) := 1 / (1 + exp(-X))exp(X) := e^XA.B denotes matrix multiplication of A and B .A*B denotes pointwise multiplication of A and B .Equations
Depending on the value of RNNOperation chosen, each sub-layer of the RNN layer will perform one of the following operations:
RELU
\(H[t] := ReLU(W[i].X[t] + R[i].H[t-1] + Wb[i] + Rb[i])\)
TANH
\(H[t] := tanh(W[i].X[t] + R[i].H[t-1] + Wb[i] + Rb[i])\)
LSTM
\(i[t] := sigmoid(W[i].X[t] + R[i].H[t-1] + Wb[i] + Rb[i])\)\(f[t] := sigmoid(W[f].X[t] + R[f].H[t-1] + Wb[f] + Rb[f])\)\(o[t] := sigmoid(W[o].X[t] + R[o].H[t-1] + Wb[o] + Rb[o])\)\(c[t] := tanh(W[c].X[t] + R[c].H[t-1] + Wb[c] + Rb[c])\)\(C[t] := f[t]*C[t-1] + i[t]*c[t]\)\(H[t] := o[t]*tanh(C[t])\)GRU
\(z[t] := sigmoid(W[z].X[t] + R[z].H[t-1] + Wb[z] + Rb[z])\)\(r[t] := sigmoid(W[r].X[t] + R[r].H[t-1] + Wb[r] + Rb[r])\)\(h[t] := tanh(W[h].X[t] + r[t]*(R[h].H[t-1] + Rb[h]) + Wb[h])\)\(H[t] := (1 - z[t])*h[t] + z[t]*H[t-1]\)Members:
RELU : Single gate RNN w/ ReLU activation
TANH : Single gate RNN w/ TANH activation
LSTM : Four-gate LSTM network w/o peephole connections
GRU : Three-gate network consisting of Gated Recurrent Units
-
tensorrt.
RNNDirection
¶ The RNN direction that may be performed by an RNN layer.
Members:
UNIDIRECTION : Network iterates from first input to last input
BIDIRECTION : Network iterates from first to last (and vice versa) and outputs concatenated
-
tensorrt.
RNNInputMode
¶ The RNN input modes that may occur with an RNN layer.
If the RNN is configured with
RNNInputMode.LINEAR
, then for each gate g in the first layer of the RNN, the input vector X[t] (length E) is left-multiplied by the gate’s corresponding weight matrix W[g] (dimensions HxE) as usual, before being used to compute the gate output as described byRNNOperation
.If the RNN is configured with
RNNInputMode.SKIP
, then this initial matrix multiplication is “skipped” and W[g] is conceptually an identity matrix. In this case, the input vector X[t] must have length H (the size of the hidden state).Members:
LINEAR : Perform the normal matrix multiplication in the first recurrent layer
SKIP : No operation is performed on the first recurrent layer
IRNNLayer¶
Deprecated since version 4.0.
-
class
tensorrt.
IRNNLayer
¶ An RNN layer in an
INetworkDefinition
.This layer applies an RNN operation on the inputs.
Deprecated This interface is superseded by IRNNv2Layer.
Variables: - num_layers –
int
The number of layers in the RNN. - hidden_size –
int
The size of the hidden layers. - max_seq_length –
int
The sequence length. This is the maximum number of input tensors that the RNN can process at once. - op –
RNNOperation
The operation of the RNN layer. - input_mode –
RNNInputMode
The input mode of the RNN layer. - direction –
RNNDirection
the direction of the RNN layer. The direction determines if the RNN is run as a unidirectional(left to right) or bidirectional(left to right and right to left). In theRNNDirection.BIDIRECTION
case the output is concatenated together, resulting in output size of 2xhidden_size
. - weights –
Weights
The weight parameters for the RNN. For more information, see IRNNLayer::setWeights(). - bias –
Weights
The bias parameter vector for the RNN layer. For more information see IRNNLayer::setBias(). - data_length –
int
The length of the data being processed by the RNN for use in computing other values. - hidden_state –
ITensor
the initial hidden state of the RNN with the provided hidden ITensor. The layout for hidden is a linear layout of a 3D matrix: C - The number of layers in the RNN, it must matchnum_layers
. H - The number of mini-batches for each time sequence. W - The size of the per layer hidden states, it must matchhidden_size
. The amount of space required is doubled ifdirection
isRNNDirection.BIDIRECTION
with the bidirectional states coming after the unidirectional states. If not specified, then the initial hidden state is set to zero. - cell_state –
ITensor
the initial cell state of the RNN with the provided cell ITensor. The layout for cell is a linear layout of a 3D matrix: C - The number of layers in the RNN, it must matchnum_layers
. H - The number of mini-batches for each time sequence. W - The size of the per layer hidden states, it must matchhidden_size
. The amount of space required is doubled ifdirection
isRNNDirection.BIDIRECTION
with the bidirectional states coming after the unidirectional states. If not specified, then the initial cell state is set to zero. The cell state only affects LSTM RNN’s.
- num_layers –
IRNNv2Layer¶
-
tensorrt.
RNNGateType
¶ The RNN input modes that may occur with an RNN layer.
If the RNN is configured with
RNNInputMode.LINEAR
, then for each gate g in the first layer of the RNN, the input vector X[t] (length E) is left-multiplied by the gate’s corresponding weight matrix W[g] (dimensions HxE) as usual, before being used to compute the gate output as described byRNNOperation
.If the RNN is configured with
RNNInputMode.SKIP
, then this initial matrix multiplication is “skipped” and W[g] is conceptually an identity matrix. In this case, the input vector X[t] must have length H (the size of the hidden state).Members:
INPUT : Input Gate
OUTPUT : Output Gate
FORGET : Forget Gate
UPDATE : Update Gate
RESET : Reset Gate
CELL : Cell Gate
HIDDEN : Hidden Gate
-
class
tensorrt.
IRNNv2Layer
¶ An RNN layer in an
INetworkDefinition
, version 2Variables: - num_layers –
int
The layer count of the RNN. - hidden_size –
int
The hidden size of the RNN. - max_seq_length –
int
The maximum sequence length of the RNN - data_length –
int
The layer count of the RNN. - seq_lengths –
ITensor
Individual sequence lengths in the batch with theITensor
provided. Theseq_lengths
ITensor
should be a {N1, …, Np} tensor, where N1..Np are the index dimensions of the input tensor to the RNN. Ifseq_lengths
is not specified, then the RNN layer assumes all sequences are sizemax_seq_length
. All sequence lengths inseq_lengths
should be in the range [1,max_seq_length
]. Zero-length sequences are not supported. This tensor must be of type int32. - op –
RNNOperation
The operation of the RNN layer. - input_mode –
int
The input mode of the RNN layer. - direction –
int
The direction of the RNN layer. - hidden_state –
ITensor
the initial hidden state of the RNN with the providedhidden_state
ITensor
. Thehidden_state
ITensor
should have the dimensions {N1, …, Np, L, H}, where: N1..Np are the index dimensions specified by the input tensor L is the number of layers in the RNN, equal tonum_layers
H is the hidden state for each layer, equal tohidden_size
ifdirection
isRNNDirection.UNIDIRECTION
, and 2xhidden_size
otherwise. - cell_state –
ITensor
The initial cell state of the LSTM with the providedcell_state
ITensor
. Thecell_state
ITensor
should have the dimensions {N1, …, Np, L, H}, where: N1..Np are the index dimensions specified by the input tensor L is the number of layers in the RNN, equal tonum_layers
H is the hidden state for each layer, equal tohidden_size
ifdirection
isRNNDirection.UNIDIRECTION
, and 2xhidden_size
otherwise. It is an error to set this on an RNN layer that is not configured withRNNOperation.LSTM
.
-
get_bias_for_gate
(self: tensorrt.tensorrt.IRNNv2Layer, layer_index: int, gate: tensorrt.tensorrt.RNNGateType, is_w: bool) → array¶ Get the bias parameters for an individual gate in the RNN.
Parameters: - layer_index – The index of the layer that contains this gate.
- gate – The name of the gate within the RNN layer.
- is_w – True if the bias parameters are for the input bias Wb[g] and false if they are for the recurrent input bias Rb[g].
Returns: The bias parameters.
-
get_weights_for_gate
(self: tensorrt.tensorrt.IRNNv2Layer, layer_index: int, gate: tensorrt.tensorrt.RNNGateType, is_w: bool) → array¶ Get the weight parameters for an individual gate in the RNN.
Parameters: - layer_index – The index of the layer that contains this gate.
- gate – The name of the gate within the RNN layer.
- is_w – True if the weight parameters are for the input matrix W[g] and false if they are for the recurrent input matrix R[g].
Returns: The weight parameters.
-
set_bias_for_gate
(self: tensorrt.tensorrt.IRNNv2Layer, layer_index: int, gate: tensorrt.tensorrt.RNNGateType, is_w: bool, bias: tensorrt.tensorrt.Weights) → None¶ Set the bias parameters for an individual gate in the RNN.
Parameters: - layer_index – The index of the layer that contains this gate. Refer to
IRNNLayer.weights
for a description of the layer index. - gate – The name of the gate within the RNN layer. The gate name must correspond to one of the gates used by this layer’s
RNNOperation
. - is_w – True if the bias parameters are for the input bias Wb[g] and false if they are for the recurrent input bias Rb[g]. See
RNNOperation
for equations showing how these bias vectors are used in the RNN gate. - bias – The weight structure holding the bias parameters, which should be an array of size
hidden_size
.
- layer_index – The index of the layer that contains this gate. Refer to
-
set_weights_for_gate
(self: tensorrt.tensorrt.IRNNv2Layer, layer_index: int, gate: tensorrt.tensorrt.RNNGateType, is_w: bool, weights: tensorrt.tensorrt.Weights) → None¶ Set the weight parameters for an individual gate in the RNN.
Parameters: - layer_index – The index of the layer that contains this gate. Refer to
IRNNLayer.weights
for a description of the layer index. - gate – The name of the gate within the RNN layer. The gate name must correspond to one of the gates used by this layer’s
RNNOperation
. - is_w – True if the weight parameters are for the input matrix W[g] and false if they are for the recurrent input matrix R[g]. See
RNNOperation
for equations showing how these matrices are used in the RNN gate. - weights – The weight structure holding the weight parameters, which are stored as a row-major 2D matrix. Refer to
IRNNLayer.weights
for documentation on the expected dimensions of this matrix.
- layer_index – The index of the layer that contains this gate. Refer to
- num_layers –
IPluginLayer¶
-
class
tensorrt.
IPluginLayer
¶ A plugin layer in an
INetworkDefinition
.Variables: plugin – IPlugin
The plugin for the layer.
IPluginV2Layer¶
-
class
tensorrt.
IPluginV2Layer
¶ A plugin layer in an
INetworkDefinition
.Variables: plugin – IPluginV2
The plugin for the layer.
IUnaryLayer¶
-
tensorrt.
UnaryOperation
¶ The unary operations that may be performed by a Unary layer.
Members:
EXP : Exponentiation
LOG : Log (base e)
SQRT : Square root
RECIP : Reciprocal
ABS : Absolute value
NEG : Negation
SIN : Sine
COS : Cosine
TAN : Tangent
SINH : Hyperbolic sine
COSH : Hyperbolic cosine
ASIN : Inverse sine
ACOS : Inverse cosine
ATAN : Inverse tangent
ASINH : Inverse hyperbolic sine
ACOSH : Inverse hyperbolic cosine
ATANH : Inverse hyperbolic tangent
CEIL : Ceiling
FLOOR : Floor
-
class
tensorrt.
IUnaryLayer
¶ A unary layer in an
INetworkDefinition
.Variables: op – UnaryOperation
The unary operation for the layer.
IReduceLayer¶
-
tensorrt.
ReduceOperation
¶ The reduce operations that may be performed by a Reduce layer
Members:
SUM :
PROD :
MAX :
MIN :
AVG :
-
class
tensorrt.
IReduceLayer
¶ A reduce layer in an
INetworkDefinition
.Variables: - op –
ReduceOperation
The reduce operation for the layer. - axes –
int
The axes over which to reduce. - keep_dims –
bool
Specifies whether or not to keep the reduced dimensions for the layer.
- op –
IPaddingLayer¶
-
class
tensorrt.
IPaddingLayer
¶ A padding layer in an
INetworkDefinition
.Variables:
IShuffleLayer¶
-
class
tensorrt.
Permutation
(*args, **kwargs)¶ The elements of the permutation. The permutation is applied as outputDimensionIndex = permutation[inputDimensionIndex], so to permute from CHW order to HWC order, the required permutation is [1, 2, 0], and to permute from HWC to CHW, the required permutation is [2, 0, 1].
It supports iteration and indexing and is implicitly convertible to/from Python iterables (like
tuple
orlist
). Therefore, you can use those classes in place ofPermutation
.Overloaded function.
- __init__(self: tensorrt.tensorrt.Permutation) -> None
- __init__(self: tensorrt.tensorrt.Permutation, arg0: List[int]) -> None
-
class
tensorrt.
IShuffleLayer
¶ A shuffle layer in an
INetworkDefinition
.This class shuffles data by applying in sequence: a transpose operation, a reshape operation and a second transpose operation. The dimension types of the output are those of the reshape dimension.
Variables: - first_transpose –
Permutation
The permutation applied by the first transpose operation. Default: Identity Permutation - reshape_dims –
Permutation
The reshaped dimensions. Two special values can be used as dimensions. Value 0 copies the corresponding dimension from input. This special value can be used more than once in the dimensions. If number of reshape dimensions is less than input, 0s are resolved by aligning the most significant dimensions of input. Value -1 infers that particular dimension by looking at input and rest of the reshape dimensions. Note that only a maximum of one dimension is permitted to be specified as -1. The product of the new dimensions must be equal to the product of the old. - second_transpose –
Permutation
The permutation applied by the second transpose operation. Default: Identity Permutation
- first_transpose –
ISliceLayer¶
-
class
tensorrt.
ISliceLayer
¶ A slice layer in an
INetworkDefinition
.Variables: -
set_input
(self: tensorrt.tensorrt.ISliceLayer, index: int, tensor: tensorrt.tensorrt.ITensor) → None¶ Sets the input tensor for the given index. The index must be 0 for a static slice layer. A static slice layer is converted to a dynamic slice layer by calling setInput with an index > 0. A dynamic slice layer cannot be converted back to a static slice layer.
For a dynamic slice layer, the values 0-3 are valid. If an index > 0 is specified, all values between index 0 and that index must be dynamic tensors. The values larger than index can use static dimensions. For example, if an index of two is specified, the stride tensor can be set via setStride, but the start tensor must be specified via setInput as both size and start are converted to dynamic tensors. The indices in the dynamic case are as follows:
Index | Description0 | Data or Shape tensor to be sliced.1 | The start tensor to begin slicing, N-dimensional for Data, and 1-D for Shape.2 | The size tensor of the resulting slice, N-dimensional for Data, and 1-D for Shape.3 | The stride of the slicing operation, N-dimensional for Data, and 1-D for Shape.If this function is called with a value greater than 0, then the function getNbInputs() changes from returning 1 to index + 1. When converting from static to dynamic slice layer, all unset tensors, between 1 and index + 1, are initialized to nullptr. It is an error to attempt to build a network that has any nullptr inputs.
Parameters: - index – The index of the input tensor.
- tensor – The input tensor.
-
IShapeLayer¶
-
class
tensorrt.
IShapeLayer
¶ A shape layer in an
INetworkDefinition
. Used for getting the shape of a tensor. This class sets the output to a one-dimensional tensor with the dimensions of the input tensor.For example, if the input is a four-dimensional tensor (of any type) with dimensions [2,3,5,7], the output tensor is a one-dimensional Int32 tensor of length 4 containing the sequence 2, 3, 5, 7.
ITopKLayer¶
-
tensorrt.
TopKOperation
¶ The operations that may be performed by a TopK layer
Members:
MAX : Maximum of the elements
MIN : Minimum of the elements
-
class
tensorrt.
ITopKLayer
¶ A TopK layer in an
INetworkDefinition
.Variables: - op –
TopKOperation
The operation for the layer. - k –
TopKOperation
the k value for the layer. Currently only values up to 25 are supported. - axes –
TopKOperation
The axes along which to reduce.
- op –
IMatrixMultiplyLayer¶
-
tensorrt.
MatrixOperation
¶ The matrix operations that may be performed by a Matrix layer
Members:
NONE :
TRANSPOSE : Transpose each matrix
VECTOR : Treat operand as collection of vectors
-
class
tensorrt.
IMatrixMultiplyLayer
¶ A matrix multiply layer in an
INetworkDefinition
.Let A be op(getInput(0)) and B be op(getInput(1)) where op(x) denotes the corresponding MatrixOperation.
When A and B are matrices or vectors, computes the inner product A * B:
matrix * matrix -> matrixmatrix * vector -> vectorvector * matrix -> vectorvector * vector -> scalarInputs of higher rank are treated as collections of matrices or vectors. The output will be a corresponding collection of matrices, vectors, or scalars.
Variables: - op0 –
MatrixOperation
How to treat the first input. - op1 –
MatrixOperation
How to treat the second input.
- op0 –
IRaggedSoftMaxLayer¶
-
class
tensorrt.
IRaggedSoftMaxLayer
¶ A ragged softmax layer in an
INetworkDefinition
.This layer takes a ZxS input tensor and an additional Zx1 bounds tensor holding the lengths of the Z sequences.
This layer computes a softmax across each of the Z sequences.
The output tensor is of the same size as the input tensor.
IIdentityLayer¶
-
class
tensorrt.
IIdentityLayer
¶ A layer that represents the identity function.
If tensor precision is explicitly specified, it can be used to transform from one precision to another.
IConstantLayer¶
-
class
tensorrt.
IConstantLayer
¶ A constant layer in an
INetworkDefinition
.Variables:
IResizeLayer¶
-
tensorrt.
ResizeMode
¶ Various modes of resize in the resize layer.
Members:
NEAREST : 1D, 2D, and 3D nearest neighbor resizing.
LINEAR : Can handle linear, bilinear, trilinear resizing.
-
class
tensorrt.
IResizeLayer
¶ A resize layer in an
INetworkDefinition
.Resize layer can be used for resizing a N-D tensor.
Resize layer currently supports the following configurations:
- ResizeMode::kNEAREST - resizes innermost m dimensions of N-D, where 0 < m <= min(3, N) and N > 0.
- ResizeMode::kLINEAR - resizes innermost m dimensions of N-D, where 0 < m <= min(3, N) and N > 0.
Default resize mode is ResizeMode::kNEAREST.
Resize layer provides two ways to resize tensor dimensions:
- Set output dimensions directly. It can be done for static as well as dynamic resize layer. Static resize layer requires output dimensions to be known at build-time. Dynamic resize layer requires output dimensions to be set as one of the input tensors.
- Set scales for resize. Each output dimension is calculated as floor(input dimension * scale). Only static resize layer allows setting scales where the scales are known at build-time.
Variables: - shape –
Dims
The output dimensions. Must to equal to input dimensions size. - scales –
List[float]
List of resize scales. - resize_mode –
ResizeMode
Resize mode can be Linear or Nearest. - align_corners –
bool
If True, the centers of the 4 corner pixels of both input and output tensors are aligned. Default: False.
-
set_input
(self: tensorrt.tensorrt.IResizeLayer, index: int, tensor: tensorrt.tensorrt.ITensor) → None¶ Sets the input tensor for the given index.
If index == 1 and num_inputs == 1, and there is no implicit batch dimension, in which case num_inputs changes to 2. Once such additional input is set, resize layer works in dynamic mode. When index == 1 and num_inputs == 1, the output dimensions are used from the input tensor, overriding the dimensions supplied by shape.
Parameters: - index – The index of the input tensor.
- tensor – The input tensor.


Active 2019 Atlantic hurricane season comes to an end Saturday
by WFTX Digital TeamLEE COUNTY, Fla. -- NOAA says the 2019 Atlantic hurricane season, which ends on November 30, was marked by tropical activity that churned busily from mid-August through October.
The season produced 18 named storms, including six hurricanes of which three were “major”.
NOAA’s outlook called for 10-17 named storms, 5-9 hurricanes and 2-4 major hurricanes.
The three major hurricanes this season were Dorian, Humberto and Lorenzo.
Hurricane Dorian is tied with three other hurricanes — the 1935 Labor Day Hurricane, 1988’s Hurricane Gilbert and 2005’s Hurricane Wilma — as the second strongest hurricane on record in the Atlantic basin in terms of wind (185 mph).
Four storms made landfall in the U.S. during the 2019 season: Barry, Dorian, Imelda and Nestor.
Barry made landfall in Louisiana as a Category 1 storm on July 13th. One storm-related death was reported in Florida.
Dorian stalled over the northern Bahamas, causing extensive damages before moving west. It was headed directly towards the Florida east coast before veering north just offshore, skirting the Georgia and South Carolina coasts before making an official landfall as a Category 1 in North Carolina on September 6th. Dorian killed more than 70 people, mostly in the Bahamas, and caused more than $6.3 billion in damages.
Imelda made landfall near Freeport, Texas as a tropical storm on September 17. The storm brought more than 40 inches of rain to some areas, causing more than $2 billion in damages.
Tropical Storm Nestor made landfall in the Florida panhandle on October 19. The storm brought moderate damage to the same area recovering from Hurricane Michael in 2018, and caused tornadoes in Polk County and Cape Coral.
During the 2019 season, NOAA’s hurricane hunter aircraft and crews flew 57 missions over 430 hours.
The 2020 hurricane season will officially begin on June 1.


Small files (known as ‘cookies’) are put onto your computer to collect information about how you browse the site.
Cookies are used to:
GOV.UK cookies aren’t used to identify you personally.
You’ll normally see a message on the site before a cookie is stored on your computer.
Find out more about how to manage cookies Opens in new window.
Google Analytics software collects information about how you use the site. This is done to help make sure the site is meeting the needs of its users and to help make improvements.
Google Analytics stores information about:
We don’t collect or store your personal information (eg your name or address) so this information can’t be used to identify who you are.
Google isn’t allowed to use or share our analytics data.
The following cookies are used:
| Name | Purpose | Expires |
|---|---|---|
| _utma | Determines the number of unique visitors to the site | 2 years |
| _utmb | This works with _utmc to calculate the average length of time you spend on our site | 30 minutes |
| _utmc | This works with _utmb to calculate when you close your browser | when you close your browser |
| _utmz | This provides information about how you reached the site (eg from another website or a search engine) | 6 months |
| GDS_successEvents and GDS_analyticsTokens | These help us identify how you use GOV.UK so we can make the site better | 4 months |
These are temporary cookie files, which are erased when you close your browser or after defined time period.
| Name | Purpose | Expires |
|---|---|---|
| _csrf | Protects against cross site request forgery | When you close your browser |
| _ga | Google Analytics cookie | 24 months |
| _gat | Google Analytics cookie | 10 minutes |
| seen_cookie_message | This is used to display a cookie message | 1 month |


We believe that anybody can make substantial profits in the cryptocurrency and digital asset market.
This is exactly why we developed the best exchange with the most unique features.
Our platform is capable of obtaining high trading volumes and generating
substantial profits. Pool trading helps spread your risk while investing in the top
30 cryptocurrencies on the market.


--- title: Substituteteacher.js featured_image: projects/substituteteacher.png link: http://schlosser.github.io/substituteteacher.js date: 2015-05-16 cta: See it in action ---
I built this JavaScript library to package up an implementation of a silly tagline feature on my old personal website. Substituteteacher.js allows for the creation of a rotating set of taglines. Input a list of strings and any configuration options, and the library will tokenize the sentences, find common words, and then animate between pairs of sentences, leaving common words on the page while making room for the appropriate removals, replacements, and additions.
{% include resimg.html src="projects/substituteteacher.gif" %}If configured to do so, Substituteteacher.js will also find an optimal ordering of sentences to minimize the total number of changes needed to animate between all of the input sentences. You can check out a live demo, or view the source on GitHub.


The two values that really stuck out were Accomplishment and Meaningful Work. I'm always trying to live up to these values, it always seems like I have someone in the back of my head telling me to do something more meaningful. That's kinda where I am today, I was unsatisfied with my past and I wanted to push myself as far as I can to see what I can acheive. But I still am always looking for someone else to tell me I'm valuable/needed/wanted.
It's kinda funny, the topics I get asked for advice on tend to deal with sports or relationships. Both things are very, very important in my life but they aren't the values I worry/think about the most. Maybe because I'm happy with those areas in my life and the knowledge I have there, but because I'm not sure about my future career I tend to worry and think about that the most, and claim that I'm the happiest when that is more figure out. I dunno. I think I'll feel more accomplished when my career is figured out, but would I if my relationship wasn't good? Probably not. The people around me know I am strong in certain areas and they ask for advice in those areas, I that is common no matter what. You ask your mechanic for advice on how to fix your car, not on how to fix your teeth. That's what a dentist is for.
I think my values will fit in well at DBC and I still don't feel comfortable comparing myself to any sort of stereotype threat. So many people have and will have it much worse than I have. There will be times at DBC where I feel dumb, or not worthy, or not in the correct line of work. I don't know how to overcome that other than to keep trying and do the best I can. I'm all in on DBC, and I'll be devastated if it doesn't work out.
Nick Siefken