Eloquent: Relationships
- Introduction
- Defining Relationships
- Polymorphic Relationships
- Querying Relations
- Eager Loading
- Inserting & Updating Related Models
- Touching Parent Timestamps
Introduction
Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy, and supports several different types of relationships:
Defining Relationships
Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional constraints on this posts
relationship:
$user->posts()->where('active', 1)->get();
But, before diving too deep into using relationships, let's learn how to define each type.
One To One
A one-to-one relationship is a very basic relation. For example, a User
model might be associated with one Phone
. To define this relationship, we place a phone
method on the User
model. The phone
method should call the hasOne
method and return its result:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
The first argument passed to the hasOne
method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
$phone = User::find(1)->phone;
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone
model is automatically assumed to have a user_id
foreign key. If you wish to override this convention, you may pass a second argument to the hasOne
method:
return $this->hasOne('App\Phone', 'foreign_key');
Additionally, Eloquent assumes that the foreign key should have a value matching the id
(or the custom $primaryKey
) column of the parent. In other words, Eloquent will look for the value of the user's id
column in the user_id
column of the Phone
record. If you would like the relationship to use a value other than id
, you may pass a third argument to the hasOne
method specifying your custom key:
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
Defining The Inverse Of The Relationship
So, we can access the Phone
model from our User
. Now, let's define a relationship on the Phone
model that will let us access the User
that owns the phone. We can define the inverse of a hasOne
relationship using the belongsTo
method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
In the example above, Eloquent will try to match the user_id
from the Phone
model to an id
on the User
model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id
. However, if the foreign key on the Phone
model is not user_id
, you may pass a custom key name as the second argument to the belongsTo
method:
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User', 'foreign_key');
}
If your parent model does not use id
as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo
method specifying your parent table's custom key:
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}
One To Many
A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Remember, Eloquent will automatically determine the proper foreign key column on the Comment
model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id
. So, for this example, Eloquent will assume the foreign key on the Comment
model is post_id
.
Once the relationship has been defined, we can access the collection of comments by accessing the comments
property. Remember, since Eloquent provides "dynamic properties", we can access relationship methods as if they were defined as properties on the model:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
//
}
Since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments
method and continuing to chain conditions onto the query:
$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();
Like the hasOne
method, you may also override the foreign and local keys by passing additional arguments to the hasMany
method:
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
One To Many (Inverse)
Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany
relationship, define a relationship function on the child model which calls the belongsTo
method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Once the relationship has been defined, we can retrieve the Post
model for a Comment
by accessing the post
"dynamic property":
$comment = App\Comment::find(1);
echo $comment->post->title;
In the example above, Eloquent will try to match the post_id
from the Comment
model to an id
on the Post
model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _
followed by the name of the primary key column. However, if the foreign key on the Comment
model is not post_id
, you may pass a custom key name as the second argument to the belongsTo
method:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key');
}
If your parent model does not use id
as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo
method specifying your parent table's custom key:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}
Many To Many
Many-to-many relations are slightly more complicated than hasOne
and hasMany
relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". To define this relationship, three database tables are needed: users
, roles
, and role_user
. The role_user
table is derived from the alphabetical order of the related model names, and contains the user_id
and role_id
columns.
Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany
method. For example, let's define the roles
method on our User
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
Once the relationship is defined, you may access the user's roles using the roles
dynamic property:
$user = App\User::find(1);
foreach ($user->roles as $role) {
//
}
Like all other relationship types, you may call the roles
method to continue chaining query constraints onto the relationship:
$roles = App\User::find(1)->roles()->orderBy('name')->get();
As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany
method:
return $this->belongsToMany('App\Role', 'role_user');
In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany
method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
Defining The Inverse Of The Relationship
To define the inverse of a many-to-many relationship, you place another call to belongsToMany
on your related model. To continue our user roles example, let's define the users
method on the Role
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}
As you can see, the relationship is defined exactly the same as its User
counterpart, with the exception of referencing the App\User
model. Since we're reusing the belongsToMany
method, all of the usual table and key customization options are available when defining the inverse of many-to-many relationships.
Retrieving Intermediate Table Columns
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User
object has many Role
objects that it is related to. After accessing this relationship, we may access the intermediate table using the pivot
attribute on the models:
$user = App\User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Notice that each Role
model we retrieve is automatically assigned a pivot
attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.
By default, only the model keys will be present on the pivot
object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
If you want your pivot table to have automatically maintained created_at
and updated_at
timestamps, use the withTimestamps
method on the relationship definition:
return $this->belongsToMany('App\Role')->withTimestamps();
Customizing The pivot
Attribute Name
As noted earlier, attributes from the intermediate table may be accessed on models using the pivot
attribute. However, you are free to customize the name of this attribute to better reflect its purpose within your application.
For example, if your application contains users that may subscribe to podcasts, you probably have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table accessor to subscription
instead of pivot
. This can be done using the as
method when defining the relationship:
return $this->belongsToMany('App\Podcast')
->as('subscription')
->withTimestamps();
Once this is done, you may access the intermediate table data using the customized name:
$users = User::with('podcasts')->get();
foreach ($users->flatMap->podcasts as $podcast) {
echo $podcast->subscription->created_at;
}
Filtering Relationships Via Intermediate Table Columns
You can also filter the results returned by belongsToMany
using the wherePivot
and wherePivotIn
methods when defining the relationship:
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);
Defining Custom Intermediate Table Models
If you would like to define a custom model to represent the intermediate table of your relationship, you may call the using
method when defining the relationship. Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot
class while custom polymorphic many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\MorphPivot
class. For example, we may define a Role
which uses a custom RoleUser
pivot model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User')->using('App\RoleUser');
}
}
When defining the RoleUser
model, we will extend the Pivot
class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUser extends Pivot
{
//
}
You can combine using
and withPivot
in order to retrieve columns from the intermediate table. For example, you may retrieve the created_by
and updated_by
columns from the RoleUser
pivot table by passing the column names to the withPivot
method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User')
->using('App\RoleUser')
->withPivot([
'created_by',
'updated_by'
]);
}
}
Custom Pivot Models And Incrementing IDs
If you have defined a many-to-many relationship that uses a custom pivot model, and that pivot model has an auto-incrementing primary key, you should ensure your custom pivot model class defines an incrementing
property that is set to true
.
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = true;
Has One Through
The "has-one-through" relationship links models through a single intermediate relation. For example, if each supplier has one user, and each user is associated with one user history record, then the supplier model may access the user's history through the user. Let's look at the database tables necessary to define this relationship:
users
id - integer
supplier_id - integer
suppliers
id - integer
history
id - integer
user_id - integer
Though the history
table does not contain a supplier_id
column, the hasOneThrough
relation can provide access to the user's history to the supplier model. Now that we have examined the table structure for the relationship, let's define it on the Supplier
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Supplier extends Model
{
/**
* Get the user's history.
*/
public function userHistory()
{
return $this->hasOneThrough('App\History', 'App\User');
}
}
The first argument passed to the hasOneThrough
method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Typical Eloquent foreign key conventions will be used when performing the relationship's queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasOneThrough
method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:
class Supplier extends Model
{
/**
* Get the user's history.
*/
public function userHistory()
{
return $this->hasOneThrough(
'App\History',
'App\User',
'supplier_id', // Foreign key on users table...
'user_id', // Foreign key on history table...
'id', // Local key on suppliers table...
'id' // Local key on users table...
);
}
}
Has Many Through
The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country
model might have many Post
models through an intermediate User
model. In this example, you could easily gather all blog posts for a given country. Let's look at the tables required to define this relationship:
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
Though posts
does not contain a country_id
column, the hasManyThrough
relation provides access to a country's posts via $country->posts
. To perform this query, Eloquent inspects the country_id
on the intermediate users
table. After finding the matching user IDs, they are used to query the posts
table.
Now that we have examined the table structure for the relationship, let's define it on the Country
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* Get all of the posts for the country.
*/
public function posts()
{
return $this->hasManyThrough('App\Post', 'App\User');
}
}
The first argument passed to the hasManyThrough
method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
Typical Eloquent foreign key conventions will be used when performing the relationship's queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasManyThrough
method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
Polymorphic Relationships
A polymorphic relationship allows the target model to belong to more than one type of model using a single association.
One To One (Polymorphic)
Table Structure
A one-to-one polymorphic relation is similar to a simple one-to-one relation; however, the target model can belong to more than one type of model on a single association. For example, a blog Post
and a User
may share a polymorphic relation to an Image
model. Using a one-to-one polymorphic relation allows you to have a single list of unique images that are used for both blog posts and user accounts. First, let's examine the table structure:
posts
id - integer
name - string
users
id - integer
name - string
images
id - integer
url - string
imageable_id - integer
imageable_type - string
Take note of the imageable_id
and imageable_type
columns on the images
table. The imageable_id
column will contain the ID value of the post or user, while the imageable_type
column will contain the class name of the parent model. The imageable_type
column is used by Eloquent to determine which "type" of parent model to return when accessing the imageable
relation.
Model Structure
Next, let's examine the model definitions needed to build this relationship:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
/**
* Get all of the owning imageable models.
*/
public function imageable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get the post's image.
*/
public function image()
{
return $this->morphOne('App\Image', 'imageable');
}
}
class User extends Model
{
/**
* Get the user's image.
*/
public function image()
{
return $this->morphOne('App\Image', 'imageable');
}
}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to retrieve the image for a post, we can use the image
dynamic property:
$post = App\Post::find(1);
$image = $post->image;
You may also retrieve the parent from the polymorphic model by accessing the name of the method that performs the call to morphTo
. In our case, that is the imageable
method on the Image
model. So, we will access that method as a dynamic property:
$image = App\Image::find(1);
$imageable = $image->imageable;
The imageable
relation on the Image
model will return either a Post
or User
instance, depending on which type of model owns the image.
One To Many (Polymorphic)
Table Structure
A one-to-many polymorphic relation is similar to a simple one-to-many relation; however, the target model can belong to more than one type of model on a single association. For example, imagine users of your application can "comment" on both posts and videos. Using polymorphic relationships, you may use a single comments
table for both of these scenarios. First, let's examine the table structure required to build this relationship:
posts
id - integer
title - string
body - text
videos
id - integer
title - string
url - string
comments
id - integer
body - text
commentable_id - integer
commentable_type - string
Model Structure
Next, let's examine the model definitions needed to build this relationship:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the comments for a post, we can use the comments
dynamic property:
$post = App\Post::find(1);
foreach ($post->comments as $comment) {
//
}
You may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphTo
. In our case, that is the commentable
method on the Comment
model. So, we will access that method as a dynamic property:
$comment = App\Comment::find(1);
$commentable = $comment->commentable;
The commentable
relation on the Comment
model will return either a Post
or Video
instance, depending on which type of model owns the comment.
Many To Many (Polymorphic)
Table Structure
Many-to-many polymorphic relations are slightly more complicated than morphOne
and morphMany
relationships. For example, a blog Post
and Video
model could share a polymorphic relation to a Tag
model. Using a many-to-many polymorphic relation allows you to have a single list of unique tags that are shared across blog posts and videos. First, let's examine the table structure:
posts
id - integer
name - string
videos
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
Model Structure
Next, we're ready to define the relationships on the model. The Post
and Video
models will both have a tags
method that calls the morphToMany
method on the base Eloquent class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
Defining The Inverse Of The Relationship
Next, on the Tag
model, you should define a method for each of its related models. So, for this example, we will define a posts
method and a videos
method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
/**
* Get all of the posts that are assigned this tag.
*/
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
/**
* Get all of the videos that are assigned this tag.
*/
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
}
Retrieving The Relationship
Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you can use the tags
dynamic property:
$post = App\Post::find(1);
foreach ($post->tags as $tag) {
//
}
You may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphedByMany
. In our case, that is the posts
or videos
methods on the Tag
model. So, you will access those methods as dynamic properties:
$tag = App\Tag::find(1);
foreach ($tag->videos as $video) {
//
}
Custom Polymorphic Types
By default, Laravel will use the fully qualified class name to store the type of the related model. For instance, given the one-to-many example above where a Comment
may belong to a Post
or a Video
, the default commentable_type
would be either App\Post
or App\Video
, respectively. However, you may wish to decouple your database from your application's internal structure. In that case, you may define a "morph map" to instruct Eloquent to use a custom name for each model instead of the class name:
use Illuminate\Database\Eloquent\Relations\Relation;
Relation::morphMap([
'posts' => 'App\Post',
'videos' => 'App\Video',
]);
You may register the morphMap
in the boot
function of your AppServiceProvider
or create a separate service provider if you wish.
Querying Relations
Since all types of Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing the relationship queries. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.
For example, imagine a blog system in which a User
model has many associated Post
models:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get all of the posts for the user.
*/
public function posts()
{
return $this->hasMany('App\Post');
}
}
You may query the posts
relationship and add additional constraints to the relationship like so:
$user = App\User::find(1);
$user->posts()->where('active', 1)->get();
You are able to use any of the query builder methods on the relationship, so be sure to explore the query builder documentation to learn about all of the methods that are available to you.
Relationship Methods Vs. Dynamic Properties
If you do not need to add additional constraints to an Eloquent relationship query, you may access the relationship as if it were a property. For example, continuing to use our User
and Post
example models, we may access all of a user's posts like so:
$user = App\User::find(1);
foreach ($user->posts as $post) {
//
}
Dynamic properties are "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model's relations.
Querying Relationship Existence
When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, imagine you want to retrieve all blog posts that have at least one comment. To do so, you may pass the name of the relationship to the has
and orHas
methods:
// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();
You may also specify an operator and count to further customize the query:
// Retrieve all posts that have three or more comments...
$posts = App\Post::has('comments', '>=', 3)->get();
Nested has
statements may also be constructed using "dot" notation. For example, you may retrieve all posts that have at least one comment and vote:
// Retrieve posts that have at least one comment with votes...
$posts = App\Post::has('comments.votes')->get();
If you need even more power, you may use the whereHas
and orWhereHas
methods to put "where" conditions on your has
queries. These methods allow you to add customized constraints to a relationship constraint, such as checking the content of a comment:
use Illuminate\Database\Eloquent\Builder;
// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
// Retrieve posts with at least ten comments containing words like foo%...
$posts = App\Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
}, '>=', 10)->get();
Querying Relationship Absence
When accessing the records for a model, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments. To do so, you may pass the name of the relationship to the doesntHave
and orDoesntHave
methods:
$posts = App\Post::doesntHave('comments')->get();
If you need even more power, you may use the whereDoesntHave
and orWhereDoesntHave
methods to put "where" conditions on your doesntHave
queries. These methods allows you to add customized constraints to a relationship constraint, such as checking the content of a comment:
use Illuminate\Database\Eloquent\Builder;
$posts = App\Post::whereDoesntHave('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
})->get();
You may use "dot" notation to execute a query against a nested relationship. For example, the following query will retrieve all posts with comments from authors that are not banned:
use Illuminate\Database\Eloquent\Builder;
$posts = App\Post::whereDoesntHave('comments.author', function (Builder $query) {
$query->where('banned', 1);
})->get();
Counting Related Models
If you want to count the number of results from a relationship without actually loading them you may use the withCount
method, which will place a {relation}_count
column on your resulting models. For example:
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
You may add the "counts" for multiple relations as well as add constraints to the queries:
$posts = App\Post::withCount(['votes', 'comments' => function ($query) {
$query->where('content', 'like', 'foo%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
You may also alias the relationship count result, allowing multiple counts on the same relationship:
$posts = App\Post::withCount([
'comments',
'comments as pending_comments_count' => function ($query) {
$query->where('approved', false);
}
])->get();
echo $posts[0]->comments_count;
echo $posts[0]->pending_comments_count;
If you're combining withCount
with a select
statement, ensure that you call withCount
after the select
method:
$posts = App\Post::select(['title', 'body'])->withCount('comments');
echo $posts[0]->title;
echo $posts[0]->body;
echo $posts[0]->comments_count;
Eager Loading
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem. To illustrate the N + 1 query problem, consider a Book
model that is related to Author
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
/**
* Get the author that wrote the book.
*/
public function author()
{
return $this->belongsTo('App\Author');
}
}
Now, let's retrieve all books and their authors:
$books = App\Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
This loop will execute 1 query to retrieve all of the books on the table, then another query for each book to retrieve the author. So, if we have 25 books, this loop would run 26 queries: 1 for the original book, and 25 additional queries to retrieve the author of each book.
Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with
method:
$books = App\Book::with('author')->get();
foreach ($books as $book) {
echo $book->author->name;
}
For this operation, only two queries will be executed:
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
Eager Loading Multiple Relationships
Sometimes you may need to eager load several different relationships in a single operation. To do so, just pass additional arguments to the with
method:
$books = App\Book::with(['author', 'publisher'])->get();
Nested Eager Loading
To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:
$books = App\Book::with('author.contacts')->get();
Eager Loading Specific Columns
You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:
$books = App\Book::with('author:id,name')->get();
{note} When using this feature, you should always include the
id
column and any relevant foreign key columns in the list of columns you wish to retrieve.
Constraining Eager Loads
Sometimes you may wish to eager load a relationship, but also specify additional query conditions for the eager loading query. Here's an example:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
In this example, Eloquent will only eager load posts where the post's title
column contains the word first
. You may call other query builder methods to further customize the eager loading operation:
$users = App\User::with(['posts' => function ($query) {
$query->orderBy('created_at', 'desc');
}])->get();
{note} The
limit
andtake
query builder methods may not be used when constraining eager loads.
Lazy Eager Loading
Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:
$books = App\Book::all();
if ($someCondition) {
$books->load('author', 'publisher');
}
If you need to set additional query constraints on the eager loading query, you may pass an array keyed by the relationships you wish to load. The array values should be Closure
instances which receive the query instance:
$books->load(['author' => function ($query) {
$query->orderBy('published_date', 'asc');
}]);
To load a relationship only when it has not already been loaded, use the loadMissing
method:
public function format(Book $book)
{
$book->loadMissing('author');
return [
'name' => $book->name,
'author' => $book->author->name
];
}
Nested Lazy Eager Loading & morphTo
If you would like to eager load a morphTo
relationship, as well as nested relationships on the various entities that may be returned by that relationship, you may use the loadMorph
method.
This method accepts the name of the morphTo
relationship as its first argument, and an array of model / relationship pairs as its second argument. To help illustrate this method, let's consider the following model:
<?php
use Illuminate\Database\Eloquent\Model;
class ActivityFeed extends Model
{
/**
* Get the parent of the activity feed record.
*/
public function parentable()
{
return $this->morphTo();
}
}
In this example, let's assume Event
, Photo
, and Post
models may create ActivityFeed
models. Additionally, let's assume that Event
models belong to a Calendar
model, Photo
models are associated with Tag
models, and Post
models belong to an Author
model.
Using these model definitions and relationships, we may retrieve ActivityFeed
model instances and eager load all parentable
models and their respective nested relationships:
$activities = ActivityFeed::with('parentable')
->get()
->loadMorph('parentable', [
Event::class => ['calendar'],
Photo::class => ['tags'],
Post::class => ['author'],
]);
Inserting & Updating Related Models
The Save Method
Eloquent provides convenient methods for adding new models to relationships. For example, perhaps you need to insert a new Comment
for a Post
model. Instead of manually setting the post_id
attribute on the Comment
, you may insert the Comment
directly from the relationship's save
method:
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
Notice that we did not access the comments
relationship as a dynamic property. Instead, we called the comments
method to obtain an instance of the relationship. The save
method will automatically add the appropriate post_id
value to the new Comment
model.
If you need to save multiple related models, you may use the saveMany
method:
$post = App\Post::find(1);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);
Recursively Saving Models & Relationships
If you would like to save
your model and all of its associated relationships, you may use the push
method:
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
The Create Method
In addition to the save
and saveMany
methods, you may also use the create
method, which accepts an array of attributes, creates a model, and inserts it into the database. Again, the difference between save
and create
is that save
accepts a full Eloquent model instance while create
accepts a plain PHP array
:
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
{tip} Before using the
create
method, be sure to review the documentation on attribute mass assignment.
You may use the createMany
method to create multiple related models:
$post = App\Post::find(1);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
You may also use the findOrNew
, firstOrNew
, firstOrCreate
and updateOrCreate
methods to create and update models on relationships.
Belongs To Relationships
When updating a belongsTo
relationship, you may use the associate
method. This method will set the foreign key on the child model:
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
When removing a belongsTo
relationship, you may use the dissociate
method. This method will set the relationship's foreign key to null
:
$user->account()->dissociate();
$user->save();
Default Models
The belongsTo
relationship allows you to define a default model that will be returned if the given relationship is null
. This pattern is often referred to as the Null Object pattern and can help remove conditional checks in your code. In the following example, the user
relation will return an empty App\User
model if no user
is attached to the post:
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault();
}
To populate the default model with attributes, you may pass an array or Closure to the withDefault
method:
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault([
'name' => 'Guest Author',
]);
}
/**
* Get the author of the post.
*/
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user) {
$user->name = 'Guest Author';
});
}
Many To Many Relationships
Attaching / Detaching
Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach
method:
$user = App\User::find(1);
$user->roles()->attach($roleId);
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
Sometimes it may be necessary to remove a role from a user. To remove a many-to-many relationship record, use the detach
method. The detach
method will delete the appropriate record out of the intermediate table; however, both models will remain in the database:
// Detach a single role from the user...
$user->roles()->detach($roleId);
// Detach all roles from the user...
$user->roles()->detach();
For convenience, attach
and detach
also accept arrays of IDs as input:
$user = App\User::find(1);
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([
1 => ['expires' => $expires],
2 => ['expires' => $expires]
]);
Syncing Associations
You may also use the sync
method to construct many-to-many associations. The sync
method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$user->roles()->sync([1, 2, 3]);
You may also pass additional intermediate table values with the IDs:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
If you do not want to detach existing IDs, you may use the syncWithoutDetaching
method:
$user->roles()->syncWithoutDetaching([1, 2, 3]);
Toggling Associations
The many-to-many relationship also provides a toggle
method which "toggles" the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached:
$user->roles()->toggle([1, 2, 3]);
Saving Additional Data On A Pivot Table
When working with a many-to-many relationship, the save
method accepts an array of additional intermediate table attributes as its second argument:
App\User::find(1)->roles()->save($role, ['expires' => $expires]);
Updating A Record On A Pivot Table
If you need to update an existing row in your pivot table, you may use updateExistingPivot
method. This method accepts the pivot record foreign key and an array of attributes to update:
$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);
Touching Parent Timestamps
When a model belongsTo
or belongsToMany
another model, such as a Comment
which belongs to a Post
, it is sometimes helpful to update the parent's timestamp when the child model is updated. For example, when a Comment
model is updated, you may want to automatically "touch" the updated_at
timestamp of the owning Post
. Eloquent makes it easy. Just add a touches
property containing the names of the relationships to the child model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* All of the relationships to be touched.
*
* @var array
*/
protected $touches = ['post'];
/**
* Get the post that the comment belongs to.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Now, when you update a Comment
, the owning Post
will have its updated_at
column updated as well, making it more convenient to know when to invalidate a cache of the Post
model:
$comment = App\Comment::find(1);
$comment->text = 'Edit to this comment!';
$comment->save();


ppdiag
is an R
package which provides a collection of tools which can be used to assess the fit of temporal point processes to data.
These currently include:
You can install the released version of ppdiag from CRAN with:
install.packages("ppdiag")
The current development version of this package is available from GitHub with:
# install.packages("remotes")
remotes::install_github("OwenWard/ppdiag")
To illustrate some of the basic functionality of this package, we can simulate data from a specified Hawkes process and examine our diagnostic results when we fit a homogeneous Poisson process to this data.
library(ppdiag)
hp_obj <- pp_hp(lambda0 = 0.2, alpha = 0.35, beta = 0.8)
sim_hp <- pp_simulate(hp_obj, end = 200)
sim_hp
#> [1] 1.251803 2.585288 15.660522 16.424361 19.852963 20.115283
#> [7] 36.749777 36.813473 54.757570 56.583400 59.564868 60.272463
#> [13] 60.884895 84.771774 88.260163 88.423628 89.601849 90.061292
#> [19] 90.370334 90.621778 90.694123 92.143117 93.395489 93.687936
#> [25] 94.588896 113.160732 121.785596 122.646369 122.770419 123.035607
#> [31] 125.550267 125.561861 130.788192 133.921184 137.518573 139.761132
#> [37] 145.099685 155.317533 161.611297 176.427144 178.593037 178.923897
#> [43] 179.170059 184.217712 184.422784 190.509601
We can readily evaluate the fit of a homogeneous Poisson process to this data.
est_hpp <- fithpp(sim_hp)
est_hpp
#> Homogeneous Poisson Process
#> lambda
#> events 1.251803 2.585288 15.66052 16.42436 19.85296 20.11528 36.74978 36.81347 54.75757 56.5834 59.56487 60.27246 60.8849 84.77177 88.26016 88.42363 89.60185 90.06129 90.37033 90.62178 90.69412 92.14312 93.39549 93.68794 94.5889 113.1607 121.7856 122.6464 122.7704 123.0356 125.5503 125.5619 130.7882 133.9212 137.5186 139.7611 145.0997 155.3175 161.6113 176.4271 178.593 178.9239 179.1701 184.2177 184.4228 190.5096
pp_diag(est_hpp, events = sim_hp)
#>
#> Raw residual: 0
#> Pearson residual: -1.421085e-14
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: r
#> D = 0.22652, p-value = 0.01481
#> alternative hypothesis: two-sided
#> Raw residual: -0.00519921
#> Pearson residual: 0.06798623
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: r
#> D = 0.10346, p-value = 0.67
#> alternative hypothesis: two-sided
This is particularly useful for more complex point processes, such as the Markov Modulated Hawkes Process (MMHP). We can simulate events from this model and examine the fit of simpler point processes to this data.
Q <- matrix(c(-0.2, 0.2, 0.1, -0.1), ncol = 2, byrow = TRUE)
mmhp_obj <- pp_mmhp(Q, delta = c(1 / 3, 2 / 3),
lambda0 = 0.2,
lambda1 = .75,
alpha = 0.4,
beta = 0.8)
mmhp_obj
#> Markov Modulated Hawkes Process
#> lambda0 0.2
#> lambda1 0.75
#> alpha 0.4
#> beta 0.8
#> Q -0.2 0.1 0.2 -0.1
#> delta 0.3333333 0.6666667
mmhp_events <- pp_simulate(mmhp_obj, n = 50)
We can easily fit a homogeneous Poisson process and visualise the goodness of fit.
#>
#> Raw residual: -1
#> Pearson residual: -1.684459
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: r
#> D = 0.27786, p-value = 0.0006626
#> alternative hypothesis: two-sided
Similarly for a Hawkes process.
#> Raw residual: -0.6181052
#> Pearson residual: -2.221529
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: r
#> D = 0.078371, p-value = 0.8949
#> alternative hypothesis: two-sided
We can then compare to the true point process model.
pp_diag(mmhp_obj, mmhp_events$events)
#> Raw residual: 5.381804
#> Pearson residual: 2.85359
#>
#> One-sample Kolmogorov-Smirnov test
#>
#> data: r
#> D = 0.12924, p-value = 0.344
#> alternative hypothesis: two-sided
Please file any issues here. Similarly, we would be delighted if anyone would like to contribute to this package (such as adding other point processes, kernel functions). Feel free to take a look here and reach out with any questions.


Accessing BFILEs Through ODP.NET Sample
Table of Contents
The purpose of this sample application is to demonstrate:
1) How to insert BFILE data through ODP.NET ?
2) How to view BFILE data through ODP.NET ?
Large Objects (LOBs) are used to store unstructured
data such as text, graphic images, video clips etc. BFILE is a type of
external LOB that is used to store large binary data objects stored in
operating system files outside database tablespaces. BFILE datatype allows
read-only byte stream access to large files on the file system of the
database server.
ODP.NET provides support to BFILE though OracleBFile
object type. Unlike Oracle BLOBs and CLOBs, Oracle BFILEs are not updatable
but BFILE locators are updatable.
This Visual Basic .NET sample demonstrates accessing
BFILEs through ODP.NET. When this sample is run a window is displayed
through which the user can establish database connection by entering parameters
as per his/her database. After connecting to database successfully, the
user needs to enter the full, qualified path of the location on the database
server where the image file which the user wants to insert resides. On
clicking the "Save Image" button the required database objects
are created and then the image is inserted. To view the inserted image
the user can click "Display Image" button, the image is retrieved
using GetOracleBFile method of OracleDataReader
into an OracleBFile object. Messages are
displayed at each step in the status bar.
When this sample application is run, a windows application
is displayed. Enter the username, password and connect string as per your
database environment. Click "Connect" button. If the connection
is successfully established then the connection status is displayed as
"connected" as shown in Figure 1.1 .
Figure 1.1: Screenshot displaying window after connection
was successfully established
To insert a BFILE, enter the directory path on the
database server where you have copied "poster.gif "
file, in the textbox provided and click "Save Image" button.
See the messages in the status bar. Then click on "Display Image"
button. The image is displayed in the picture box as shown in figure
1.2 .
Figure 1.2 : Screenshot displaying
saved image from database
A "Disconnect" button is provided for user
to disconnect the database connection. One can use "Connect"
button again to connect as a different database user. To close this application
the user can click the "Exit" button.
-
Visual Basic.NET installed with Visual Studio
2005/2008/2010/2012.
-
Oracle11g
Database Enterprise Edition or higher running SQL*Net TCP/IP listener
(can be downloaded
here)
-
Oracle Data Provider for .NET (ODP.NET) (can
be downloaded
here)
.
Unzip AccessBFile.zip
using Winzip or command utility to a convenient directory referred to
as <Extract_Dir> .
Extraction of the zip file results in the creation of "AccessBFile"
directory. Refer Description of Sample Files
section for more details.
An Oracle database object "Directory"
needs to be created to run this sample. For any database user
to create this object, a special privilege "CREATE ANY DIRECTORY"
needs to be granted by DBA (for eg. SYSTEM database user).
To grant this privilege to any normal database user
say scott (in this example), at SQL prompt type the following
command:
|
Syntax:
SQL> CONNECT <DBAUser>/<Password>@<ConnectString>;
SQL> GRANT CREATE ANY DIRECTORY TO <DatabaseUser>;
eg.:
SQL> CONNECT system/manager@oracle;
SQL> GRANT CREATE ANY DIRECTORY TO scott;
|
|
Now "Scott"
user can run this sample.
1. Open AccessBFile.sln using Visual Studio
.NET from <Extract_Dir>\AccessBFile folder.
2. Ensure that the following .NET Component References
have been added to AccessBFile project:
System,
System.Data,
System.Drawing,
System.Windows.Forms,
Oracle.ManagedDataAccess.
To add the above .NET Components
a)Go to Menu ->View-> Solution Explorer.
b)Right click on AccessBFile project, choose 'Add Reference'.
c)Choose the above .NET Components from the list displayed.
d)Click 'Select', then OK.
e) The chosen .NET component gets added to the project.
3. Build and run the sample.
1. A sample image, poster.gif (BFILE)
is provided with this sample. Copy "poster.gif"
image file from <Extract_Dir>\AccessBfile\doc folder to
a directory located on the database server. Note down this directory as
it will be later required in the sample.
2. When this sample is run a window with facilities
like establishing database connection and inserting/displaying BFILE is
displayed.
3. Ensure that you have completed the Database
Setup.
4. Enter appropriate Username, Password, Data Source
in the text boxes and click "Connect" button. If the connection
is successfully established the connection status "connected"
is displayed in green. NOTE: Ensure that the database
user you are using has the "CREATE ANY DIRECTORY"
privilege.
5. To insert image "poster.gif"
to the database. Enter the full, qualified path of the image where it
is located on the database server. This is the directory path on the database
server you used in Step 1.
6. Click "Save Image" button to insert image
to the database. The following steps are taken to insert the image:
- A database table Test_Bfile with
a column named "photo" of type BFILE is created.
- A Directory "BFILEDIR"
is created pointing the path entered by the user in Step. 5.
- A single row, containing a BFILE pointer is inserted
to the Test_Bfile table.
7. To display the inserted image from the Test_Bfile
database table. Click on "Display Image" button. The following
steps are taken to display the image:
- BFILE locator is selected from Test_Bfile
Table and stored in OracleBFile .
- A memory stream is opened on the selected OracleBFile
(BFILE locator).
- Image file is fetched and shown in a Picture
Box.
1. In case the image is not displayed correctly, then
check the path entered in the text box. The image "poster.gif"
must be stored on the database server. In case your database server is
installed on Windows operating system then enter the path as for e.g.
e:\myimages . If your database server is on
a Unix/Linux operating system then enter the path as for e.g.
/home/myimages . Where myimages could
be any directory as per your machine settings.
2. In case you wish to use some other image other than
"poster.gif" , then you will have
to change the image name in the code. The image name "poster.gif"
is hardcoded in the code in Bfile.vb file.
This sample provides facility to only view Binary files like images etc.
Following is the directory structure of the AccessBfile.zip
:
| Directory |
Files |
Description
|
AccessBFile\doc\ |
Readme.html |
This file |
otn.css |
Cascading Stylesheet applied to Readme.html |
poster.gif |
A sample image file used in this sample. |
AccessBFile\doc\images\ |
*.gif |
Screenshots used in Readme.html
file |
AccessBFile\src\ |
AcessBFile.sln |
Visual Studio Solution |
AcessBFile.suo |
Solution User option (this
file gets automatically generated when a Visual Studio Solution is
created). |
Bfile.vb |
The source file containing
the UI and all the methods that are used for accessing a BFILE. |
Bfile.resx |
.NET XML resource template |
AccessBfile.vbproj |
VB project file |
AccessBfile.vbproj.user |
Visual Studio Project
User Options (this file gets automatically generated when a Visual
Studio Project is created) |
|


Apache 1.1 and earlier let modules handle POST and PUT requests by
themselves. The module would, on its own, determine whether the
request had an entity, how many bytes it was, and then called a
function (read_client_block
) to get the data.
However, HTTP/1.1 requires several things of POST and PUT request handlers that did not fit into this module, and all existing modules have to be rewritten. The API calls for handling this have been further abstracted, so that future HTTP protocol changes can be accomplished while remaining backwards-compatible.
int ap_setup_client_block (request_rec *, int read_policy); int ap_should_client_block (request_rec *); long ap_get_client_block (request_rec *, char *buffer, int buffer_size);
ap_setup_client_block()
near the beginning of the request
handler. This will set up all the necessary properties, and
will return either OK, or an error code. If the latter,
the module should return that error code. The second parameter
selects the policy to apply if the request message indicates a
body, and how a chunked
transfer-coding should be interpreted. Choose one of
REQUEST_NO_BODY Send 413 error if message has any body REQUEST_CHUNKED_ERROR Send 411 error if body without Content-Length REQUEST_CHUNKED_DECHUNK If chunked, remove the chunks for me. REQUEST_CHUNKED_PASS Pass the chunks to me without removal.In order to use the last two options, the caller MUST provide a buffer large enough to hold a chunk-size line, including any extensions.
ap_should_client_block()
.
This will tell the module whether or not to read input. If it is 0,
the module should assume that the input is of a non-entity type
(e.g., a GET request). A nonzero response indicates that the module
should proceed (to step 3).
This step also sends a 100 Continue response
to HTTP/1.1 clients, so should not be called until the module
is *definitely* ready to read content. (otherwise, the
point of the
100 response is defeated). Never call this function more than once.
ap_get_client_block
in a loop. Pass it a
buffer and its
size. It will put data into the buffer (not necessarily the full
buffer, in the case of chunked inputs), and return the length of
the input block. When it is done reading, it will
return 0 if EOF, or -1 if there was an error.
As an example, please look at the code in
mod_cgi.c
. This is properly written to the new API
guidelines.


Superconductor
Data points:
.
GPU vertices:
ERROR: HTML canvas support not found.
Height
Radius
Rotation


A construction company hired by Barry Slwasky to build his would-be retirement home has sued their former emplyer for breach of contract, alleging that Slawsky failed to pay their final invoice of $32,914 after terminating their contract in December 2014. Read more in the Times Colonist and The Globe and Mail.
Click here for more information from CBC.
Click The Globe and Mail for more information.
Available here.


|
| linux | android | ||||||||||||||||||
|
|
||||||||||||||||||
| ₩0e07c2d7073b | ₩erikchen | @chromium.org
|
|
||||||||||||||||
|
₩Make Telemetry tests check the configuration of the OSX Keychain. Historically, the OSX Keychain has been misconfigured on some perf bots, which has caused Telemtry tests to stall. This CL adds checks to emit warnings if the Keychain is misconfigured. I added checks for three common misconfigurations: - Is the default Keychain locked. - Is the default Keychain configured to automatically lock after a period of time. - Are the ACLs of a commonly accessed key in the default keychain misconfigured for the perf bots. The first and third checks are performed by short C programs since the information is easily available through the Security framework, but not from the security CLI. BUG=443340 Review URL: https://codereview.chromium.org/809473004 Cr-Commit-Position: refs/heads/master@{#314921} |
|||||||||||||||||||
| 89876b5e53a0 | blink-deps-roller | @chromium.org
|
|
||||||||||||||||
|
Roll src/third_party/WebKit d953d07:dc9973e (svn 189584:189586) Summary of changes available at: https://chromium.googlesource.com/chromium/blink/+log/d953d07..dc9973e TBR=dcheng<EMAIL_ADDRESS>Review URL: https://codereview.chromium.org/886643004 Cr-Commit-Position: refs/heads/master@{#314920} |
|||||||||||||||||||
| 60d02cca7a5e | spang | @chromium.org
|
|
||||||||||||||||
|
content: Make ui/events dependency unconditional It is not used only when toolkit_views is enabled. This fixes some unresolved reference errors that will break the linux_ecs_ozone trybot once we enable -Wl,-z,defs. This dependency is already unconditional in the GN build. BUG=445627 TEST=linux_ecs_ozone tryjob Review URL: https://codereview.chromium.org/874163004 Cr-Commit-Position: refs/heads/master@{#314919} |
|||||||||||||||||||
| e7fba1549e8b | enne | @chromium.org
|
|
||||||||||||||||
|
cc: Don't refer to layer render target when using property trees This is a vestige of old UpdateDrawProperties and instead should go directly to the target_id on the transform node. Also, the root node was setting the target_id incorrectly because its transform_node_index was not set before being referenced. This is a fix contributing towards getting property trees to entirely replace UpdateDrawProperties on the main thread. Review URL: https://codereview.chromium.org/897373002 Cr-Commit-Position: refs/heads/master@{#314918} |
|||||||||||||||||||
| 10ce97b93303 | sergeyu | @chromium.org
|
|
||||||||||||||||
|
Rename VideoScheduler->VideoFramePump. BUG=455818 Review URL: https://codereview.chromium.org/893353002 Cr-Commit-Position: refs/heads/master@{#314917} |
|||||||||||||||||||
| b73c88950e94 | sebmarchand | @chromium.org
|
|
||||||||||||||||
|
Roll Syzygy DEPS to <IP_ADDRESS> Version <IP_ADDRESS> [cec4a29a57] Add support for rate targeted heaps [562794745b] Add support for more AVX2 instructions. BUG=454269 Review URL: https://codereview.chromium.org/880573006 Cr-Commit-Position: refs/heads/master@{#314916} |
|||||||||||||||||||
| 4686a2a41477 | dgn | @chromium.org
|
|
||||||||||||||||
|
Style fixes. Review URL: https://codereview.chromium.org/905573003 Cr-Commit-Position: refs/heads/master@{#314915} |
|||||||||||||||||||
| eb640d0e9f13 | aurimas | @chromium.org
|
|
||||||||||||||||
|
Fix random lint warnings in chrome/android/shell BUG=266140 Review URL: https://codereview.chromium.org/900103002 Cr-Commit-Position: refs/heads/master@{#314914} |
|||||||||||||||||||
| 9ce5c6661b03 | vmpstr | @chromium.org
|
|
||||||||||||||||
|
cc: Split ReleaseResources into Release and Recreate. This patch splits the work we do in ReleaseResources into two parts: ReleaseResources and RecreateResources. If any part of invalidating or creating new resources requires access to new structures (such as a new tile manager and new output surface), this is the way to get this information. That is, ReleaseResources happens while old objects are alive and accessible. RecreateResources happens when the new objects are alive and accessible. R=danakj, enne Review URL: https://codereview.chromium.org/899313003 Cr-Commit-Position: refs/heads/master@{#314913} |
|||||||||||||||||||
| 65d6cc0bbd41 | skia-deps-roller | @chromium.org
|
|
||||||||||||||||
|
Roll src/third_party/skia 5e1378d:f71b4c1 Summary of changes available at: https://chromium.googlesource.com/skia/+log/5e1378d..f71b4c1 CQ_EXTRA_TRYBOTS=tryserver.blink:linux_blink_rel,linux_blink_dbg<EMAIL_ADDRESS>Review URL: https://codereview.chromium.org/902493008 Cr-Commit-Position: refs/heads/master@{#314912} |
|||||||||||||||||||
| 7ea968e9d783 | hcarmona | @chromium.org
|
|
||||||||||||||||
|
Don't call preventDefault in the FocusGrid's click event Calling preventDefault in the click event prevents buttons from handling the event. BUG=455617 Review URL: https://codereview.chromium.org/879243007 Cr-Commit-Position: refs/heads/master@{#314911} |
|||||||||||||||||||
| c85184da42d0 | dalecurtis | @chromium.org
|
|
||||||||||||||||
|
Purge AudioOutputDispatcher after close delay if no proxies exist. This prevents transient audio creation errors from cumulatively breaking audio output by blackholing everything to a fake audio stream after fallback attempts are exhausted. BUG=453560 TEST=new unittest, manual testing. Review URL: https://codereview.chromium.org/899923003 Cr-Commit-Position: refs/heads/master@{#314910} |
|||||||||||||||||||
| 8468daefc9eb | thestig | @chromium.org
|
|
||||||||||||||||
|
Cleanup: Remove an unused parameter in StartupBrowserCreator. Review URL: https://codereview.chromium.org/896053002 Cr-Commit-Position: refs/heads/master@{#314909} |
|||||||||||||||||||
| 3e5ab95765d4 | palmer | @chromium.org
|
|
||||||||||||||||
|
Change NULL to nullptr, per style. This is preparatory work for bug 444244. BUG=444244 TBR=sky Review URL: https://codereview.chromium.org/882273003 Cr-Commit-Position: refs/heads/master@{#314908} |
|||||||||||||||||||
| 82b22b21f123 | edwardjung | @chromium.org
|
|
||||||||||||||||
|
Update SSL/malware/net error interstitial design + On small screens the navigation buttons are anchored to the bottom of the screen. + Tweaks to the text colour + Change button styling of safe browsing page BUG=422882 Review URL: https://codereview.chromium.org/885283005 Cr-Commit-Position: refs/heads/master@{#314907} |
|||||||||||||||||||
| e1393cf52aa9 | spang | @chromium.org
|
|
||||||||||||||||
|
libxml2: Add missing dependency on libm The library uses functions from "math.h". This fixes the embedded build with -Wl,-z,defs. BUG=445627 TEST=linux_ecs_ozone tryjob TBR=cpu Review URL: https://codereview.chromium.org/901273002 Cr-Commit-Position: refs/heads/master@{#314906} |
|||||||||||||||||||
| 3fb85eb7a52c | xiyuan | @chromium.org
|
|
||||||||||||||||
|
cros: Pass gaia_auth init params via postMessage. - Pass gaia auth init params via postMessage instead of URL params; - Validate message origins on both ends to ensure gaia auth only takes params from intended hosting pages and hosting pages only send params to gaia_auth; - Add string data storage to GaiaAuthExtensionLoader; - Use the string data storage to pass frameURL for switchToFullTab; - Update CSP in manifests to be more restrictive; - Clean up unused code in util.js; BUG=453994 Review URL: https://codereview.chromium.org/902493003 Cr-Commit-Position: refs/heads/master@{#314905} |
|||||||||||||||||||
| a490eab9b44d | wfh | @chromium.org
|
|
||||||||||||||||
|
Update Flash plugin metadata version to latest versions. BUG=412078 Review URL: https://codereview.chromium.org/896523002 Cr-Commit-Position: refs/heads/master@{#314904} |
|||||||||||||||||||
| d7bcb2ebabea | kelvinp | @chromium.org
|
|
||||||||||||||||
|
Revert of Update sync promo string in chrome://settings (patchset #1 id:100001 of https://codereview.chromium.org/904513002) Reason for revert: 165 Browser test crashing on Linux after the patch Sample failure: http://build.chromium.org/p/chromium.linux/builders/Linux%20Tests%20%28dbg%29%281%29/builds/38668/steps/browser_tests/logs/OptionsWebUIExtendedTest.ShowPageWithHistory Original issue's description: > Update sync promo string in chrome://settings > > BUG=455273 > Committed: https://crrev.com/fdef2865f067f30e99f1f11b33d8811d98bf1e54 > Cr-Commit-Position: refs/heads/master@{#314875} <EMAIL_ADDRESS>NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true Review URL: https://codereview.chromium.org/884743004 Cr-Commit-Position: refs/heads/master@{#314903} |
|||||||||||||||||||
| 82a66024f96d | simonhatch | @chromium.org
|
|
||||||||||||||||
|
Temporarily upload minidump to private cloud storage on windows. Should be reverted once we have one from crashing startup.warm.blank_page perf test. BUG=433966 Review URL: https://codereview.chromium.org/899293003 Cr-Commit-Position: refs/heads/master@{#314902} |
|||||||||||||||||||
| eb69a8a42edf | rch | @chromium.org
|
|
||||||||||||||||
|
Switch to QUIC version 24. Review URL: https://codereview.chromium.org/904723002 Cr-Commit-Position: refs/heads/master@{#314901} |
|||||||||||||||||||
|
|||||||||||||||||||
| 846191e5a129 | rfevang | @chromium.org
|
|
||||||||||||||||
|
Dont set NEEDS_OFFLINE_PROCESSING flag. The server will now always do processing for nodes that don't have stars.id set, so no need to flip this flag any more. BUG= Review URL: https://codereview.chromium.org/888983002 Cr-Commit-Position: refs/heads/master@{#314900} |
|||||||||||||||||||
|
|||||||||||||||||||
| 62ae3a5d1154 | waltercacau | @chromium.org
|
|
||||||||||||||||
|
Recording in UMA when a user interacted with an address form or a credit card form. BUG=454140 Review URL: https://codereview.chromium.org/884843002 Cr-Commit-Position: refs/heads/master@{#314899} |
|||||||||||||||||||
|
|||||||||||||||||||
| ed1472c96613 | sbc | @chromium.org
|
|
||||||||||||||||
|
[NaCl SDK] Use separate gyp output folders for x64 and ia32 Previously we were re-using 'gypbuild' for both 64 and 32. This change increases the complexity of the build but is more correct and robust and allows us to avoid cleaning the gyp output folders between builds. Review URL: https://codereview.chromium.org/898613002 Cr-Commit-Position: refs/heads/master@{#314898} |
|||||||||||||||||||
|
|||||||||||||||||||
| 4a16ff998e64 | zmo | @chromium.org
|
|
||||||||||||||||
|
Add UniformBlock related commands to command buffer. 1) glGetUniformBlocksCHROMIUM This is Chromium GPU command buffer internal command. The purpose is to fetch UniformBlock related information in a linked program from service side in one command instead of multiple ones. 2) glGetUniformBlockIndex 3) glGetActiveUniformBlockName Get value from client side cache (retrieved by GetUniformBlockCHROMIUM); if that fails, send the command to service side. What's missing: glGetActiveUniformBlockiv. It requires some extra tuning, so leave that for a separate CL. BUG=453127,429053 TEST=gpu_unittests<EMAIL_ADDRESS>Review URL: https://codereview.chromium.org/895933004 Cr-Commit-Position: refs/heads/master@{#314897} |
|||||||||||||||||||
|
|||||||||||||||||||


Nulls are wrapped in
tags (i.e. null
) to
make a visual distinction between the string "null" and a null value.
The value is appended to any child markup.
Given the expression "username" returns a null, we expect the following results:
We have stripped out the concordion:echo attributes from the "expected output" for legibility. They may be present.
| Instrumentation | Expected output |
|---|---|
 |
null |
 |
null |
abc |
abcnull |
abc |
abcnull |


--- layout: archive title: Zulip Chat Archive permalink: /stream/113489-new-members/topic/kif.html ---
I am playing with SUMO ontology (http://ontologyportal.org ) trying to understand its semantics and possible translation to dependent types.
one of the language features is the use of row variables (a way to deal with variable arity). So a variable with an @, in the beginning, means a placeholder to one or more arguments. The axiom below, use ListFn
(constructor of lists given any number of arguments, the equivalent of Common Lisp list
function) and inList
to check if an item is an element of the list. How to translate it to Lean?
(=> (exhaustiveDecomposition ?CLASS @ROW) (forall (?OBJ) (=> (instance ?OBJ ?CLASS) (exists (?ITEM) (and (inList ?ITEM (ListFn @ROW)) (instance ?OBJ ?ITEM))))))
The SUMO guy (Adam Pease) spoke at AITP this year: aitp-conference.org/2019/slides/AP.pdf
yep! I am planning to work with him in the formalization of the translation from SUMO to TF0.
What do you mean by "translate it to Lean" exactly?
Good question. I am still thinking about the details, but I am trying something like:
R. Dapoigny and P. Barlatier, “Formalizing Context for Domain Ontologies in Coq,”, May 2014.
All axioms could be encoded as variables, right? For example, the SUMO axiom (simplified):
(<=> (partition ?class ?x ?y) (and (exhaustiveDecomposition ?class ?x ?y) (disjointDecomposition ?class ?x ?y)))
could be encoded as:
constant Class : Type constants partition exhaustiveDecomposition disjointDecomposition : Class → Class → Class → Prop variable AxPartition : ∀ x y z : Class, partition x y z ↔ exhaustiveDecomposition x y z ∧ disjointDecomposition x y z
Does it make sense?
{% endraw %}Last updated: Apr 24 2020 at 19:02 UTC


Last Updated: 2020-05-21
Schrodinger is a Java library for use in FTC robot control systems that helps with building state machines.
A state machine is the combination of a number of states and a number of transitions between them. The subject of a state machine occupies only one state at a time. The library is named after Erwin Schrödinger, who's thought-experiment about a cat in a box involved subatomic particles in multiple states simultaneously. Fortunately, this library is much easier to understand than quantum physics!
State machines are particularly useful in an FTC robot control system because it is usually not desirable for code execution to stop and wait while some condition changes. State machines allow other operations to run during the waiting period and code execution is repeatedly returned to the waiting state. This is particularly useful when state management is required for multiple components moving and waiting simultaneously in the robot.
An example of where state machines are useful is for robots in a tele-operated mode. Take, for instance, a driver-controlled robot that plays tennis. After swinging the racket, the driver would like to continue to move the robot while the racket is drawn back again. A state machine can manage the operation of the racket while the robot continuously moves in response to the driver's commands.
In this codelab, you're going to create op modes for an FTC robot that use the Schrodinger library to implement state machines.
If you do not already have Android Studio installed, follow the instructions for Installing Android Studio
If you are familiar with git, create a new clone of the FTC project repository on your computer. Otherwise, just follow these instructions for Downloading the Android Studio Project Folder
You'll need to let Android Studio (the gradle build system, really) know from where it can download the schrodinger library. Add maven { url 'https://dl.bintray.com/crazycatladies/maven' }
to the repositories section at the bottom of the build.gradle
file in the root folder of your project.
/**
* Top-level build file for ftc_app project.
*
* It is extraordinarily rare that you will ever need to edit this file.
*/
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
}
}
// This is now required because aapt2 has to be downloaded from the
// google() repository beginning with version 3.2 of the Android Gradle Plugin
allprojects {
repositories {
google()
jcenter()
maven { url 'https://dl.bintray.com/crazycatladies/maven' }
}
}
You'll make your project dependent on schrodinger, which will cause Android Studio (gradle, really) to download the library, by adding implementation 'ftc.crazycatladies:schrodinger:0.1.1'
to the end of the dependencies section in TeamCode/build.release.gradle
dependencies {
implementation project(':FtcRobotController')
implementation (name: 'RobotCore-release', ext: 'aar')
implementation (name: 'Hardware-release', ext: 'aar')
implementation (name: 'FtcCommon-release', ext: 'aar')
implementation (name: 'WirelessP2p-release', ext:'aar')
implementation (name: 'tfod-release', ext:'aar')
implementation (name: 'tensorflow-lite-0.0.0-nightly', ext:'aar')
implementation 'ftc.crazycatladies:schrodinger:0.1.1'
}
Schrodinger uses Java 8 features, and you'll probably want to do the same in your own code. You can enable Java 8 by changing the compileOptions
section in build.common.gradle
(in the root folder of the project):
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
After changing and saving these files, you should be able to update gradle by clicking "Sync Now" in the bar which appears at the top of these files:
If everything has gone well, your project will now reference the downloaded schrodinger external library, which you can see in the "Project" view of the Project window:
Create a new Java class in the org.firstinspires.ftc.teamcode
package of the TeamCode
module called SchrodingerTeleOpMode
. If you're not sure how to create an op mode class, refer to Creating and Running an Op Mode (Android Studio)
Start by adding basic code which will display the x & y values for the left stick of gamepad1.
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
@TeleOp(name="SchrodingerTeleOp")
public class SchrodingerTeleOpMode extends LinearOpMode {
@Override
public void runOpMode() throws InterruptedException {
waitForStart();
while (opModeIsActive()) {
telemetry.addData("x", gamepad1.left_stick_x);
telemetry.addData("y", gamepad1.left_stick_y);
telemetry.update();
}
}
}
Test this out with a gamepad connected to your Driver Station phone.
We'll add a simple state machine to this op mode that starts a 5-second countdown when the A button is pressed on the gamepad. In a real FTC robot control system, a state machine would coordinate a more complicated series of operations, but this simple example already enables one to see how state machines provide for management of simultaneous sequences of actions.
First, at the top of runOpMode()
, above waitForStart()
, declare the StateMachine variable sm
and initialize the data logger. The StateMachine is defined with the Integer type, since this is the object type for the context variable that is provided and kept with the state machine.
StateMachine<Integer> sm = null;
final int SECONDS = 5;
DataLogger.createDataLogger(new OpModeTime(this), this.getClass().getSimpleName());
After waitForStart()
, add the initialization of the state machine in this block:
if (opModeIsActive()) {
sm = new StateMachine("A button countdown");
sm.repeat((state, seconds) -> {
if (gamepad1.a) {
state.next();
}
});
sm.repeat(((state, seconds) -> {
double secsInState = state.getTimeInState().seconds();
telemetry.addData("sm-countdown", (int)(seconds - secsInState));
if (secsInState > seconds) {
state.next();
}
}));
sm.setLooping(true);
sm.init(SECONDS);
}
These instructions perform the following steps:
At the top of the while loop, add sm.run()
to repeatedly run the state machine. Note when you run the op mode that the stick telemetry feedback continues during the countdown.
The entire class is as follows:
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import ftc.crazycatladies.schrodinger.log.DataLogger;
import ftc.crazycatladies.schrodinger.opmode.OpModeTime;
import ftc.crazycatladies.schrodinger.state.StateMachine;
@TeleOp(name="SchrodingerTeleOp")
public class SchrodingerTeleOpMode extends LinearOpMode {
@Override
public void runOpMode() throws InterruptedException {
StateMachine<Integer> sm = null;
final int SECONDS = 5;
DataLogger.createDataLogger(new OpModeTime(this), this.getClass().getSimpleName());
waitForStart();
if (opModeIsActive()) {
sm = new StateMachine("A button countdown");
sm.repeat((state, seconds) -> {
if (gamepad1.a) {
state.next();
}
});
sm.repeat(((state, seconds) -> {
double secsInState = state.getTimeInState().seconds();
telemetry.addData("sm-countdown", (int)(seconds - secsInState));
if (secsInState > seconds) {
state.next();
}
}));
sm.setLooping(true);
sm.init(SECONDS);
}
while (opModeIsActive()) {
sm.run();
telemetry.addData("x", gamepad1.left_stick_x);
telemetry.addData("y", gamepad1.left_stick_y);
telemetry.update();
}
}
}
While a state machine that runs sequentially to the end can be useful in itself for the reasons mentioned above, Schrodinger also allows for state machines to have internal loops or branches using the jump transition.
The code below replaces the initialization of the StateMachine object to add some additional complexity to our countdown. Now the third state will jump back to the previous state 50% of the time to repeat the countdown. You can imagine a need for something like this if a state machine needed to be able to recover automatically from some sort of failure.
sm = new StateMachine("A button countdown");
sm.repeat((state, seconds) -> {
if (gamepad1.a) {
state.next();
}
});
State<Integer> countdown = sm.repeat(((state, seconds) -> {
double secsInState = state.getTimeInState().seconds();
telemetry.addData("sm-countdown", (int)(seconds - secsInState));
if (secsInState > seconds) {
state.next();
}
}));
sm.repeat((state, seconds) -> {
if (Math.random() < 0.5) {
telemetry.addData("sm", "repeat countdown");
state.jump(countdown);
} else {
state.next();
}
});
sm.setLooping(true);
sm.init(SECONDS);
Complicated state machines can be created which are defined more by jumping than following a sequence. For example, a state machine that can transition between any of four repeating states could be implemented with twelve jumps (each state to each other state).
In the previous examples, the state machine is initialized with the number of seconds to count down. The context for the state machine is defined to be a simple Integer object.
It is possible, however, to use much more complex types to provide and maintain a much more complex set of data for a Schrodinger state machine. You could use a data structure like an array, hash map, etc., or you can define your own class and provide an instance of this class in the initialization of the state machine, as shown below.
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import ftc.crazycatladies.schrodinger.log.DataLogger;
import ftc.crazycatladies.schrodinger.opmode.OpModeTime;
import ftc.crazycatladies.schrodinger.state.StateMachine;
@TeleOp(name="SchrodingerCustomContext")
public class SchrodingerCustomContext extends LinearOpMode {
public class SMContext {
int widgetDetected;
}
@Override
public void runOpMode() throws InterruptedException {
StateMachine<SMContext> sm = null;
DataLogger.createDataLogger(new OpModeTime(this), this.getClass().getSimpleName());
waitForStart();
if (opModeIsActive()) {
sm = new StateMachine("context demo");
sm.once((state, context) -> {
context.widgetDetected = (int)(3 * Math.random());
});
sm.pause(500);
sm.repeat((state, context) -> {
if (state.getTimeInState().seconds() < 1) {
telemetry.addData("widgetDetected", context.widgetDetected);
} else {
state.next();
}
});
sm.init(new SMContext());
}
while (opModeIsActive()) {
sm.run();
telemetry.update();
}
}
}
In this example, data is collected in the first state that is needed again in the third state. An SMContext
object is used to store it, in the widgetDetected
field. You can imagine a real-world example of this where a robot uses a sensor to read a clue on the field that defines the location of a game element which the robot then travels to retrieve.
Also, notice that the second state on this state machine is created by using the pause()
function. This makes for an easy way to create a state that waits for a servo to complete movement, for example.
One of the included benefits of Schrodinger is logging. As shown in the snippet below, a history is recorded of each execution of a step with timestamp information, and the string representation of the state machine's context. The context is not repeated again until its string representation has changed - in order to decrease redundancy in the log.
{"opMode":"SchrodingerCustomContext","time":"1589034300710","t":"0.003"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"0.050104","state":"0","context":"SMContext{widgetDetected=0}","nextAction":"StateTransitionAction","t":"1.539"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"0.7363540000000001","state":"1","nextAction":"StateContinueAction","t":"1.539"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"1.380625","state":"1","nextAction":"StateContinueAction","t":"1.539"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"1.93651","state":"1","nextAction":"StateContinueAction","t":"1.539"}
...
{"type":"SM","name":"context demo","execNum":1,"timeInState":"491.933747","state":"1","nextAction":"StateContinueAction","t":"2.030"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"492.190934","state":"1","nextAction":"StateContinueAction","t":"2.030"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"492.44484","state":"1","nextAction":"StateContinueAction","t":"2.030"}
...
{"type":"SM","name":"context demo","execNum":1,"timeInState":"998.912496","state":"2","nextAction":"StateContinueAction","t":"3.035"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"999.291662","state":"2","nextAction":"StateContinueAction","t":"3.035"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"999.600621","state":"2","nextAction":"StateContinueAction","t":"3.035"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"999.890048","state":"2","nextAction":"StateContinueAction","t":"3.041"}
{"type":"SM","name":"context demo","execNum":1,"timeInState":"1000.1840060000001","state":"2","nextAction":"StateTransitionAction","t":"3.041"}


Open Pampas [aw13], plain, in Mandoria, peasants: 100
Last updated Turn #136
Open Pampas [aw13], plain, in Mandoria, peasants: 100
------------------------------------------------------------------------
12: The Savvy Aardvark [ha5r], ship, 2 hulls, 1 rowing port, 6 sails,
12: 22% damaged, arrived from Ocean [av13], owner:
12: Phantasm [n4b], Imperial Empire, duke, with two workers,
12: eight sailors
13: The Savvy Aardvark [ha5r], ship, 2 hulls, 1 rowing port, 6 sails,
13: 22% damaged, departed for Ocean [aw12].
14: Stack of cyclops [bf6m], cyclops, number: 7, went south.
19: Pack of wolves [dg2j], wolves, number: 6, went south.
21: Carmody de L'air [a2o], refugee, arrived from the south.
25: Carmody de L'air [a2o], refugee, went south.
Routes leaving Open Pampas:
North, to Ocean [av13], The Outer Sea, 2 days
East, plain, to Open Pampas [aw14], 7 days
South, forest, to Cyprus Forest [ax13], 8 days
West, to Ocean [aw12], The Outer Sea, 2 days
Inner locations:
Rocky hill [ae4u], rocky hill, 1 day, owner:
Giant lizard [bo1o], giant lizards, number: 19
Seen here:
Stack of giants [cs0k], giants, number: 13
Carmody de L'air [a2o], refugee


Question
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
Stats
| Frequency | 2 |
| Difficulty | 5 |
| Adjusted Difficulty | 3 |
| Time to use | ---------- |
Analysis
The image below explains the solution very well (for the input number “687432”).
Solution
Read this blog for a very nice piece of code.
The following code is written by me.
My code
public class Solution {
public void nextPermutation(int[] num) {
if (num == null || num.length <= 1) {
return;
}
int len = num.length;
int p = len - 2;
// note that when values are equals, proceed the pointer!
// same for line 22
while (p >= 0 && num[p] >= num[p + 1]) {
// move p to left as long as its value is larger than next num
// we want to find the end of increasing sequence (from end to start)
p--;
}
if (p == -1) {
// the input is a strictly decreasing sequence
Arrays.sort(num);
return;
}
// replace number at p with an larger value found in the right of p
int w = len - 1;
while (num[w] <= num[p]) {
w--;
}
// ok, now swap number at p and w
swop(num, p, w);
// reverse all numbers to the right of p
reverse(num, p + 1, len - 1);
}
private void swop(int[] num, int a, int b) {
int temp = num[a];
num[a] = num[b];
num[b] = temp;
}
private void reverse(int[] num, int a, int b) {
while (a < b) {
swop(num, a++, b--);
}
}
}


#include "channel_manager.h"
#include "cachemodel_manager.h"
Go to the source code of this file.
Data Structures | |
| struct | session_param |
| Session parameters. More... | |
| struct | sessionlist_param |
| Session list parameters. More... | |
Typedefs | |
| typedef session_param | session_param_t |
| Session parameters. | |
| typedef sessionlist_param | sessionlist_param_t |
| Session list parameters. | |
Functions | |
| sessionlist_param_t * | gene_sessionlist (void) |
| generate a session list | |
| session_param_t * | gene_session (sessionlist_param_t *sessionlist) |
| generate a session under the sesion list | |
| OPJ_BOOL | search_session_and_channel (char cid[], sessionlist_param_t *sessionlist, session_param_t **foundsession, channel_param_t **foundchannel) |
| search a channel and its belonging session by channel ID | |
| void | insert_cachemodel_into_session (session_param_t *session, cachemodel_param_t *cachemodel) |
| insert a cache model into a session | |
| OPJ_BOOL | delete_session (session_param_t **session, sessionlist_param_t *sessionlist) |
| delete a session | |
| void | delete_sessionlist (sessionlist_param_t **sessionlist) |
| delete session list | |
| void | print_allsession (sessionlist_param_t *sessionlist) |
| print all sessions |
|
|
Session parameters.
|
|
|
Session list parameters.
|
|
|
delete a session
|
|
|
delete session list
|
|
|
generate a session under the sesion list
|
|
|
generate a session list
|
|
|
insert a cache model into a session
|
|
|
print all sessions
|
|
|
search a channel and its belonging session by channel ID
|


|
Jailer is a tool for database subsetting, schema
and data browsing.
It creates small slices from your database and lets you navigate through your database following the relationships..
Ideal for creating small samples of test data or for local problem analysis with relevant production data.
Features
- The Data Browser lets you navigate through your database following the relationships (foreign key-based or user-defined) between tables.
- The Subsetter creates small slices from
your productive database and imports the data into your
development and test environment (consistent and referentially intact).
- Improves database performance by removing and archiving
obsolete data without violating integrity.
- Generates SQL (topologically sorted), XML (hierarchically structured) and DbUnit
datasets.
- A demo database is included with which you can get a first impression without any configuration effort.
Supported Databases
Any DMBS is basically supported thanks to the JDBC technology used.
Jailer also uses additional knowledge to cope with the peculiarities of major database systems. These are:
- PostgreSQL
- Oracle
- MySQL
- MariaDB
- Microsoft SQL Server
- IBM Db2
- SQLite
- Sybase
- Amazon Redshift
- Firebird
- Informix Dynamic Server
- H2
- HSQL (HyperSQL)
- Derby
- Interbase
| |
|
News
|
2023-02-03 |
Thanks to deep analysis of statements, the SQL console can now relate the result of queries to the source tables and display them accordingly. In addition, this technique also allows filter conditions to be dynamically added to arbitrary SQL queries.
|
|
2022-01-01 |
Comprehensive redesign and modernization of the entire user interface.
New Look & Feel FlatLaf.
|
|
2021-02-04 |
Cycles in parent-child relationships will be detected and broken. Thus, such data can be exported by deferring the insertion of nullable foreign keys. |
|
2020-02-04 |
The Jailer engine is published in Maven repository . |
|
2019-02-01 |
The new "Model Migration Tool" allows you to easily find and edit the newly added associations
if the data model has been extended after the last change to this extraction model. |
|
2018-04-26 |
The new
feature "Analyze SQL" analyzes SQL statements and proposes
association definitions. This allows to reverse-engineer the
data model based on existing SQL queries. |
|
2018-03-06 |
SQL Console
with code completion, syntax highlighting and database
metadata visualization. |
|
2017-05-10 |
New API provides programmatic access to the
data export and import functionality. |
|
2017-03-30 |
Improved
filter management . Filter
Templates allows you to define rules for assigning filters to
columns.
Filters on primary key columns will automatically be
propagated to the corresponding foreign key columns. |
|
2015-12-04 |
Data can now also be exported directly to a schema of the same database. This ensures optimal performance. |
|
2015-10-23 |
Rows can alternatively be collected in a separate embedded database. This allows exporting data from read-only databases. |
|
2014-07-20 |
Implemented
the "Subset by Example"
feature: Use the Data Browser to collect all the rows to be
extracted and let Jailer create a model for that subset. |
|
2014-04-15 |
A Data Browser Videos has been introduced.
Navigate bidirectionally through the database by following
foreign-key-based or user-defined relationships. |
About Jailer
Databases are growing in both size and complexity to meet the
increasing demands of business. Applications to process the data
are also increasing in size and complexity. With the growing
complexity, solid testing becomes more and more important in order
to assure the quality of software. Ideally we would like to test
all changes against up-to-date production data, so the general
practice is use a copy of the production database for all
testing.
But when a database exceeds a certain size it becomes very
expensive to provide full-size copies of the production database
for development and testing. One solution of this problem is to
have fewer full size copies of the production database than are
really needed, often only one, which will be shared between the
development and testing teams.
Of course this is far from optimal. Data in the database is left in
an unknown state when passed from one team to the other. It takes a
long time to provide a refresh of the production copy when
it's required. Always having an up-to-date
production copy is almost impossible.
The databases required for development and testing rarely need to
be full size, it is often easier to work on a small copy.
Unfortunately it is very hard to manually extract a small subset of
the production data. It is not possible to just take 10% of each
table to get a 10% size database. The data in one table would not
be related to the data in the other tables. It would not be
referentially
intact.
Jailer simplifies the extraction of referentially intact data. Once
you have defined an extraction
model, it can be used to extract data from the production
database fast and easy whenever up-to-date test data is
required.
|


| # | Sta | Rlx | Name | Row Text |
| 0 | ST | 0 | autoRow0 | one amino acid requires three nucleotides in DNA to be encoded ; to be made (69af-000d-2165-e939) |
| 1 | ST | 0 | autoRow1 | DNA are made of two sequences of nucleotides linked together (9a8c-9e9d-2f7d-537e) |
| 2 | ST | 0 | autoRow2 | a nucleotide is a kind of basic unit of genetic information (2425-834b-a516-1a0d) |
| 3 | ST | 0 | autoRow3 | proteins are made of a chain of 20 amino acids (8f6f-b765-8298-2ac5) |
| 4 | ST | 0 | autoRow4 | the sequence of nucleotides contains genetic information for the organism (dfc7-ea44-9a0a-a350) |
| 5 | ST | 0 | autoRow5 | translation is when genetic information flows from RNA to proteins (73e3-8544-fa97-e4fb) |
| 6 | ST | 0 | autoRow6 | genetic information can be used for making proteins (205f-a820-0cda-de3c) |
| 7 | ST | 0 | autoRow7 | genetic information is encoded in genetic code (3ba4-7de7-8125-4e20) |
| 8 | ST | 0 | autoRow8 | making proteins requires genetic information (def0-6991-a084-0b14) |
| 9 | ST | 0 | autoRow9 | genes contains genetic information (e5cc-028d-dd22-6e8f) |
| 10 | ST | 0 | autoRow10 | In the central dogma of molecular biology , translation follows transcription (b5fa-ca29-d311-6b06) |
| 11 | ST | 0 | autoRow11 | the central dogma of molecular biology begins with the transcription of DNA (bbac-8b14-0705-6c99) |
| 12 | ST | 0 | autoRow12 | transcription is when genetic information flows from DNA to RNA (4101-0f31-6871-d4ea) |
| 13 | ST | 0 | autoRow13 | to be found in means to be contained in (e57b-18c2-73ff-869b) |
| 14 | ST | 0 | autoRow14 | unit is similar to part (c78b-0a6d-70b9-47ff) |


{{ notification.actor.username }}
starred your drawing
Unsubscribe
from emails from DrawQuest.
Copyright © 2013 Canvas Networks, Inc.


5 players set to battle it out for Dubai jackpot
Cape Town - The European Tour season is set for a thrilling finale with five players still in line to claim the jackpot at this week's DP World Tour Championship.
Bernd Wiesberger, Tommy Fleetwood, Jon Rahm, Shane Lowry and Matt Fitzpatrick are all still in with a chance of claiming the Race to Dubai title and earning the $2 million bonus prize, while the season finale itself has a top prize of $3 million to the winner.
Race to Dubai leader Bernd Wiesberger obviously finds himself in the strongest position with just one tournament to play, but if he has a bad week it will open the door for his closest pursuers.
Fleetwood would need a solo third or better; Rahm would need a two-way tie for second or better; Lowry would need a solo second or better; while Fitzpatrick would need to win the title.
As for Wiesberger, if he finishes solo second he will walk away with the jackpot regardless of who claims the trophy.
After skipping the Nedbank Challenge, Open champion Lowry dropped down to fourth in the standings, but a win in Dubai this weekend would still see him claim the double prize, and even a sole runner-up finish would still give him the chance to claim the order of merit title, depending on how the other contenders finish up.
Fleetwood's win in Sun City on Sunday has allowed the Englishman to leapfrog into second place.
"The closer it gets to the end of the season, the harder it is to stay in the present, do your things and concentrate on what you do best. I'm happy for the challenge, feel like I am ready," he said.
Former Race to Dubai winners:
2009 - Lee Westwood
2010 - Martin Kaymer
2011 - Luke Donald
2012 - Rory McIlroy
2013 - Henrik Stenson
2014 - Rory McIlroy
2015 - Rory McIlroy
2016 - Henrik Stenson
2017 - Tommy Fleetwood
2018 - Francesco Molinari
- TeamTalk Media


If you see this page, the default mount point for serving static files is working. Further configuration is required.
$ cncjs -h Usage: cncjs [options] Options: -m, --mount [<url>:]<path> set the mount point for serving static files (default: /static:static)
$ cncjs -m /static:/path/to/your/static/files
The example shown below is a tiny web interface for small size LCD display 320x240 with very limited features.
Visit http://localhost:8000/pendant/ after running the command:
$ cncjs -m /pendant:/path/to/tinyweb
For online documentation please refer to https://cnc.js.org/docs.


--- title: Winter in the Garden date: 2009-01-12 00:00:00 -06:00 categories: - whats-blooming layout: post blog-banner: whats-blooming-now-winter.jpg post-date: January 12, 2009 post-time: 11:32 AM blog-image: wbn-default.jpg ---
Liriodendron tulipifera Dried fruit with snow
Orangerie and Wind Sculpture
Herb Garden
Tree Squirrel
Aronia arbutifolia Red Chokecherry
Everything stands out against the backdrop of white, from the dark greens of the conifers to the red of the sandstone walls.
Our hard working garden staff does an excellent job at keeping all of the paths in the garden snow and ice free. So come take advantage of this perfect opportunity to see the garden and take some great photos.. Be sure to keep an eye out for our some of our elusive garden visitors such as bobcats and coyotes.


-
Must See Places of the New Year
Whether it’s India’s literary hub or Switzerland’s mountain majesty, these go-now destinations will send you packing.
Read more -
Must See Places of the New Year
Whether it’s India’s literary hub or Switzerland’s mountain majesty, these go-now destinations will send you packing.
Read more -
Must See Places of the New Year
Whether it’s India’s literary hub or Switzerland’s mountain majesty, these go-now destinations will send you packing.
Read more


Soldier Tenis:
What? Really?  Then give me that horn. Shall we open the box?
(Hand over the horn.) "Why don't you open this box?"