text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="CONSTRAINT clause" />
<meta content="CONSTRAINT clause, Constraints, Storage properties, for indexes backing constraints, Backing indexes, specifying storage properties for, Tables, specifying page size for, specifying properties for" name="DC.subject" />
<meta content="CONSTRAINT clause, Constraints, Storage properties, for indexes backing constraints, Backing indexes, specifying storage properties for, Tables, specifying page size for, specifying properties for" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefclauses.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj16095.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj42154.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj16357.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj91438.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj13590" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>CONSTRAINT clause</title>

CONSTRAINT clause

A CONSTRAINT clause is an optional part of a CREATE TABLE statement or ALTER TABLE statement. A constraint is a rule to which data
must conform. Constraint names are optional.

A CONSTRAINT can be one
of the following:

a
column-level constraint
Column-level constraints refer to a single column
in the table and do not specify a column name (except check constraints).
They refer to the column that they follow.

a
table-level constraint
Table-level constraints refer to one or more columns
in the table. Table-level constraints specify the names of the columns to
which they apply. Table-level CHECK constraints can refer to 0 or more columns
in the table.

Column
constraints include:

NOT NULL
Specifies that this column cannot hold NULL values (constraints
of this type are not nameable).

PRIMARY KEY

Specifies the column that uniquely identifies a row in the table. The
identified columns must be defined as NOT NULL.

Note: If you attempt
to add a primary key using ALTER TABLE and any of the columns included in
the primary key contain null values, an error will be generated and the primary
key will not be added. See ALTER TABLE statement for
more information.

UNIQUE
Specifies that values in the column must be unique.

FOREIGN KEY
Specifies that the values in the column must correspond
to values in a referenced primary key or unique key column or that they are
NULL.

CHECK
Specifies rules for values in the column.

Table constraints include:

PRIMARY KEY
Specifies
the column or columns that uniquely identify a row in the table. NULL values
are not allowed.

UNIQUE
Specifies that values in the columns must be unique.

FOREIGN KEY
Specifies that the values in the columns must correspond
to values in referenced primary key or unique columns or that they are NULL.

Note: If
the foreign key consists of multiple columns, and any column is NULL,
the whole key is considered NULL. The insert is permitted no matter what is
on the non-null columns.

CHECK
Specifies a wide range of rules for values in the table.

Column constraints and table constraints
have the same function; the difference is in where you specify them. Table
constraints allow you to specify more than one column in a PRIMARY KEY, UNIQUE,
CHECK, or FOREIGN KEY constraint definition. Column-level constraints (except
for check constraints) refer to only one column.

A constraint operates with the privileges of the owner of the constraint.
See "Using SQL standard authorization" and "Privileges on views, triggers, and
constraints" in the Java DB Developer's Guide for
details.

Syntax

Primary key constraints

A primary
key defines the set of columns that uniquely identifies rows in a table.

When
you create a primary key constraint, none of the columns included in the primary
key can have NULL constraints; that is, they must not permit NULL values.

ALTER
TABLE ADD PRIMARY KEY allows you to include existing columns in a primary
key if they were first defined as NOT NULL. NULL values are not allowed. If
the column(s) contain NULL values, the system will not add the primary key
constraint. See ALTER TABLE statement for more information.

A
table can have at most one PRIMARY KEY constraint.

Unique constraints

A UNIQUE constraint defines a set of columns that uniquely identify rows in a
table only if all the key values are not NULL. If one or more key parts are
NULL, duplicate keys are allowed.

For example, if there is a UNIQUE constraint on <samp class="codeph">col1</samp> and
<samp class="codeph">col2</samp> of a table, the combination of the values held by
<samp class="codeph">col1</samp> and <samp class="codeph">col2</samp> will be unique as long
as these values are not NULL. If one of <samp class="codeph">col1</samp> and
<samp class="codeph">col2</samp> holds a NULL value, there can be another identical row in
the table.

A table can have multiple UNIQUE constraints.

Foreign key constraints

Foreign keys provide
a way to enforce the referential integrity of a database. A foreign key is
a column or group of columns within a table that references a key in some
other table (or sometimes, though rarely, the same table). The foreign key
must always include the columns of which the types exactly match those in
the referenced primary key or unique constraint.

For a table-level
foreign key constraint in which you specify the columns in the table that
make up the constraint, you cannot use the same column more than once.

If
there is a column list in the ReferencesSpecification (a list of columns
in the referenced table), it must correspond either to a unique constraint
or to a primary key constraint in the referenced table. The ReferencesSpecification can
omit the column list for the referenced table if that table has a declared
primary key.

If there is no column list in the ReferencesSpecification and
the referenced table has no primary key, a statement exception is thrown.
(This means that if the referenced table has only unique keys, you must include
a column list in the ReferencesSpecification.)

A foreign key
constraint is satisfied if there is a matching value in the referenced unique
or primary key column. If the foreign key consists of multiple columns, the
foreign key value is considered NULL if any of its columns contains a NULL.

Note: It is possible for a foreign key consisting of multiple columns to
allow one of the columns to contain a value for which there is no matching
value in the referenced columns, per the SQL-92 standard. To avoid this situation,
create NOT NULL constraints on all of the foreign key's columns.

Foreign key constraints and DML

When you insert
into or update a table with an enabled foreign key constraint, Derby checks
that the row does not violate the foreign key constraint by looking up the
corresponding referenced key in the referenced table. If the constraint is
not satisfied, Derby rejects
the insert or update with a statement exception.

When you update or
delete a row in a table with a referenced key (a primary or unique constraint
referenced by a foreign key), Derby checks
every foreign key constraint that references the key to make sure that the
removal or modification of the row does not cause a constraint violation.
If removal or modification of the row would cause a constraint violation,
the update or delete is not permitted and Derby throws
a statement exception.

Derby performs
constraint checks at the time the statement is executed, not when the transaction
commits.

Backing indexes

UNIQUE,
PRIMARY KEY, and FOREIGN KEY constraints generate indexes that enforce or
"back" the constraint (and are sometimes called backing indexes).
PRIMARY KEY constraints generate unique indexes. FOREIGN KEY constraints
generate non-unique indexes. UNIQUE constraints generate unique indexes if
all the columns are non-nullable, and they generate non-unique indexes if
one or more columns are nullable. Therefore, if a column or set of columns has
a UNIQUE, PRIMARY KEY, or FOREIGN KEY constraint on it, you do not need to
create an index on those columns for performance. Derby has
already created it for you. See Indexes and constraints.

These indexes are
available to the optimizer for query optimization (see CREATE INDEX statement)
and have system-generated names.

You cannot drop backing indexes with
a DROP INDEX statement; you must drop the constraint or the table.

Check constraints

A
check constraint can be used to specify a wide range of rules for the contents
of a table. A search condition (which is a boolean expression) is specified
for a check constraint. This search condition must be satisfied for all rows
in the table. The search condition is applied to each row that is modified
on an INSERT or UPDATE at the time of the row modification. The entire statement
is aborted if any check constraint is violated.

Requirements for search condition

If
a check constraint is specified as part of a column-definition, a column reference
can only be made to the same column. Check constraints specified as part of
a table definition can have column references identifying columns previously
defined in the CREATE TABLE statement.

The search condition must always
return the same value if applied to the same values. Thus, it cannot contain
any of the following:

Dynamic parameters (?)

Date/Time Functions (CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP)

Subqueries

User Functions (such as USER, SESSION_USER, CURRENT_USER)

Referential actions

You can specify
an ON DELETE clause and/or an ON UPDATE clause, followed by the appropriate
action (CASCADE, RESTRICT, SET NULL, or NO ACTION) when defining foreign keys.
These clauses specify whether Derby should
modify corresponding foreign key values or disallow the operation, to keep
foreign key relationships intact when a primary key value is updated or deleted
from a table.

You specify the update and delete rule of a referential
constraint when you define the referential constraint.

The update rule
applies when a row of either the parent or dependent table is updated. The
choices are NO ACTION and RESTRICT.

When a value in a column of the
parent table's primary key is updated and the update rule has been specified
as RESTRICT, Derby checks
dependent tables for foreign key constraints. If any row in a dependent table
violates a foreign key constraint, the transaction is rolled back.

If
the update rule is NO ACTION, Derby checks
the dependent tables for foreign key constraints after all updates
have been executed but before triggers have been executed. If any row
in a dependent table violates a foreign key constraint, the statement is rejected.

When
a value in a column of the dependent table is updated, and that value is part
of a foreign key, NO ACTION is the implicit update rule. NO ACTION means that
if a foreign key is updated with a non-null value, the update value must match
a value in the parent table's primary key when the update statement is completed.
If the update does not match a value in the parent table's primary key, the
statement is rejected.

The delete rule applies when a row of the parent
table is deleted and that row has dependents in the dependent table of the
referential constraint. If rows of the dependent table are deleted, the delete
operation on the parent table is said to be propagated to the dependent
table. If the dependent table is also a parent table, the action specified
applies, in turn, to its dependents.

The choices are NO ACTION, RESTRICT,
CASCADE, or SET NULL. SET NULL can be specified only if some column of the
foreign key allows null values.

If the delete rule is:

NO ACTION, Derby checks the dependent
tables for foreign key constraints after all deletes have been executed
but before triggers have been executed. If any row in a dependent table
violates a foreign key constraint, the statement is rejected.

RESTRICT, Derby checks dependent tables
for foreign key constraints. If any row in a dependent table violates a foreign
key constraint, the transaction is rolled back.

CASCADE, the delete
operation is propagated to the dependent table (and that table's dependents,
if applicable).

SET NULL, each nullable column of the dependent table's
foreign key is set to null. (Again, if the dependent table also has dependent
tables, nullable columns in those tables' foreign keys are also set to null.)

Each
referential constraint in which a table is a parent has its own delete rule;
all applicable delete rules are used to determine the result of a delete operation.
Thus, a row cannot be deleted if it has dependents in a referential constraint
with a delete rule of RESTRICT or NO ACTION. Similarly, a row cannot be deleted
if the deletion cascades to any of its descendants that are dependents in
a referential constraint with the delete rule of RESTRICT or NO ACTION.

Deleting
a row from the parent table involves other tables. Any table involved in a
delete operation on the parent table is said to be delete-connected to the
parent table. The delete can affect rows of these tables in the following
ways:

If the delete rule is RESTRICT or NO ACTION, a dependent table is involved
in the operation but is not affected by the operation. (That is, Derby checks
the values within the table, but does not delete any values.)

If the delete rule is SET NULL, a dependent table's rows can be updated
when a row of the parent table is the object of a delete or propagated delete
operation.

If the delete rule is CASCADE, a dependent table's rows can be deleted
when a parent table is the object of a delete.

If the dependent table is also a parent table, the actions described in
this list apply, in turn, to its dependents.

Examples

-- column-level primary key constraint named OUT_TRAY_PK:
CREATE TABLE SAMP.OUT_TRAY
	(
	SENT TIMESTAMP,
	DESTINATION CHAR(8),
	SUBJECT CHAR(64) NOT NULL CONSTRAINT OUT_TRAY_PK PRIMARY KEY,
	NOTE_TEXT VARCHAR(3000)
   );

-- the table-level primary key definition allows you to
-- include two columns in the primary key definition:
CREATE TABLE SAMP.SCHED
	(
	CLASS_CODE CHAR(7) NOT NULL,
	DAY SMALLINT NOT NULL,
	STARTING TIME,
	ENDING TIME,
	PRIMARY KEY (CLASS_CODE, DAY)
	);

-- Use a column-level constraint for an arithmetic check
-- Use a table-level constraint
-- to make sure that a employee's taxes does not
-- exceed the bonus
CREATE TABLE SAMP.EMP
	(
	EMPNO CHAR(6) NOT NULL CONSTRAINT EMP_PK PRIMARY KEY,
	FIRSTNME CHAR(12) NOT NULL,
	MIDINIT vARCHAR(12) NOT NULL,
	LASTNAME VARCHAR(15) NOT NULL,
	SALARY DECIMAL(9,2) CONSTRAINT SAL_CK CHECK (SALARY >= 10000),
	BONUS DECIMAL(9,2),
	TAX DECIMAL(9,2),
	CONSTRAINT BONUS_CK CHECK (BONUS > TAX)
	);

-- use a check constraint to allow only appropriate
-- abbreviations for the meals
CREATE TABLE FLIGHTS
	(
	FLIGHT_ID CHAR(6) NOT NULL ,
	SEGMENT_NUMBER INTEGER NOT NULL ,
	ORIG_AIRPORT CHAR(3),
	DEPART_TIME TIME,
	DEST_AIRPORT CHAR(3),
	ARRIVE_TIME TIME,
	MEAL CHAR(1) CONSTRAINT MEAL_CONSTRAINT
	CHECK (MEAL IN ('B', 'L', 'D', 'S')),
	PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER)
	);

CREATE TABLE METROPOLITAN
	(
	HOTEL_ID INT NOT NULL CONSTRAINT HOTELS_PK PRIMARY KEY,
	HOTEL_NAME VARCHAR(40) NOT NULL,
	CITY_ID INT CONSTRAINT METRO_FK REFERENCES CITIES
	);

-- create a table with a table-level primary key constraint
-- and a table-level foreign key constraint
CREATE TABLE FLTAVAIL
	(
	FLIGHT_ID CHAR(6) NOT NULL,
	SEGMENT_NUMBER INT NOT NULL,
	FLIGHT_DATE DATE NOT NULL,
	ECONOMY_SEATS_TAKEN INT,
	BUSINESS_SEATS_TAKEN INT,
	FIRSTCLASS_SEATS_TAKEN INT,
	CONSTRAINT FLTAVAIL_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER),
	CONSTRAINT FLTS_FK
	FOREIGN KEY (FLIGHT_ID, SEGMENT_NUMBER)
	REFERENCES Flights (FLIGHT_ID, SEGMENT_NUMBER)
	);
-- add a unique constraint to a column
ALTER TABLE SAMP.PROJECT
ADD CONSTRAINT P_UC UNIQUE (PROJNAME);

-- create a table whose city_id column references the
-- primary key in the Cities table
-- using a column-level foreign key constraint
CREATE TABLE CONDOS
	(
	CONDO_ID INT NOT NULL CONSTRAINT hotels_PK PRIMARY KEY,
	CONDO_NAME VARCHAR(40) NOT NULL,
	CITY_ID INT CONSTRAINT city_foreign_key
	REFERENCES Cities ON DELETE CASCADE ON UPDATE RESTRICT
	);

Statement dependency system

INSERT
and UPDATE statements depend on all constraints on the target table. DELETEs
depend on unique, primary key, and foreign key constraints. These statements
are invalidated if a constraint is added to or dropped from the target table.

Column-level-constraint

Table-level constraint

References specification

searchCondition

Parent topic: SQL clauses


text:
'use strict';
var _ = require('lodash'),
	mongoose = require('mongoose'),
	formidable = require('formidable'),
	fs = require('fs'),
	path = require('path');

var Article = mongoose.model('Article');

var getArticleById = function (id) {
	return Article.findById(id).exec();
};

var buildImagePath = function(uploadDir, name) {
	return path.resolve(uploadDir, 'img', name);
};

module.exports.get = function (req, res, next, id) {
	getArticleById(id).then(function (article) {
		if (article) {
			req._article = article;
			next();
		} else {
			res.status(404);
		}
	});
};
module.exports.create = function (req, res, next) {
	var article = new Article({
		heading: 'New Article',
		enabled: false,
		time: new Date()
	});

	article.save(function () {
		res.redirect(req.__enhance.mount('/article/' + article.id));
	});
};
module.exports.all = function (req, res, next) {
	var query = Article.find().sort('-time');

	query.exec().then(function (articles) {
		res.render(req.__enhance.view('article/list'), {
			articles: articles
		});
	});
};
module.exports.show = function (req, res, next) {
	res.render(req.__enhance.view('article/detail'), {
		article: req._article
	});
};
module.exports.showJSON = function (req, res, next) {
	getArticleById(req._params.id).then(function (article) {
		res.json({
			article: article
		});
	});
};
module.exports.createExtract = function (req, res, next) {
	var index = req._article.extracts.length || 0;
	req._article.extracts.push(req.body);
	req._article.extracts[index].identifier = new Date().getTime();

	// sort by identider - ascending
	req._article.extracts.sort(function (extract1, extract2) {
		return extract1.identifier - extract2.identifier;
	});

	req._article.save(function (err) {
		if (err) {
			res.status(500).jsonp({
				err: err
			});
		} else {
			res.json({
				extract: req._article.extracts[index]
			});
		}
	});
};
module.exports.updateExtract = function (req, res, next) {
	var extract = req._article.extracts.id(req._params.id);
	extract = _.assign(extract, req.body);

	req._article.save(function (err) {
		if (err) {
			res.status(500).jsonp({
				err: err
			});
		} else {
			res.json({
				extract: extract
			});
		}
	});
};
module.exports.removeExtract = function (req, res, next) {
	var extract = req._article.extracts.id(req._params.id);

	if (extract.image) {
		fs.unlink(buildImagePath(req.__uploadDir, extract.image));
	}

	extract.remove();

	req._article.save(function (err) {
		if (err) {
			res.status(500).jsonp({
				err: err
			});
		} else {
			res.json({
				result: true
			});
		}
	});
};
module.exports.saveDraft = function (req, res, next) {
	// disable the article
	req.body.enabled = false;
	Article.update({
		_id: req._params.id
	}, req.body).exec().then(function (data) {
		res.json({
			result: data
		});
	}, function (err) {
		res.status(500).json(err);
	});
};
module.exports.publish = function (req, res, next) {
	req._article.enabled = true;

	req._article.save(function () {
		res.redirect(req.__enhance.mount('/articles'));
	});
};
module.exports.uploadImage = function (req, res, next) {
	var form = new formidable.IncomingForm();

	form.parse(req, function (err, fields, files) {
		var source = fs.createReadStream(files.file.path);

		var destPath = buildImagePath(req.__uploadDir, fields.name);

		var dest = fs.createWriteStream(destPath, {
			flags: 'a'
		});

		source.pipe(dest);

		source.on('end', function () {
			fs.unlink(files.file.path);

			res.json({
				image: fields.name
			});
		});

		source.on('error', function (err) {
			res.json({
				error: err
			});
		});
	});
};
module.exports.removeImage = function (req, res, next) {
	var destPath = buildImagePath(req.__uploadDir, req._params.id);

	fs.unlink(destPath, function (err) {
		res.json({
			result: err || true
		});
	});
};
module.exports.destroy = function (req, res, next) {
	var index,
		destPath;

	for (index in req._article.images) {
		destPath = buildImagePath(req.__uploadDir, req._article.images[index]);
		fs.unlink(destPath);
	}

	for (index in req._article.extracts) {
		if (!!req._article.extracts[index].image) {
			destPath = buildImagePath(req.__uploadDir, req._article.extracts[index].image);
			fs.unlink(destPath);
		}
	}

	req._article.remove(function () {
		res.redirect(req.__enhance.mount('/articles'));
	});
};

redpajama_set_name: RedPajamaGithub


text:
degenerator
===========
### Turns sync functions into async generator functions
[![Build Status](https://travis-ci.org/TooTallNate/node-degenerator.png?branch=master)](https://travis-ci.org/TooTallNate/node-degenerator)

Sometimes you need to write sync looking code that's really async under the hood.
This module takes a String to one or more synchronous JavaScript functions, and
returns a new String that with those JS functions transpiled into ES6 Generator
Functions.

So this:

``` js
function foo () {
  return a('bar') || b();
}
```

Gets compiled into:

``` js
function* foo() {
    return (yield a('bar')) || (yield b());
}
```

From there, you can provide asynchronous thunk-based or Generator-based
implementations for the `a()` and `b()` functions, in conjunction with any
Generator-based flow control library to execute the contents of the
function asynchronously.

Installation
------------

Install with `npm`:

``` bash
$ npm install degenerator
```

Example
-------

You must explicitly specify the names of the functions that should be
"asyncified". So say we wanted to expose a `get(url)` function that did
and HTTP request and returned the response body.

The user has provided us with this implementation:

``` js
function myFn () {
  var one = get('https://google.com');
  var two = get('http://nodejs.org');
  var three = JSON.parse(get('http://jsonip.org'));
  return [one, two, three];
}
```

Now we can compile this into an asyncronous generator function, implement the
async `get()` function, and finally evaluate it into a real JavaScript function
instance with the `vm` module:

``` js
var co = require('co');
var vm = require('vm');
var degenerator = require('degenerator');

// the `get()` function is thunk-based (error handling omitted for brevity)
function get (endpoint) {
  return function (fn) {
    var mod = 0 == endpoint.indexOf('https:') ? require('https') : require('http');
    var req = mod.get(endpoint);
    req.on('response', function (res) {
      var data = '';
      res.setEncoding('utf8');
      res.on('data', function (b) { data += b; });
      res.on('end', function () {
        fn(null, data);
      });
    });
  };
}

// convert the JavaScript string provided from the user (assumed to be `str` var)
str = degenerator(str, [ 'get' ]);

// at this stage, you could use a transpiler like `facebook/regenerator`
// here if desired.

// turn the JS String into a real GeneratorFunction instance
var genFn = vm.runInNewContext('(' + str + ')', { get: get });

// use a generator-based flow control library (`visionmedia/co`, `jmar777/suspend`,
// etc.) to create an async function from the generator function.

var asnycFn = co(genFn);

// NOW USE IT!!!
asyncFn(function (err, res) {
  // ...
});
```

API
---

### degenerator(String jsStr, Array functionNames) → String

Returns a "degeneratorified" JavaScript string, with ES6 Generator
functions transplanted.

License
-------

(The MIT License)

Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>Groups of selectors</title>

  <link rel="next" href="css3-modsel-2.xml" title="Type element selectors"/>
  <link rel="last" href="css3-modsel-d4.xml" title="Dynamic updating of :first-child and :last-child"/>
  <link rel="up" href="./index.html"/>
  <link rel="top" href="../../index.html"/>

The background of this list item should be green

The background of this second list item should be also green

The background of this paragraph should be green.


text:
package com.intel.icecp.node.management;

import com.intel.icecp.core.Channel;
import com.intel.icecp.core.channels.ChannelProvider;
import com.intel.icecp.core.management.ConfigurationManager;
import com.intel.icecp.core.metadata.formats.JsonFormat;
import com.intel.icecp.core.messages.ConfigurationMessage;
import com.intel.icecp.core.metadata.Persistence;
import com.intel.icecp.core.misc.ChannelLifetimeException;
import com.intel.icecp.core.misc.Configuration;
import com.intel.icecp.core.pipeline.Pipeline;
import com.intel.icecp.node.ConfigurationImpl;
import com.intel.icecp.node.pipeline.implementations.MessageFormattingPipeline;
import java.net.URI;
import java.nio.file.Path;

/**
 * Retrieve configuration files from a specific file system location.
 *
 */
public class FileConfigurationManager implements ConfigurationManager {

    public static final String FILE_SUFFIX = ".json";
    private final Path configurationRoot;
    private final ChannelProvider channelBuilder;

    /**
     * Constructor
     *
     * @param configurationRoot the {@link Path} where all
     * @param channelBuilder mechanism for creating channels to retrieve
     * configurations
     */
    public FileConfigurationManager(Path configurationRoot, ChannelProvider channelBuilder) {
        this.configurationRoot = configurationRoot;
        this.channelBuilder = channelBuilder;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Configuration get(String name) {
        return new ConfigurationImpl(getChannel(name));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Channel<ConfigurationMessage> getChannel(String name) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("No configuration name given.");
        }
        URI uri = configurationRoot.resolve(name + FILE_SUFFIX).toUri();
        Pipeline p = MessageFormattingPipeline.create(ConfigurationMessage.class, new JsonFormat(ConfigurationMessage.class));
        try {
            return channelBuilder.build(uri, p, new Persistence());
        } catch (ChannelLifetimeException ex) {
            throw new IllegalArgumentException("Unable to create the desired channel: " + uri, ex);
        }
    }
}


text:
#pragma once

#include "library/sp.h"
#include "library/strings.h"
#include "library/vec.h"
#include <vector>

namespace OpenApoc
{

class Renderer;
class TileMap;
class Tile;
class VoxelMap;
class Image;
enum class TileViewMode;
class TileTransform;

class TileObject : public std::enable_shared_from_this<TileObject>
{
  public:
	enum class Type
	{
		// For purpose of detemining draw order, these four must come first
		Ground,
		LeftWall,
		RightWall,
		Feature,

		// From here on in, anything else goes. However, object type is a tiebreaker
		// in case both objects are located on the same exact position
		Shadow,
		Item,
		Unit,
		Projectile,
		Vehicle,
		Scenery,
		Doodad,
		Hazard,
	};

	/* 'screenPosition' is where the center of the object should be drawn */
	virtual void draw(Renderer &r, TileTransform &transform, Vec2<float> screenPosition,
	                  TileViewMode mode, bool visible = true, int currentLevel = 0,
	                  bool friendly = false, bool hostile = false) = 0;
	const Type &getType() const { return this->type; }
	virtual Vec3<float> getPosition() const = 0;
	// Vector from object position to object center
	virtual Vec3<float> getCenterOffset() const { return {0.0f, 0.0f, 0.0f}; }
	virtual Vec3<float> getCenter() const { return getPosition() + getCenterOffset(); };

	// Used to calculate draw order
	virtual float getZOrder() const { return getCenter().z + (float)getType() / 1000.0f; }

	virtual float getDistanceTo(sp<TileObject> target) const;
	virtual float getDistanceTo(Vec3<float> target) const;
	// For TileObjects, position is usually the location of the object's centre
	// Usually, owner objects will have the same position (i.e. proj.pos == to_proj.pos)
	// Some, however, will not (scenery's position points to top left corner, but
	// getPosition returns centre)
	// Some TileObjects, OTOH, have position pointing to their center on xy and bottom on z
	// This is useful for battlescape where object should be assigned to the tile where
	// it is resting, therefore, where it's bottom is
	virtual void setPosition(Vec3<float> newPosition);
	virtual void removeFromMap();
	virtual void addToDrawnTiles(Tile *tile);

	Tile *getOwningTile() const { return this->owningTile; }
	std::vector<Tile *> getIntersectingTiles() const { return this->intersectingTiles; }

	virtual sp<VoxelMap> getVoxelMap(Vec3<int> /*mapIndex*/, bool /*los*/) const { return nullptr; }
	virtual bool hasVoxelMap(bool los) const { return false; }
	// Vector from voxel map top left back corner to object center
	virtual Vec3<float> getVoxelOffset() const { return bounds_div_2; }
	virtual Vec3<float> getVoxelCentrePosition() const { return {0.0, 0.0, 0.0}; }
	Vec3<float> getBounds() const { return bounds; }

	virtual const UString &getName() { return this->name; }

	virtual ~TileObject();

	TileMap ↦

	static void drawTinted(Renderer &r, sp<Image> sprite, Vec2<float> position, bool visible);

	// TileObjects are not copy-able
	TileObject(const TileObject &) = delete;
	// Move is fine
	TileObject(TileObject &&) = default;

  protected:
	friend class TileMap;

	Type type;

	Tile *owningTile;
	Tile *drawOnTile;
	std::vector<Tile *> intersectingTiles;

	TileObject(TileMap &map, Type type, Vec3<float> bounds);

	// The bounds is a cube centered around the 'position' used for stuff like collision detection
	Vec3<float> bounds;
	// Bounds hardly ever change, so this will provide faster calculations
	// Bounds divided by 2, used to find inclusive object boundary's coordinates
	Vec3<float> bounds_div_2;

	virtual void setBounds(Vec3<float> bounds);

	UString name;

  private:
};

} // namespace OpenApoc


text:
package info.openmods.calc.types.bool;

import info.openmods.calc.IValuePrinter;
import info.openmods.calc.utils.config.ConfigProperty;

public class BoolPrinter implements IValuePrinter<Boolean> {

	@ConfigProperty
	public boolean numeric = false;

	@Override
	public String str(Boolean value) {
		if (numeric) return value? "1" : "0";
		return value.toString();
	}

	@Override
	public String repr(Boolean value) {
		return value.toString();
	}
}


text:
"""This module handles triggering Kokoro release jobs for merged release pull requests."""

import importlib
import re
from typing import Tuple

from autorelease import common, github, kokoro, reporter

LANGUAGE_ALLOWLIST = []
ORGANIZATIONS_TO_SCAN = ["googleapis", "GoogleCloudPlatform"]

# Whenever we add new languages to the allowlist, update this value as
# well to prevent trying to release old versions.
CREATED_AFTER = "2021-04-01"

def trigger_kokoro_build_for_pull_request(
    kokoro_session,
    gh: github.GitHub,
    issue: dict,
    result,
    update_labels: bool = True,
    use_allowlist: bool = True,
) -> None:
    """Triggers the Kokoro job for a given pull request if possible.

    If the pull request is not merged, remove the `autorelease: pending` label
    and mark it as closed. Otherwise, determine the name of the Kokoro job
    name and trigger a build.
    """
    # Reify the "issue" into a full pull request object from github. This
    # is necessary because github gives us back an issue object, but it
    # doesn't contain all of the PR info.
    pull = gh.get_url(issue["pull_request"]["url"])

    # Before doing any processing, check to make sure the PR was actually merged.
    # "closed" PRs can be merged or just closed without merging.
    if not pull.get("merged_at"):
        result.skipped = True
        result.print("Closed, not merged, skipping.")
        # Remove the label so we don't continue processing it.
        gh.update_pull_labels(
            pull, add=["autorelease: closed"], remove=["autorelease: pending"]
        )
        return

    # If the Kokoro job has already been triggered, don't trigger again.
    if "labels" in pull and any(
        "name" in label and label["name"] == "autorelease: triggered"
        for label in pull["labels"]
    ):
        return

    # Determine language.
    lang = common.guess_language(gh, pull["base"]["repo"]["full_name"])

    # As part of the migration to release-please tagging, cross-reference the
    # language against an allowlist to allow migrating language-by-language.
    if use_allowlist and lang not in LANGUAGE_ALLOWLIST:
        result.skipped = True
        result.print(f"Language {lang} not in allowlist, skipping.")
        return

    language_module = importlib.import_module(f"releasetool.commands.tag.{lang}")
    package_name = language_module.package_name(pull)
    kokoro_job_name = language_module.kokoro_job_name(
        pull["base"]["repo"]["full_name"], package_name
    )
    pull_request_url = pull["html_url"]
    if kokoro_job_name is None:
        result.skipped = True
        result.print(f"No Kokoro job for {pull_request_url}, skipping.")
        return

    sha = pull["merge_commit_sha"]

    # Trigger Kokoro release build
    result.print(f"Triggering {kokoro_job_name} using {sha}")
    kokoro.trigger_build(
        kokoro_session,
        job_name=kokoro_job_name,
        sha=sha,
        env_vars={"AUTORELEASE_PR": pull_request_url},
    )
    if update_labels:
        gh.update_pull_labels(pull, add=["autorelease: triggered"])

def _parse_issue(pull_request_url: str) -> Tuple[str, int]:
    match = re.match(".*github.com/(.*)/pull/(\\d+)", pull_request_url)
    if match:
        return match[1], match[2]
    raise Exception(f"bad url format: {pull_request_url}")

def trigger_single(
    github_token: str, kokoro_credentials: str, pull_request_url: str
) -> reporter.Reporter:
    report = reporter.Reporter("autorelease.trigger")
    # TODO(busunkim): Use proxy once KMS setup is complete.
    gh = github.GitHub(github_token, use_proxy=False)

    if kokoro_credentials:
        kokoro_session = kokoro.make_authorized_session(kokoro_credentials)
    else:
        kokoro_session = kokoro.make_adc_session()

    try:
        repository, number = _parse_issue(pull_request_url)
        issue = gh.get_issue(repository, number)
        result = reporter.Result(f"{issue['title']}")
        result.print(
            f"Processing {issue['title']}: {issue['pull_request']['html_url']}"
        )
        report.add(result)
    except Exception:
        result = reporter.Result(pull_request_url, error=True)
        result.print(f"Error fetching pull request: {pull_request_url}")
        report.add(result)
        return report

    try:
        trigger_kokoro_build_for_pull_request(
            kokoro_session, gh, issue, result, False, False
        )
    # Failing any one PR is fine, just record it in the log and continue.
    except Exception as exc:
        result.error = True
        result.print(f"{exc!r}")

    return report

def main(github_token: str, kokoro_credentials: str) -> reporter.Reporter:
    report = reporter.Reporter("autorelease.trigger")
    # TODO(busunkim): Use proxy once KMS setup is complete.
    gh = github.GitHub(github_token, use_proxy=False)

    if kokoro_credentials:
        kokoro_session = kokoro.make_authorized_session(kokoro_credentials)
    else:
        kokoro_session = kokoro.make_adc_session()

    # First, we need to get a list of all pull requests (GitHub calls these "issues")
    # that are merged ("closed") and have the label "autorelease: tagged".
    list_result = reporter.Result("list issues")
    report.add(list_result)

    all_issues = []
    for org in ORGANIZATIONS_TO_SCAN:
        try:
            issues = gh.list_org_issues(
                org=org,
                # Must be merged ("closed").
                state="closed",
                # Must be labeled with "autorelease: pending"
                labels="autorelease: tagged",
                # Only look at issues created recently
                created_after=CREATED_AFTER,
            )

            # Just in case any non-PRs got in here.
            issues = [result for result in issues if "pull_request" in result]

            all_issues.extend(issues)

        # Exceptions while getting the list of pull requests constitutes a total failure.
        except Exception as exc:
            list_result.error = True
            list_result.print(exc)

    # Print out our findings as a checkpoint.
    list_result.print("Working set:")
    for issue in all_issues:
        list_result.print(f" * {issue['title']}: {issue['pull_request']['html_url']}")

    # For each pull request, execute releasetool tag for it.
    for issue in all_issues:
        result = reporter.Result(f"{issue['title']}")
        report.add(result)
        result.print(
            f"Processing {issue['title']}: {issue['pull_request']['html_url']}"
        )

        try:
            trigger_kokoro_build_for_pull_request(kokoro_session, gh, issue, result)
        # Failing any one PR is fine, just record it in the log and continue.
        except Exception as exc:
            result.error = True
            result.print(f"{exc!r}")

    return report


text:
layout: post
title: "Switching Docker from aufs to devicemapper"
category: posts
---
We use [Docker](http://docker.io) for various teaching webservices ([Codematch](http://codematch.muehe.org), [Xquery](http://xquery.muehe.org), [Datalog](http://datalog.muehe.org)) we want to offer to students but which should not cause our webserver to be more exposed. Docker has been good so far and we have already used the architecture to migrate all containers from the original dev host to the production webserver host. Here, we'll talk about switching from AUFS to Devicemapper as a storage backend.

Why device mapper?
------------------

I can not attest to either storage backend being strictly better or worse than the other. However, for us the benefit is being able to run IBM DB2 without resorting to mounting an external volume for the DB2 container. This is beneficial, as using external storage break the versioned architecture of docker while keeping all data inside the container's filesystem yields a nice separation of concerns.

1) Exporting all important images
---------------------------------

We first committed each image we care for so that we had the most recent version tagged somewhere with all changes included. This can be done roughly like this

	docker ps -a
	# for each container you care for, stop and then commit it
	docker commit e198aac7112d export/server1
	docker commit a312312fddde export/server2

Then, we saved each image to a tar archive using the `docker save` command. Beware that docker save streams the tarred and gzipped output to stdout so you better redirect it into a file like so:

	docker save export/server1 > export_server1.tar.gz
	docker save export/server2 > export_server2.tar.gz

This gives you loadable copies of each of your important images. Alternatively, you could also export the container using export and import but I had less success with this: import failed to load a 1500MB export (I killed it after 15 hours of "importing"). Your milage may vary.

2) Switching storage backends
-----------------------------

On ubuntu, this is simple. You want to add an argument to the docker deamon when it's launched on system startup. Storage selection is done using the `--storage-driver=x` flag. AUFS seems to be the default so I changed `/etc/default/docker` to enable device mapper:

	# Use DOCKER_OPTS to modify the daemon startup options.
	DOCKER_OPTS="--storage-driver=devicemapper"

and restarted docker. With this, all containers and images should be gone (as there are none in devicemapper storage, if you removed the command line options, you'd see everything again). Now we import the original images like this:

	docker load < export_server1.tar.gz
	docker load < export_server2.tar.gz

This should actually allow you to start each image just like before except that you are running using the device mapper backend now. Of course, once you are confident that everything works as expected, you can get rid of the original images and containers stored in AUFS.


text:
This recipe builds Chinese Mandarin systems with the HKUST Mandarin Telephone Speech corpus.

You need to obtain the following 2 LDC datasets:

LDC2005S15 : http://www.ldc.upenn.edu/Catalog/catalogEntry.jsp?catalogId=LDC2005S15

LDC2005T32 : http://www.ldc.upenn.edu/Catalog/catalogEntry.jsp?catalogId=LDC2005T32

The recipe run_ctc_char.sh models **3600+ Mandarin characters** directly. Dictionaries are not required.


text:
package com.github.Dimmer2222.DLIB.exceptions;

/**
 * Will be thrown if in the Config is not set the path
 */

public class ConfigSetException extends CoreException{
}


text:
class Gradle < Formula
  desc "Open-source build automation tool based on the Groovy and Kotlin DSL"
  homepage "https://www.gradle.org/"
  url "https://services.gradle.org/distributions/gradle-5.0-all.zip"
  sha256 "17847c8e12b2bcfce26a79f425f082c31d4ded822f99a66127eee2d96bf18216"

  bottle :unneeded

  option "with-all", "Installs Javadoc, examples, and source in addition to the binaries"

  depends_on :java => "1.7+"

  def install
    rm_f Dir["bin/*.bat"]
    libexec.install %w[bin lib]
    libexec.install %w[docs media samples src] if build.with? "all"
    (bin/"gradle").write_env_script libexec/"bin/gradle", Language::Java.overridable_java_home_env
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/gradle --version")
  end
end


text:
package com.skuehnel.dbvisualizer.report;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Factory for different implementations of the report generator
 */
public class ReportGeneratorFactory {
    public static ReportGenerator createReportGeneratorInstance(String format) {
        ReportGenerator reportGenerator;
        switch (format) {
            case "HTML":
                reportGenerator = new HTMLReportGenerator();
                break;
            case "PDF":
                reportGenerator = new PDFReportGenerator();
                break;
            case "MARKDOWN":
                reportGenerator = new MarkdownReportGenerator();
                break;
            default:
                throw new RuntimeException("Unsupported Format");
        }
        return reportGenerator;
    }
}


text:
package com.aspose.words.cloud.bookmarks;

import java.nio.file.Path;

import com.aspose.storage.api.StorageApi;
import com.aspose.words.api.WordsApi;
import com.aspose.words.cloud.config.Configuration;
import com.aspose.words.cloud.config.Utils;
import com.aspose.words.model.BookmarkResponse;

public class ReadingBookmarkExample {

	public static void main(String[] args) {
		// ExStart: ReadingBookmarkExample
		try {
			// Instantiate Aspose Storage API SDK
			StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);

			// Instantiate Aspose Words API SDK
			WordsApi wordsApi = new WordsApi(Configuration.apiKey, Configuration.appSID, true);

			// set input file name
			String fileName = "SampleWordDocument.docx";
			String bookmarkName = "_Toc76372689";
			String storage = null;
			String folder = null;

			Path path=Utils.getPath(ReadingBookmarkExample.class, fileName);

			// upload input file to aspose cloud storage
			storageApi.PutCreate(fileName, "", "",
			      path.toFile());

			// invoke Aspose.Words Cloud SDK API to get the bookmark by given
			// name from a word document
			BookmarkResponse apiResponse = wordsApi.GetDocumentBookmarkByName(fileName, bookmarkName, storage, folder);

			if (apiResponse != null && apiResponse.getStatus().equals("OK")) {

				if (apiResponse.getBookmark() != null) {
					// display bookmark info
					System.out.println("Name: " + apiResponse.getBookmark().getName() + " Text: "
							+ apiResponse.getBookmark().getText() + " link: "
							+ apiResponse.getBookmark().getLink().getHref());
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		// ExEnd: ReadingBookmarkExample

	}

}


text:
package org.apache.river.test.spec.eventmailbox;

import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.rmi.ServerException;

import java.util.logging.Level;
import net.jini.core.event.EventRegistration;
import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.lease.Lease;
import net.jini.event.MailboxPullRegistration;
import net.jini.event.PullEventMailbox;
import net.jini.io.MarshalledInstance;
import org.apache.river.constants.TimeConstants;
import org.apache.river.qa.harness.QAConfig;
import org.apache.river.qa.harness.Test;
import org.apache.river.test.impl.mercury.EMSTestBase;
import org.apache.river.test.impl.mercury.TestGenerator;
import org.apache.river.test.impl.mercury.TestPullListener;
import org.apache.river.test.impl.mercury.TestPullListenerImpl;
import org.apache.river.test.impl.mercury.TestUtils;

public class EMSST_PULL extends EMSTestBase implements TimeConstants {

    //
    // This should be long enough to sensibly run the test.
    // If the service doesn't grant long enough leases, then
    // we might have to resort to using something like the
    // LeaseRenewalManager to keep our leases current.
    //
    private final long DURATION1 = 3*HOURS;

    private final int NUM_EVENTS = 5;

    private final long EVENT_ID = 1234;

    private final long MAX_WAIT = 60 * 1000;

    public void run() throws Exception {
	PullEventMailbox mb = getPullMailbox();
	int i = 0;

	// Register and check lease
	MailboxPullRegistration mr = getPullRegistration(mb, DURATION1);
	Lease mrl = getPullMailboxLease(mr);
	checkLease(mrl, DURATION1);

	// Create "listener" to collect events for this test
	TestPullListener tpl = TestUtils.createPullListener(getManager());

	logger.log(Level.INFO, "Getting pull mailbox listener");
	RemoteEventListener mbRel = getPullMailboxListener(mr);

	// Create an event generator and pass it the
	// mailbox's remote event listener.
	TestGenerator myGen = TestUtils.createGenerator(getManager());
	EventRegistration evtReg =
	    myGen.register(EVENT_ID,	// Event ID to use
			   null,		// handback
			   mbRel,		// Notification target
			   DURATION1);	// Lease duration
	Lease tgl = evtReg.getLease();
	checkLease(tgl, DURATION1);

	int goodCount = 0;

	// Generate some events
	logger.log(Level.INFO, "Generating " + NUM_EVENTS + " events");
	RemoteEvent[] events = new RemoteEvent[NUM_EVENTS];
	for (i = 0; i < NUM_EVENTS; i++) {
	    events[i] = myGen.generateEvent(evtReg.getID(), 3);
	}

	RemoteEvent[] bogus = {
	    new RemoteEvent(myGen, 9999, 9999, (MarshalledInstance) null),
	    new RemoteEvent(myGen, 5678, 1234, (MarshalledInstance) null),
	};

	//
	// Kill event mailbox service
	//
	shutdown(0);

	goodCount = NUM_EVENTS;
	logger.log(Level.INFO, "Getting events");
	getCollectedRemoteEvents(tpl, mr, goodCount, MAX_WAIT);
	logger.log(Level.INFO, "Verifying event delivery");
	assertCount(tpl, goodCount);
	logger.log(Level.INFO, "Verifying events");
	assertEvents(tpl, events);

	logger.log(Level.INFO, "Generating another event");
	RemoteEvent re = myGen.generateEvent(evtReg.getID(), 3);
	goodCount++;
	getCollectedRemoteEvents(tpl, mr, goodCount, MAX_WAIT);
	logger.log(Level.INFO, "Verifying event delivery");
	assertCount(tpl, goodCount);
	logger.log(Level.INFO, "Verifying events");
	assertEvent(tpl, re);

    }

    /**
     * Invoke parent's construct and parser
     * @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has not yet begun.
     */
    public Test construct(QAConfig config) throws Exception {
	super.construct(config);
	parse();
        return this;
    }
}


text:
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::db_metadata::DbMetadataSchema;
use crate::pruner::state_store::generics::StaleNodeIndexSchemaTrait;
use crate::schema::db_metadata::DbMetadataValue;
use crate::{
    jellyfish_merkle_node::JellyfishMerkleNodeSchema, metrics::PRUNER_LEAST_READABLE_VERSION,
    pruner::db_pruner::DBPruner, pruner_utils, StaleNodeIndexCrossEpochSchema,
    OTHER_TIMERS_SECONDS,
};
use anyhow::Result;
use aptos_infallible::Mutex;
use aptos_jellyfish_merkle::node_type::NodeKey;
use aptos_jellyfish_merkle::StaleNodeIndex;
use aptos_logger::error;
use aptos_types::transaction::{AtomicVersion, Version};
use schemadb::schema::KeyCodec;
use schemadb::{ReadOptions, SchemaBatch, DB};
use std::sync::{atomic::Ordering, Arc};

pub mod generics;
pub(crate) mod state_value_pruner;

#[cfg(test)]
mod test;

pub const STATE_MERKLE_PRUNER_NAME: &str = "state_merkle_pruner";

/// Responsible for pruning the state tree.
#[derive(Debug)]
pub struct StateMerklePruner<S> {
    /// State DB.
    state_merkle_db: Arc<DB>,
    /// Keeps track of the target version that the pruner needs to achieve.
    target_version: AtomicVersion,
    /// 1. min readable version
    /// 2. if things before that version fully cleaned
    progress: Mutex<(Version, bool)>,
    _phantom: std::marker::PhantomData<S>,
}

impl<S: StaleNodeIndexSchemaTrait> DBPruner for StateMerklePruner<S>
where
    StaleNodeIndex: KeyCodec<S>,
{
    fn name(&self) -> &'static str {
        STATE_MERKLE_PRUNER_NAME
    }

    fn prune(&self, batch_size: usize) -> Result<Version> {
        if !self.is_pruning_pending() {
            return Ok(self.min_readable_version());
        }
        let min_readable_version = self.min_readable_version();
        let target_version = self.target_version();

        match self.prune_state_merkle(min_readable_version, target_version, batch_size, None) {
            Ok(new_min_readable_version) => Ok(new_min_readable_version),
            Err(e) => {
                error!(
                    error = ?e,
                    "Error pruning stale states.",
                );
                Err(e)
                // On error, stop retrying vigorously by making next recv() blocking.
            }
        }
    }

    fn initialize_min_readable_version(&self) -> Result<Version> {
        Ok(self
            .state_merkle_db
            .get::<DbMetadataSchema>(&S::tag())?
            .map_or(0, |v| v.expect_version()))
    }

    fn min_readable_version(&self) -> Version {
        let (version, _) = *self.progress.lock();
        version
    }

    fn set_target_version(&self, target_version: Version) {
        self.target_version.store(target_version, Ordering::Relaxed);
    }

    fn target_version(&self) -> Version {
        self.target_version.load(Ordering::Relaxed)
    }

    // used only by blanket `initialize()`, use the underlying implementation instead elsewhere.
    fn record_progress(&self, min_readable_version: Version) {
        self.record_progress_impl(min_readable_version, false /* is_fully_pruned */);
    }

    fn is_pruning_pending(&self) -> bool {
        let (min_readable_version, fully_pruned) = *self.progress.lock();
        self.target_version() > min_readable_version || !fully_pruned
    }

    /// (For tests only.) Updates the minimal readable version kept by pruner.
    fn testonly_update_min_version(&self, version: Version) {
        self.record_progress_impl(version, true /* is_fully_pruned */);
    }
}

impl<S: StaleNodeIndexSchemaTrait> StateMerklePruner<S>
where
    StaleNodeIndex: KeyCodec<S>,
{
    pub fn new(state_merkle_db: Arc<DB>) -> Self {
        let pruner = StateMerklePruner {
            state_merkle_db,
            target_version: AtomicVersion::new(0),
            progress: Mutex::new((0, true)),
            _phantom: std::marker::PhantomData,
        };
        pruner.initialize();
        pruner
    }

    // If the existing schema batch is not none, this function only adds items need to be
    // deleted to the schema batch and the caller is responsible for committing the schema batches
    // to the DB.
    pub fn prune_state_merkle(
        &self,
        min_readable_version: Version,
        target_version: Version,
        batch_size: usize,
        existing_schema_batch: Option<&mut SchemaBatch>,
    ) -> anyhow::Result<Version> {
        assert_ne!(batch_size, 0);
        let (indices, is_end_of_target_version) =
            self.get_stale_node_indices(min_readable_version, target_version, batch_size)?;
        if indices.is_empty() {
            self.record_progress_impl(target_version, is_end_of_target_version);
            Ok(target_version)
        } else {
            let _timer = OTHER_TIMERS_SECONDS
                .with_label_values(&["state_pruner_commit"])
                .start_timer();
            let new_min_readable_version =
                indices.last().expect("Should exist.").stale_since_version;

            // Delete stale nodes.
            if let Some(existing_schema_batch) = existing_schema_batch {
                indices.into_iter().try_for_each(|index| {
                    existing_schema_batch.delete::<JellyfishMerkleNodeSchema>(&index.node_key)?;
                    existing_schema_batch.delete::<S>(&index)
                })?;
            } else {
                let batch = SchemaBatch::new();
                indices.into_iter().try_for_each(|index| {
                    batch.delete::<JellyfishMerkleNodeSchema>(&index.node_key)?;
                    batch.delete::<S>(&index)
                })?;

                batch.put::<DbMetadataSchema>(
                    &S::tag(),
                    &DbMetadataValue::Version(new_min_readable_version),
                )?;

                // Commit to DB.
                self.state_merkle_db.write_schemas(batch)?;
            }

            // TODO(zcc): recording progress after writing schemas might provide wrong answers to
            // API calls when they query min_readable_version while the write_schemas are still in
            // progress.
            self.record_progress_impl(new_min_readable_version, is_end_of_target_version);
            Ok(new_min_readable_version)
        }
    }

    fn record_progress_impl(&self, min_readable_version: Version, is_fully_pruned: bool) {
        *self.progress.lock() = (min_readable_version, is_fully_pruned);
        PRUNER_LEAST_READABLE_VERSION
            .with_label_values(&[S::name()])
            .set(min_readable_version as i64);
    }

    fn get_stale_node_indices(
        &self,
        start_version: Version,
        target_version: Version,
        batch_size: usize,
    ) -> Result<(Vec<StaleNodeIndex>, bool)> {
        let mut indices = Vec::new();
        let mut iter = self.state_merkle_db.iter::<S>(ReadOptions::default())?;
        iter.seek(&StaleNodeIndex {
            stale_since_version: start_version,
            node_key: NodeKey::new_empty_path(0),
        })?;

        // over fetch by 1
        for _ in 0..=batch_size {
            if let Some((index, _)) = iter.next().transpose()? {
                if index.stale_since_version <= target_version {
                    indices.push(index);
                    continue;
                }
            }
            break;
        }

        let is_end_of_target_version = if indices.len() > batch_size {
            indices.pop();
            false
        } else {
            true
        };
        Ok((indices, is_end_of_target_version))
    }
}

impl StateMerklePruner<StaleNodeIndexCrossEpochSchema> {
    /// Prunes the genesis state and saves the db alterations to the given change set
    pub fn prune_genesis(state_merkle_db: Arc<DB>, batch: &mut SchemaBatch) -> Result<()> {
        let target_version = 1; // The genesis version is 0. Delete [0,1) (exclusive)
        let max_version = 1; // We should only be pruning a single version

        let state_pruner =
            pruner_utils::create_state_pruner::<StaleNodeIndexCrossEpochSchema>(state_merkle_db);
        state_pruner.set_target_version(target_version);

        let min_readable_version = state_pruner.min_readable_version();
        let target_version = state_pruner.target_version();
        state_pruner.prune_state_merkle(
            min_readable_version,
            target_version,
            max_version,
            Some(batch),
        )?;

        Ok(())
    }
}


text:
SET client_encoding TO 'UTF8';

CREATE OR REPLACE FUNCTION ag_log_participant_sample (
    barcode_ text,
    sample_site_ text,
    environment_sampled_ text,
    sample_date_ text,
    sample_time_ text,
    participant_name_ text,
    notes_ text
)
 RETURNS VOID AS $body$
BEGIN

    update  ag_kit_barcodes
    set     site_sampled = sample_site_,
            environment_sampled = environment_sampled_,
            sample_date = sample_date_,
            sample_time = sample_time_,
            participant_name = participant_name_,
            notes = notes_
    where   barcode = barcode_;
end;
/*
begin;
select ag_log_participant_sample('000010860', 'Stool', '', '07/29/2014', '09:30 AM', 'Emily', 'no notes');
select * from ag_kit_barcodes where barcode = ('000010860');
select ag_delete_sample ('000010860', cast('d8592c747da12135e0408a80115d6401' as uuid));
select * from ag_kit_barcodes where barcode = '000010860';
commit;
*/

$body$
LANGUAGE PLPGSQL;


text:
class CanningSessionsController < ApplicationController
    load_and_authorize_resource
  # GET /canning_sessions
  # GET /canning_sessions.json
  def index
    @canning_sessions = CanningSession.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @canning_sessions }
    end
  end

  # GET /canning_sessions/1
  # GET /canning_sessions/1.json
  def show
    @canning_session = CanningSession.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @canning_session }
    end
  end

  # GET /canning_sessions/new
  # GET /canning_sessions/new.json
  def new
    @canning_session = CanningSession.new
    @canning_session.harvest_id = params[:harvest_id]

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @canning_session }
    end
  end

  # GET /canning_sessions/1/edit
  def edit
    @canning_session = CanningSession.find(params[:id])
  end

  # POST /canning_sessions
  # POST /canning_sessions.json
  def create
    @canning_session = CanningSession.new(params[:canning_session])

    respond_to do |format|
      if @canning_session.save
        format.html { redirect_to @canning_session, notice: 'Canning session was successfully created.' }
        format.json { render json: @canning_session, status: :created, location: @canning_session }
      else
        format.html { render action: "new" }
        format.json { render json: @canning_session.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /canning_sessions/1
  # PUT /canning_sessions/1.json
  def update
    @canning_session = CanningSession.find(params[:id])

    respond_to do |format|
      if @canning_session.update_attributes(params[:canning_session])
        format.html { redirect_to @canning_session, notice: 'Canning session was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @canning_session.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /canning_sessions/1
  # DELETE /canning_sessions/1.json
  def destroy
    @canning_session = CanningSession.find(params[:id])
    @canning_session.destroy

    respond_to do |format|
      format.html { redirect_to canning_sessions_url }
      format.json { head :no_content }
    end
  end
end


text:
using System;

namespace MyApp.Domain.Users
{
    [Flags]
    public enum Role
    {
        None = 0,
        Administrator = 1,
        Contributor = 2
    }
}


text:
/* eslint jsx-quotes: ["error", "prefer-double"] */

import React from 'react'
import Reflux from 'reflux'

import Store from './../Store'

import FontAwesome from 'react-fontawesome'

const iconType = {
  'question-choices': 'question-circle',
  'question-number': 'sort-numeric-asc',
  'content-message': 'comments'
}

class ProjectAction extends Reflux.Component {
  constructor (props) {
    super(props)
    this.store = Store
    this.handleCreateAction = (e) => {
      this.props.handleCreateAction(e, this.props.index)
    }
    this.handleEditAction = (e) => {
      this.props.handleEditAction(e, this.props.index)
    }
    this.handlerChangeName = (e) => {
      this.props.data.name = e.target.value
    }
  }
  render () {
    return (

        <FontAwesome className="float-left text dark-blue" fixedWidth width={68} size="4x" style={{opacity: '0.75', position: 'fixed', marginTop: '-8px'}} name={iconType[this.props.data.type]} />

          <input type="text" className="no-border smaller" defaultValue={this.props.data.name} onChange={this.handlerChangeName} />
          <FontAwesome className="text dark-blue" size="2x" name="pencil-square" />

        <FontAwesome className="text dark-blue" size="2x" name="plus-circle" />

    )
  }
}

export default ProjectAction


text:
/**
 * In CLDR, there are some special locales with abnormal hierarchy.
 *
 * E.g.zh-hk.xml is aliased to zh-hant-hk.xml for all the calendar/number/currency data.
 * So after CLDR transformation, JSON bundles under zh-hk is totally the same as those under zh-hant-hk.
 * Problems will occur when dojo loads zh-hk bundle, as dojo will flatten it with the following sequence:
 * Root -> zh -> zh-hk, but the right sequence should be Root -> zh -> zh-hant -> zh-hk(zh-hant-hk)
 * so the bundles under zh-hant locale is missing.
 *
 * This script is used to process all the special locales so that after CLDR transformation,
 * zh-hk bundle will be flatted both with zh-hant and zh-hant-hk, nothing will be lost then.
 * Please see the following SPECIAL_LOCALES_MAP for detail mapping info.
 *
 * Note: Here for simplification, we name zh-hk as source locale,and name zh-hant-hk as alias locale.
 */
djConfig={baseUrl: "../../../dojo/"};

load("../../../dojo/dojo.js");
load("../jslib/logger.js");
load("../jslib/fileUtil.js");
load("cldrUtil.js");

dojo.require("dojo.i18n");

var dir/*String*/ = arguments[0];// ${dojo}/dojo/cldr/nls

//locales that are generated by ${dojo}/util/buildscripts/cldr/build.xml
var allLocalesStr/*String*/ = arguments[1];//e.g. "ar,ar-eg,en-au,en-ca,en-gb,en-us,de-de,es-es,fr-fr,..."

var logDir = arguments[2];

//related bundles, currently only 'number','currency','gregorian' bundles
//TBD - 'buddhist','chinese','coptic','currency','ethiopic','gregorian','hebrew','islamic','islamic-civil','japanese','persian'
var BUNDLE_MAP = ['number','currency','gregorian'];

//headers for generated bundle files
var NLS_JSON_HEAD = ['// generated from ldml/main/*.xml, xpath: ldml/numbers\n',
				 	 '// generated from ldml/main/*.xml, xpath: ldml/numbers/currencies\n',
				     '// generated from ldml/main/*.xml, xpath: ldml/calendars/calendar-gregorian\n'];

var SPECIAL_LOCALES_MAP = {
	//Mapping info for some special locales with abnormal hierarchy.
	//Currently for CLDR 1.6, will be updated with latest CLDR release.

	'zh-hk':'zh-hant-hk',
	'zh-mo':'zh-hant-mo',
	'sh':'sr-latn',
	'mo':'ro-md',
	'pa-pk':'pa-arab-pk',//pa-pk and pa-arab-pk don't exist, but pa-arab exists
	'zh-tw':'zh-hant-tw',//zh-tw and zh-hant-tw don't exist, but zh-hant exists
	'uz-af':'uz-arab-af',//uz-af and uz-arab-af don't exist, but uz-arab exists
	'ha-sd':'ha-arab-sd',//ha-sd and ha-arab-sd don't exist, but ha-arab exists
	'ku-tr':'ku-latn-tr' //ku-tr and ku-latn-tr don't exist, but ku-latn exists

	/* The following locales don't have any bundles currently (CLDR 1.6),
	 * listed here for CLDR future release.
	 *
	'az-az':'az-latn-az',
	'ha-gh':'ha-latn-gh',
	'ha-ne':'ha-latn-ne',
	'ha-ng':'ha-latn-ng',
	'kk-kz':'kk-cyrl-kz',
	'ku-iq':'ku-latn-iq',
	'ku-ir':'ku-latn-ir',
	'ku-sy':'ku-latn-sy',
	'pa-in':'pa-guru-in',
	'sr-cs':'sr-cyrl-cs',
	'sr-me':'sr-cyrl-me',
	'sr-rs':'sr-cyrl-rs',
	'sr-yu':'sr-cyrl-rs',
	'uz-uz':'uz-cyrl-uz',
	'zh-sg':'zh-hans-sg',
	'zh-cn':'zh-hans-cn',
	'mn-cn':'mn-mong-cn',
	'mn-mn':'mn-cyrl-cn',
	'pa-in':'pa-guru-in',

	*/

	/* Don't need to process the following locale alias
	 * only listed here for futher comparison
	 *
	//sh is already aliased to sr-latn
	'sh-cs':'sr-latn-rs',
	'sh-yu':'sr-latn-rs',
	'sh-ba':'sr-latn-ba',//sh-ba and sr-latn-ba don't exist, but sr-latn exists

	//has the same parent
	'sr-cyrl-cs':'sr-cyrl-rs',
	'sr-cyrl-yu':'sr-cyrl-rs',

	'sr-cs':'sr-cyrl-cs',
	'sr-me':'sr-cyrl-me',
	'sr-rs':'sr-cyrl-rs',
	'sr-yu':'sr-cyrl-rs',
	'sr-ba':'sr-cyrl-ba',//sr-cyrl is null
	'tg-tj':'tg-cyrl-tj',//tg-cyrl is null
	'ug-cn':'ug-arab-cn',//ug-arab is null
	'uz-uz':'uz-cyrl-uz',//uz-cyrl is null
	'zh-cn':'zh-hans-cn',//zh-hans is null
	'zh-sg':'zh-hans-sg',//zh-hans is null
	*/
};

print('specialLocale.js...');

var srcLocaleList = [];//source locale file paths
for(x in SPECIAL_LOCALES_MAP){
	if(allLocalesStr == '${locales}' //no $locales parameter,all locales required
	   || (allLocalesStr && 0 <= allLocalesStr.indexOf(x))){
		//only if this locale is required
		srcLocaleList.push(dir + '/' + x);
	}
}

/*
 * Get and compare the flattened bundles(using dojo.i18n) of each source locale and its alias
 * Copy those bundles that alias has but source locale doesn't to source locale,
 * and also update new items in source locale bundle
 */
var logStr = "";
for(var i= 0; i < srcLocaleList.length; i++){
	var srcLocalePath = srcLocaleList[i];//source locale path
	var srcPathSegments = srcLocalePath.split("/");
	var srcLocale = srcPathSegments[srcPathSegments.length - 1];
	var aliasLocale = SPECIAL_LOCALES_MAP[srcLocale];

	//iterate each bundle
	for(var len = 0; len < BUNDLE_MAP.length; len++){
		try{
			//declare bundles
			dojo.i18n._requireLocalization('dojo.cldr', BUNDLE_MAP[len], srcLocale);
			dojo.i18n._requireLocalization('dojo.cldr', BUNDLE_MAP[len], aliasLocale);

			//get bundles
			var srcBundle = dojo.i18n.getLocalization('dojo.cldr', BUNDLE_MAP[len], srcLocale);
			var aliasBundle = dojo.i18n.getLocalization('dojo.cldr', BUNDLE_MAP[len], aliasLocale);
		}catch(e){print(e);/*it's ok if no bundle found*/}

		if(!aliasBundle && !srcBundle){
			break;
		}else if(!aliasBundle && srcBundle){
			//should be an error case
			//logStr += 'specialLocale.js error: source locale has more bundles than alias locale\n';
			break;
		}else if(aliasBundle && !srcBundle){
			//add the new bundle to source locale
			validateDir(srcLocalePath);
			fileUtil.saveUtf8File(srcLocalePath + '/' + BUNDLE_MAP[len] + '.js', NLS_JSON_HEAD[len] + '(' + dojo.toJson(aliasBundle, true) + ')');
			//logStr += "specialLocale.js : copied " + BUNDLE_MAP[len] + '.js to ' + srcLocalePath + '\n';
		}else if(aliasBundle && srcBundle){
			var isUpdated = false;
			//get native bundle whose content is not flattened
			try{
				var nativeSrcBundle = getNativeBundle(srcLocalePath + '/' + BUNDLE_MAP[len] + '.js');
			}catch(e){
				//if no nativeSrcBundle
				nativeSrcBundle = {};
			}

			for(p in aliasBundle){
				if(!isLocaleAliasSrc(p, aliasBundle) // p is not the source of a 'locale' alias mapping
				   && (!srcBundle[p] || !compare(srcBundle[p], aliasBundle[p]))){
				   //inherit
				   nativeSrcBundle[p] = aliasBundle[p];
				   //logStr += "copied " + p + "=" + aliasBundle[p] + "\n";
				   isUpdated = true;
				}
			}

			if(isUpdated){
				validateDir(srcLocalePath);
				fileUtil.saveUtf8File(srcLocalePath + '/' + BUNDLE_MAP[len] + '.js', NLS_JSON_HEAD[len] + '(' + dojo.toJson(nativeSrcBundle, true) + ')');
				//logStr += 'specialLocale.js : updated ' + BUNDLE_MAP[len] + '.js in ' + srcLocalePath + '\n';
			}
		}
	}
}

//fileUtil.saveUtf8File(logDir + '/specialLocale.log',logStr+'\n');

function validateDir(/*String*/dirPath){
	//summary:make sure the dir exists
	var dir = new java.io.File(dirPath);
	if(!dir.exists()){
		dir.mkdir();
	}
}


text:
require 'spec_helper'

module Piemap
  describe Tweet do
     it "should downloads tweets" do
       Tweet.send(:get_json).is_a?(Hash).should be_true
     end

     describe "with test data" do
       before :each do
         data = File.read File.expand_path("../../../twitter_data.json", __FILE__)
         Net::HTTP.stub(:get).and_return(data)
       end

       it "should still get data" do
         Tweet.send(:get_json).should == JSON.parse(File.read File.expand_path("../../../twitter_data.json", __FILE__))
       end

       it "should add tweets to database" do
         lambda {
           Tweet.get_latest
         }.should change(Tweet, :count).by(15)
       end
     end
  end
end


text:
from django.contrib import admin
from . import models

admin.site.register(models.AppNameTask)
admin.site.register(models.UserHistory)
admin.site.register(models.ToolInfo)
# TODO: Register any models that actually exist here.
admin.site.register(models.ResultType)
admin.site.register(models.AnimationType)


text:
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/mpage.h>

#include "hfsplus_fs.h"
#include "hfsplus_raw.h"

static int hfsplus_readpage(struct file *file, struct page *page)
{
	return block_read_full_page(page, hfsplus_get_block);
}

static int hfsplus_writepage(struct page *page, struct writeback_control *wbc)
{
	return block_write_full_page(page, hfsplus_get_block, wbc);
}

static int hfsplus_prepare_write(struct file *file, struct page *page, unsigned from, unsigned to)
{
	return cont_prepare_write(page, from, to, hfsplus_get_block,
		&HFSPLUS_I(page->mapping->host).phys_size);
}

static sector_t hfsplus_bmap(struct address_space *mapping, sector_t block)
{
	return generic_block_bmap(mapping, block, hfsplus_get_block);
}

static int hfsplus_releasepage(struct page *page, gfp_t mask)
{
	struct inode *inode = page->mapping->host;
	struct super_block *sb = inode->i_sb;
	struct hfs_btree *tree;
	struct hfs_bnode *node;
	u32 nidx;
	int i, res = 1;

	switch (inode->i_ino) {
	case HFSPLUS_EXT_CNID:
		tree = HFSPLUS_SB(sb).ext_tree;
		break;
	case HFSPLUS_CAT_CNID:
		tree = HFSPLUS_SB(sb).cat_tree;
		break;
	case HFSPLUS_ATTR_CNID:
		tree = HFSPLUS_SB(sb).attr_tree;
		break;
	default:
		BUG();
		return 0;
	}
	if (tree->node_size >= PAGE_CACHE_SIZE) {
		nidx = page->index >> (tree->node_size_shift - PAGE_CACHE_SHIFT);
		spin_lock(&tree->hash_lock);
		node = hfs_bnode_findhash(tree, nidx);
		if (!node)
			;
		else if (atomic_read(&node->refcnt))
			res = 0;
		if (res && node) {
			hfs_bnode_unhash(node);
			hfs_bnode_free(node);
		}
		spin_unlock(&tree->hash_lock);
	} else {
		nidx = page->index << (PAGE_CACHE_SHIFT - tree->node_size_shift);
		i = 1 << (PAGE_CACHE_SHIFT - tree->node_size_shift);
		spin_lock(&tree->hash_lock);
		do {
			node = hfs_bnode_findhash(tree, nidx++);
			if (!node)
				continue;
			if (atomic_read(&node->refcnt)) {
				res = 0;
				break;
			}
			hfs_bnode_unhash(node);
			hfs_bnode_free(node);
		} while (--i && nidx < tree->node_count);
		spin_unlock(&tree->hash_lock);
	}
	return res ? try_to_free_buffers(page) : 0;
}

static int hfsplus_get_blocks(struct inode *inode, sector_t iblock, unsigned long max_blocks,
			      struct buffer_head *bh_result, int create)
{
	int ret;

	ret = hfsplus_get_block(inode, iblock, bh_result, create);
	if (!ret)
		bh_result->b_size = (1 << inode->i_blkbits);
	return ret;
}

static ssize_t hfsplus_direct_IO(int rw, struct kiocb *iocb,
		const struct iovec *iov, loff_t offset, unsigned long nr_segs)
{
	struct file *file = iocb->ki_filp;
	struct inode *inode = file->f_dentry->d_inode->i_mapping->host;

	return blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
				  offset, nr_segs, hfsplus_get_blocks, NULL);
}

static int hfsplus_writepages(struct address_space *mapping,
			      struct writeback_control *wbc)
{
	return mpage_writepages(mapping, wbc, hfsplus_get_block);
}

struct address_space_operations hfsplus_btree_aops = {
	.readpage	= hfsplus_readpage,
	.writepage	= hfsplus_writepage,
	.sync_page	= block_sync_page,
	.prepare_write	= hfsplus_prepare_write,
	.commit_write	= generic_commit_write,
	.bmap		= hfsplus_bmap,
	.releasepage	= hfsplus_releasepage,
};

struct address_space_operations hfsplus_aops = {
	.readpage	= hfsplus_readpage,
	.writepage	= hfsplus_writepage,
	.sync_page	= block_sync_page,
	.prepare_write	= hfsplus_prepare_write,
	.commit_write	= generic_commit_write,
	.bmap		= hfsplus_bmap,
	.direct_IO	= hfsplus_direct_IO,
	.writepages	= hfsplus_writepages,
};

static struct dentry *hfsplus_file_lookup(struct inode *dir, struct dentry *dentry,
					  struct nameidata *nd)
{
	struct hfs_find_data fd;
	struct super_block *sb = dir->i_sb;
	struct inode *inode = NULL;
	int err;

	if (HFSPLUS_IS_RSRC(dir) || strcmp(dentry->d_name.name, "rsrc"))
		goto out;

	inode = HFSPLUS_I(dir).rsrc_inode;
	if (inode)
		goto out;

	inode = new_inode(sb);
	if (!inode)
		return ERR_PTR(-ENOMEM);

	inode->i_ino = dir->i_ino;
	INIT_LIST_HEAD(&HFSPLUS_I(inode).open_dir_list);
	init_MUTEX(&HFSPLUS_I(inode).extents_lock);
	HFSPLUS_I(inode).flags = HFSPLUS_FLG_RSRC;

	hfs_find_init(HFSPLUS_SB(sb).cat_tree, &fd);
	err = hfsplus_find_cat(sb, dir->i_ino, &fd);
	if (!err)
		err = hfsplus_cat_read_inode(inode, &fd);
	hfs_find_exit(&fd);
	if (err) {
		iput(inode);
		return ERR_PTR(err);
	}
	HFSPLUS_I(inode).rsrc_inode = dir;
	HFSPLUS_I(dir).rsrc_inode = inode;
	igrab(dir);
	hlist_add_head(&inode->i_hash, &HFSPLUS_SB(sb).rsrc_inodes);
	mark_inode_dirty(inode);
out:
	d_add(dentry, inode);
	return NULL;
}

static void hfsplus_get_perms(struct inode *inode, struct hfsplus_perm *perms, int dir)
{
	struct super_block *sb = inode->i_sb;
	u16 mode;

	mode = be16_to_cpu(perms->mode);

	inode->i_uid = be32_to_cpu(perms->owner);
	if (!inode->i_uid && !mode)
		inode->i_uid = HFSPLUS_SB(sb).uid;

	inode->i_gid = be32_to_cpu(perms->group);
	if (!inode->i_gid && !mode)
		inode->i_gid = HFSPLUS_SB(sb).gid;

	if (dir) {
		mode = mode ? (mode & S_IALLUGO) :
			(S_IRWXUGO & ~(HFSPLUS_SB(sb).umask));
		mode |= S_IFDIR;
	} else if (!mode)
		mode = S_IFREG | ((S_IRUGO|S_IWUGO) &
			~(HFSPLUS_SB(sb).umask));
	inode->i_mode = mode;

	HFSPLUS_I(inode).rootflags = perms->rootflags;
	HFSPLUS_I(inode).userflags = perms->userflags;
	if (perms->rootflags & HFSPLUS_FLG_IMMUTABLE)
		inode->i_flags |= S_IMMUTABLE;
	else
		inode->i_flags &= ~S_IMMUTABLE;
	if (perms->rootflags & HFSPLUS_FLG_APPEND)
		inode->i_flags |= S_APPEND;
	else
		inode->i_flags &= ~S_APPEND;
}

static void hfsplus_set_perms(struct inode *inode, struct hfsplus_perm *perms)
{
	if (inode->i_flags & S_IMMUTABLE)
		perms->rootflags |= HFSPLUS_FLG_IMMUTABLE;
	else
		perms->rootflags &= ~HFSPLUS_FLG_IMMUTABLE;
	if (inode->i_flags & S_APPEND)
		perms->rootflags |= HFSPLUS_FLG_APPEND;
	else
		perms->rootflags &= ~HFSPLUS_FLG_APPEND;
	perms->userflags = HFSPLUS_I(inode).userflags;
	perms->mode = cpu_to_be16(inode->i_mode);
	perms->owner = cpu_to_be32(inode->i_uid);
	perms->group = cpu_to_be32(inode->i_gid);
	perms->dev = cpu_to_be32(HFSPLUS_I(inode).dev);
}

static int hfsplus_permission(struct inode *inode, int mask, struct nameidata *nd)
{
	/* MAY_EXEC is also used for lookup, if no x bit is set allow lookup,
	 * open_exec has the same test, so it's still not executable, if a x bit
	 * is set fall back to standard permission check.
	 */
	if (S_ISREG(inode->i_mode) && mask & MAY_EXEC && !(inode->i_mode & 0111))
		return 0;
	return generic_permission(inode, mask, NULL);
}

static int hfsplus_file_open(struct inode *inode, struct file *file)
{
	if (HFSPLUS_IS_RSRC(inode))
		inode = HFSPLUS_I(inode).rsrc_inode;
	if (atomic_read(&file->f_count) != 1)
		return 0;
	atomic_inc(&HFSPLUS_I(inode).opencnt);
	return 0;
}

static int hfsplus_file_release(struct inode *inode, struct file *file)
{
	struct super_block *sb = inode->i_sb;

	if (HFSPLUS_IS_RSRC(inode))
		inode = HFSPLUS_I(inode).rsrc_inode;
	if (atomic_read(&file->f_count) != 0)
		return 0;
	if (atomic_dec_and_test(&HFSPLUS_I(inode).opencnt)) {
		mutex_lock(&inode->i_mutex);
		hfsplus_file_truncate(inode);
		if (inode->i_flags & S_DEAD) {
			hfsplus_delete_cat(inode->i_ino, HFSPLUS_SB(sb).hidden_dir, NULL);
			hfsplus_delete_inode(inode);
		}
		mutex_unlock(&inode->i_mutex);
	}
	return 0;
}

extern struct inode_operations hfsplus_dir_inode_operations;
extern struct file_operations hfsplus_dir_operations;

static struct inode_operations hfsplus_file_inode_operations = {
	.lookup		= hfsplus_file_lookup,
	.truncate	= hfsplus_file_truncate,
	.permission	= hfsplus_permission,
	.setxattr	= hfsplus_setxattr,
	.getxattr	= hfsplus_getxattr,
	.listxattr	= hfsplus_listxattr,
};

static struct file_operations hfsplus_file_operations = {
	.llseek 	= generic_file_llseek,
	.read		= generic_file_read,
	.write		= generic_file_write,
	.mmap		= generic_file_mmap,
	.sendfile	= generic_file_sendfile,
	.fsync		= file_fsync,
	.open		= hfsplus_file_open,
	.release	= hfsplus_file_release,
	.ioctl          = hfsplus_ioctl,
};

struct inode *hfsplus_new_inode(struct super_block *sb, int mode)
{
	struct inode *inode = new_inode(sb);
	if (!inode)
		return NULL;

	inode->i_ino = HFSPLUS_SB(sb).next_cnid++;
	inode->i_mode = mode;
	inode->i_uid = current->fsuid;
	inode->i_gid = current->fsgid;
	inode->i_nlink = 1;
	inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
	inode->i_blksize = HFSPLUS_SB(sb).alloc_blksz;
	INIT_LIST_HEAD(&HFSPLUS_I(inode).open_dir_list);
	init_MUTEX(&HFSPLUS_I(inode).extents_lock);
	atomic_set(&HFSPLUS_I(inode).opencnt, 0);
	HFSPLUS_I(inode).flags = 0;
	memset(HFSPLUS_I(inode).first_extents, 0, sizeof(hfsplus_extent_rec));
	memset(HFSPLUS_I(inode).cached_extents, 0, sizeof(hfsplus_extent_rec));
	HFSPLUS_I(inode).alloc_blocks = 0;
	HFSPLUS_I(inode).first_blocks = 0;
	HFSPLUS_I(inode).cached_start = 0;
	HFSPLUS_I(inode).cached_blocks = 0;
	HFSPLUS_I(inode).phys_size = 0;
	HFSPLUS_I(inode).fs_blocks = 0;
	HFSPLUS_I(inode).rsrc_inode = NULL;
	if (S_ISDIR(inode->i_mode)) {
		inode->i_size = 2;
		HFSPLUS_SB(sb).folder_count++;
		inode->i_op = &hfsplus_dir_inode_operations;
		inode->i_fop = &hfsplus_dir_operations;
	} else if (S_ISREG(inode->i_mode)) {
		HFSPLUS_SB(sb).file_count++;
		inode->i_op = &hfsplus_file_inode_operations;
		inode->i_fop = &hfsplus_file_operations;
		inode->i_mapping->a_ops = &hfsplus_aops;
		HFSPLUS_I(inode).clump_blocks = HFSPLUS_SB(sb).data_clump_blocks;
	} else if (S_ISLNK(inode->i_mode)) {
		HFSPLUS_SB(sb).file_count++;
		inode->i_op = &page_symlink_inode_operations;
		inode->i_mapping->a_ops = &hfsplus_aops;
		HFSPLUS_I(inode).clump_blocks = 1;
	} else
		HFSPLUS_SB(sb).file_count++;
	insert_inode_hash(inode);
	mark_inode_dirty(inode);
	sb->s_dirt = 1;

	return inode;
}

void hfsplus_delete_inode(struct inode *inode)
{
	struct super_block *sb = inode->i_sb;

	if (S_ISDIR(inode->i_mode)) {
		HFSPLUS_SB(sb).folder_count--;
		sb->s_dirt = 1;
		return;
	}
	HFSPLUS_SB(sb).file_count--;
	if (S_ISREG(inode->i_mode)) {
		if (!inode->i_nlink) {
			inode->i_size = 0;
			hfsplus_file_truncate(inode);
		}
	} else if (S_ISLNK(inode->i_mode)) {
		inode->i_size = 0;
		hfsplus_file_truncate(inode);
	}
	sb->s_dirt = 1;
}

void hfsplus_inode_read_fork(struct inode *inode, struct hfsplus_fork_raw *fork)
{
	struct super_block *sb = inode->i_sb;
	u32 count;
	int i;

	memcpy(&HFSPLUS_I(inode).first_extents, &fork->extents,
	       sizeof(hfsplus_extent_rec));
	for (count = 0, i = 0; i < 8; i++)
		count += be32_to_cpu(fork->extents[i].block_count);
	HFSPLUS_I(inode).first_blocks = count;
	memset(HFSPLUS_I(inode).cached_extents, 0, sizeof(hfsplus_extent_rec));
	HFSPLUS_I(inode).cached_start = 0;
	HFSPLUS_I(inode).cached_blocks = 0;

	HFSPLUS_I(inode).alloc_blocks = be32_to_cpu(fork->total_blocks);
	inode->i_size = HFSPLUS_I(inode).phys_size = be64_to_cpu(fork->total_size);
	HFSPLUS_I(inode).fs_blocks = (inode->i_size + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
	inode_set_bytes(inode, HFSPLUS_I(inode).fs_blocks << sb->s_blocksize_bits);
	HFSPLUS_I(inode).clump_blocks = be32_to_cpu(fork->clump_size) >> HFSPLUS_SB(sb).alloc_blksz_shift;
	if (!HFSPLUS_I(inode).clump_blocks)
		HFSPLUS_I(inode).clump_blocks = HFSPLUS_IS_RSRC(inode) ? HFSPLUS_SB(sb).rsrc_clump_blocks :
				HFSPLUS_SB(sb).data_clump_blocks;
}

void hfsplus_inode_write_fork(struct inode *inode, struct hfsplus_fork_raw *fork)
{
	memcpy(&fork->extents, &HFSPLUS_I(inode).first_extents,
	       sizeof(hfsplus_extent_rec));
	fork->total_size = cpu_to_be64(inode->i_size);
	fork->total_blocks = cpu_to_be32(HFSPLUS_I(inode).alloc_blocks);
}

int hfsplus_cat_read_inode(struct inode *inode, struct hfs_find_data *fd)
{
	hfsplus_cat_entry entry;
	int res = 0;
	u16 type;

	type = hfs_bnode_read_u16(fd->bnode, fd->entryoffset);

	HFSPLUS_I(inode).dev = 0;
	inode->i_blksize = HFSPLUS_SB(inode->i_sb).alloc_blksz;
	if (type == HFSPLUS_FOLDER) {
		struct hfsplus_cat_folder *folder = &entry.folder;

		if (fd->entrylength < sizeof(struct hfsplus_cat_folder))
			/* panic? */;
		hfs_bnode_read(fd->bnode, &entry, fd->entryoffset,
					sizeof(struct hfsplus_cat_folder));
		hfsplus_get_perms(inode, &folder->permissions, 1);
		inode->i_nlink = 1;
		inode->i_size = 2 + be32_to_cpu(folder->valence);
		inode->i_atime = hfsp_mt2ut(folder->access_date);
		inode->i_mtime = hfsp_mt2ut(folder->content_mod_date);
		inode->i_ctime = hfsp_mt2ut(folder->attribute_mod_date);
		HFSPLUS_I(inode).create_date = folder->create_date;
		HFSPLUS_I(inode).fs_blocks = 0;
		inode->i_op = &hfsplus_dir_inode_operations;
		inode->i_fop = &hfsplus_dir_operations;
	} else if (type == HFSPLUS_FILE) {
		struct hfsplus_cat_file *file = &entry.file;

		if (fd->entrylength < sizeof(struct hfsplus_cat_file))
			/* panic? */;
		hfs_bnode_read(fd->bnode, &entry, fd->entryoffset,
					sizeof(struct hfsplus_cat_file));

		hfsplus_inode_read_fork(inode, HFSPLUS_IS_DATA(inode) ?
					&file->data_fork : &file->rsrc_fork);
		hfsplus_get_perms(inode, &file->permissions, 0);
		inode->i_nlink = 1;
		if (S_ISREG(inode->i_mode)) {
			if (file->permissions.dev)
				inode->i_nlink = be32_to_cpu(file->permissions.dev);
			inode->i_op = &hfsplus_file_inode_operations;
			inode->i_fop = &hfsplus_file_operations;
			inode->i_mapping->a_ops = &hfsplus_aops;
		} else if (S_ISLNK(inode->i_mode)) {
			inode->i_op = &page_symlink_inode_operations;
			inode->i_mapping->a_ops = &hfsplus_aops;
		} else {
			init_special_inode(inode, inode->i_mode,
					   be32_to_cpu(file->permissions.dev));
		}
		inode->i_atime = hfsp_mt2ut(file->access_date);
		inode->i_mtime = hfsp_mt2ut(file->content_mod_date);
		inode->i_ctime = hfsp_mt2ut(file->attribute_mod_date);
		HFSPLUS_I(inode).create_date = file->create_date;
	} else {
		printk(KERN_ERR "hfs: bad catalog entry used to create inode\n");
		res = -EIO;
	}
	return res;
}

int hfsplus_cat_write_inode(struct inode *inode)
{
	struct inode *main_inode = inode;
	struct hfs_find_data fd;
	hfsplus_cat_entry entry;

	if (HFSPLUS_IS_RSRC(inode))
		main_inode = HFSPLUS_I(inode).rsrc_inode;

	if (!main_inode->i_nlink)
		return 0;

	if (hfs_find_init(HFSPLUS_SB(main_inode->i_sb).cat_tree, &fd))
		/* panic? */
		return -EIO;

	if (hfsplus_find_cat(main_inode->i_sb, main_inode->i_ino, &fd))
		/* panic? */
		goto out;

	if (S_ISDIR(main_inode->i_mode)) {
		struct hfsplus_cat_folder *folder = &entry.folder;

		if (fd.entrylength < sizeof(struct hfsplus_cat_folder))
			/* panic? */;
		hfs_bnode_read(fd.bnode, &entry, fd.entryoffset,
					sizeof(struct hfsplus_cat_folder));
		/* simple node checks? */
		hfsplus_set_perms(inode, &folder->permissions);
		folder->access_date = hfsp_ut2mt(inode->i_atime);
		folder->content_mod_date = hfsp_ut2mt(inode->i_mtime);
		folder->attribute_mod_date = hfsp_ut2mt(inode->i_ctime);
		folder->valence = cpu_to_be32(inode->i_size - 2);
		hfs_bnode_write(fd.bnode, &entry, fd.entryoffset,
					 sizeof(struct hfsplus_cat_folder));
	} else if (HFSPLUS_IS_RSRC(inode)) {
		struct hfsplus_cat_file *file = &entry.file;
		hfs_bnode_read(fd.bnode, &entry, fd.entryoffset,
			       sizeof(struct hfsplus_cat_file));
		hfsplus_inode_write_fork(inode, &file->rsrc_fork);
		hfs_bnode_write(fd.bnode, &entry, fd.entryoffset,
				sizeof(struct hfsplus_cat_file));
	} else {
		struct hfsplus_cat_file *file = &entry.file;

		if (fd.entrylength < sizeof(struct hfsplus_cat_file))
			/* panic? */;
		hfs_bnode_read(fd.bnode, &entry, fd.entryoffset,
					sizeof(struct hfsplus_cat_file));
		hfsplus_inode_write_fork(inode, &file->data_fork);
		if (S_ISREG(inode->i_mode))
			HFSPLUS_I(inode).dev = inode->i_nlink;
		if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
			HFSPLUS_I(inode).dev = kdev_t_to_nr(inode->i_rdev);
		hfsplus_set_perms(inode, &file->permissions);
		if ((file->permissions.rootflags | file->permissions.userflags) & HFSPLUS_FLG_IMMUTABLE)
			file->flags |= cpu_to_be16(HFSPLUS_FILE_LOCKED);
		else
			file->flags &= cpu_to_be16(~HFSPLUS_FILE_LOCKED);
		file->access_date = hfsp_ut2mt(inode->i_atime);
		file->content_mod_date = hfsp_ut2mt(inode->i_mtime);
		file->attribute_mod_date = hfsp_ut2mt(inode->i_ctime);
		hfs_bnode_write(fd.bnode, &entry, fd.entryoffset,
					 sizeof(struct hfsplus_cat_file));
	}
out:
	hfs_find_exit(&fd);
	return 0;
}


text:
var Node = require('basis.ui').Node;
var template = require('basis.template');
var Row = require('./modules/row/index');

var templates = template.define('app.ui.table', {
    table: resource('./template/table.tmpl')
});

module.exports = Node.subclass({
    tableId: 'AbstractTable',
    template: templates.table,
    childClass: Row,
    binding: {
        head: 'satellite:',
        foot: 'satellite:'
    }
});


text:
package com.robin.core.fileaccess.writer;

import com.robin.core.fileaccess.meta.DataCollectionMeta;

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public abstract class WriterBasedFileWriter extends AbstractFileWriter{
	protected  int ioBufSize = 16 * 1024;

	public WriterBasedFileWriter(DataCollectionMeta colmeta) {
		super(colmeta);
	}
	@Override
	public void setOutputStream(OutputStream out) {
		super.setOutputStream(out);
		try {
			writer = new BufferedWriter(new OutputStreamWriter(out, colmeta.getEncode()));
		}catch (Exception ex){

		}

	}

	public void setBufferSize(int size) {
		this.ioBufSize = size;
	}
}


text:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import _ from 'lodash';
import DeckMechanics from './sidebar/details/deck-mechanics';
import MapFunctionlessIcons from '../right-container/topbar-assets/map-functionless-icons';
import ManaCurve from "../../../../../components/mana-curve/mana-curve";
import Icon from "../../../../../components/icon";
import DecklistSidebar from '../../../../../components/decklist-sidebar/decklist';
import Button from "../../../../../components/buttons/button";
import {toggleDeckMechanics} from "../../../../../redux/create-deck/actions/create-deck.action";

class DeckSidebar extends Component {

  handleDeckMechanicsToggle = () => {
    const {toggleDeckMechanics, deckCreation} = this.props;
    const {deckMechanics} = deckCreation;
    toggleDeckMechanics(!deckMechanics);
  };

  decklistHeaderView = () => {
    const {deck, imgReadyDecklist} = this.props.deckCreation;
    return imgReadyDecklist
        ? <MapFunctionlessIcons deck={deck} activeClass="decklist-summary" set="types"/>
        : <Button handleClick={this.handleDeckMechanicsToggle} text="Deck Mechanics" type="default--active" />
  };

  render() {
    const {playerClass, cards, deckCreation} = this.props;
    const {deck, deckMechanics} = deckCreation;
    let countByCost = _.countBy(deck, (value)=>value.cost < 7 ? value.cost : 7);
    let max = _.max(Object.values(countByCost));

    return (

Cards/Mana Cost

          <ManaCurve deck={deck} max={max} padding="1vh 0" barHeight="70%" barColor={playerClass}/>

Chosen Cards{this.decklistHeaderView()}

          {
            !deckMechanics
              ? <DecklistSidebar deck={deck} inDeckCreation/>
              : <DeckMechanics deck={deck} cards={cards}/>
          }

          <Icon name={playerClass} />

    );
  }
}

const mapStateToProps = state =>{
  const {deckCreation} = state;
  const {cards} = state.cards;

  return {deckCreation, cards};
};

const mapDispatchToProps = dispatch => {
  return {
    toggleDeckMechanics: deckMechanics => dispatch(toggleDeckMechanics(deckMechanics)),
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(DeckSidebar);


text:
package main

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/rightscale/rsc/gen"
)

var _ = Describe("APIAnalyzer ParseRoute", func() {
	var (
		moniker string
		routes  []string

		pathPatterns []*gen.PathPattern
	)

	JustBeforeEach(func() {
		pathPatterns = ParseRoute(moniker, routes)
	})

	Context("given a simple route", func() {
		BeforeEach(func() {
			routes = []string{"GET    /api/servers(.:format)? {:action=>\"index\", :controller=>\"servers\"}"}
		})

		It("computes the path pattern", func() {
			Ω(len(pathPatterns)).Should(Equal(1))
			Ω(pathPatterns[0].HTTPMethod).Should(Equal("GET"))
			Ω(pathPatterns[0].Pattern).Should(Equal("/api/servers"))
			Ω(pathPatterns[0].Variables).Should(BeEmpty())
		})
	})

	Context("given an obsolete route", func() {
		BeforeEach(func() {
			routes = []string{"GET    /api/session(.:format)? {:action=>\"index\", :controller=>\"servers\"}"}
		})

		It("does not produce a path pattern", func() {
			Ω(len(pathPatterns)).Should(Equal(0))
		})
	})

	Context("given a route with a variable", func() {
		BeforeEach(func() {
			routes = []string{"PUT    /api/servers/:id(.:format)? {:action=>\"index\", :controller=>\"servers\"}"}
		})

		It("computes the path pattern", func() {
			Ω(len(pathPatterns)).Should(Equal(1))
			Ω(pathPatterns[0].HTTPMethod).Should(Equal("PUT"))
			Ω(pathPatterns[0].Pattern).Should(Equal("/api/servers/%s"))
			Ω(len(pathPatterns[0].Variables)).Should(Equal(1))
			Ω(pathPatterns[0].Variables[0]).Should(Equal("id"))
		})
	})

	Context("given a route with multiple variables", func() {
		BeforeEach(func() {
			routes = []string{"PUT    /api/clouds/:cloud_id/instances/:instance_id/security_groups/:id(.:format)? {:action=>\"index\", :controller=>\"security_groups\"}"}
		})

		It("computes the path pattern", func() {
			Ω(len(pathPatterns)).Should(Equal(1))
			Ω(pathPatterns[0].HTTPMethod).Should(Equal("PUT"))
			Ω(pathPatterns[0].Pattern).Should(Equal("/api/clouds/%s/instances/%s/security_groups/%s"))
			Ω(len(pathPatterns[0].Variables)).Should(Equal(3))
			Ω(pathPatterns[0].Variables[0]).Should(Equal("cloud_id"))
			Ω(pathPatterns[0].Variables[1]).Should(Equal("instance_id"))
			Ω(pathPatterns[0].Variables[2]).Should(Equal("id"))
		})
	})

	Context("given multiple routes with multiple ", func() {
		BeforeEach(func() {
			routes = []string{
				"GET    /api/security_groups/:id(.:format)? {:action=>\"index\", :controller=>\"security_groups\"}",
				"GET    /api/instances/:instance_id/security_groups/:id(.:format)? {:action=>\"index\", :controller=>\"security_groups\"}",
				"GET    /api/clouds/:cloud_id/instances/:instance_id/security_groups/:id(.:format)? {:action=>\"index\", :controller=>\"security_groups\"}",
			}
		})

		It("computes the path patterns", func() {
			Ω(len(pathPatterns)).Should(Equal(3))
			Ω(pathPatterns[0].HTTPMethod).Should(Equal("GET"))
			Ω(pathPatterns[0].Pattern).Should(Equal("/api/security_groups/%s"))
			Ω(len(pathPatterns[0].Variables)).Should(Equal(1))
			Ω(pathPatterns[0].Variables[0]).Should(Equal("id"))
			Ω(pathPatterns[0].Pattern).Should(Equal("/api/security_groups/%s"))
			Ω(len(pathPatterns[1].Variables)).Should(Equal(2))
			Ω(pathPatterns[1].HTTPMethod).Should(Equal("GET"))
			Ω(pathPatterns[1].Variables[0]).Should(Equal("instance_id"))
			Ω(pathPatterns[1].Variables[1]).Should(Equal("id"))
			Ω(pathPatterns[1].Pattern).Should(Equal("/api/instances/%s/security_groups/%s"))
			Ω(len(pathPatterns[2].Variables)).Should(Equal(3))
			Ω(pathPatterns[2].HTTPMethod).Should(Equal("GET"))
			Ω(pathPatterns[2].Variables[0]).Should(Equal("cloud_id"))
			Ω(pathPatterns[2].Variables[1]).Should(Equal("instance_id"))
			Ω(pathPatterns[2].Variables[2]).Should(Equal("id"))
			Ω(pathPatterns[2].Pattern).Should(Equal("/api/clouds/%s/instances/%s/security_groups/%s"))
		})
	})
})


text:
package com.lee.jwaf.dto.bind;

import com.lee.jwaf.dto.WorkDTO;

/**
 * ClassName : WorkDTOAware

 * Description: provide work dto for action

 * notice: one action implement this interface will be set work dto

 * Create Time : 2016-09-19

 * @author jimmyblylee@126.com
 */
public interface WorkDTOAware {

    /**
     * Description : set work dto

     * Create Time: 2016-09-19

     * Create by : jimmyblylee@126.com

     *
     * @param workDTO the work dto
     */
    void setWorkDTO(WorkDTO workDTO);
}


text:
local assert =  require('assert')
local tap =  require('util/tap')

local shell =  require('wotc/shell')

local test = tap.test

test('test shell - getDeviceStatus', function()
    local device = shell.getDeviceStatus()
    console.log('device', device)
    assert.ok(device ~= nil)
    assert.ok(device.at >= 0)
    assert.ok(device.cpuUsage >= 0)
    assert.ok(device.memoryFree >= 0)
    assert.ok(device.memoryUsage >= 0)
    assert.ok(device.storageFree >= 0)
    assert.ok(device.storageUsage >= 0)
    assert.ok(device.updated >= 0)
end)

test('test shell - getDeviceProperties', function()
    local device = shell.getDeviceProperties()
    console.log('device', device)
    assert.ok(device ~= nil)
    assert.ok(device.currentTime ~= nil)
    assert.ok(device.memoryTotal ~= nil)
    assert.ok(device.softwareVersion ~= nil)
    assert.ok(device.manufacturer ~= nil)
    assert.ok(device.deviceType ~= nil)
    assert.ok(device.hardwareVersion ~= nil)
end)

test('test shell - getNetworkProperties', function()
    local network = shell.getNetworkProperties()
    console.log('network', network)
    assert.ok(network ~= nil)
    --assert.ok(network.total >= network.free)
    --assert.ok(network.usage >= 0)
end)

--[[

test('test shell - getMemoryStatus', function()
    local memory = shell.getMemoryStatus()
    assert.ok(memory ~= nil)
    console.log('memory', memory)
    assert.ok(memory.total >= memory.free)
    assert.ok(memory.usage >= 0)
end)

test('test shell - getNetworkStatus', function()
    local network = shell.getNetworkStatus()
    --assert.ok(network ~= nil)
    console.log('network', network)
    --assert.ok(network.total >= network.free)
    --assert.ok(network.usage >= 0)
end)

test('test shell - getNetworkStatus', function()
    local network = shell.getNetworkStatus()
    --assert.ok(network ~= nil)
    console.log('storage', network)
    --assert.ok(network.total >= network.free)
    --assert.ok(network.usage >= 0)
end)

test('test shell - getStorageStatus', function()
    local storage = shell.getStorageStatus()
    assert.ok(storage ~= nil)
    console.log('storage', storage)

    assert.ok(storage.total >= storage.free)
    assert.ok(storage.usage >= 0)
end)

test('test shell - getCpuUsage', function()
    local cpuUsage = shell.getCpuUsage()
    assert.ok(cpuUsage ~= nil)
    assert.ok(cpuUsage >= 0)
    console.log('cpuUsage', cpuUsage)
end)

test('test shell - getEnvironment', function()
    local cwd = process.cwd()
    local environment = shell.getEnvironment()
    assert.ok(environment ~= nil)
    assert.equal(environment.path, cwd)
end)

test('test shell - getMacAddress', function()
    local address = shell.getMacAddress()
    assert.ok(address ~= nil)
    assert.equal(#address, 12)
    console.log('address', address)
end)

test('test shell - shellExecute', function()
    local cwd = process.cwd()
    console.log(cwd)
    local cmd = 'ls /bin/sh'
    shell.shellExecute(cmd, function(result)
        console.log(result)

        assert.ok(result.output ~= nil)
        assert.equal(result.cmd, cmd)
        assert.equal(result.environment.path, cwd)
    end)
end)

test('test shell - chdir', function()
    local cwd = process.cwd()
    console.log(cwd)
    shell.chdir('/', function(result)
        console.log(result)

        assert.equal(result.environment.path, '/')
        shell.chdir(cwd)
    end)
end)

--]]

tap.run()


text:
'use strict';

type Scene = {name: string};

let _listeners: Array<(scene: Scene) => void> = [];

let _activeScene = {name: 'default'};

const SceneTracker = {
  setActiveScene(scene: Scene) {
    _activeScene = scene;
    _listeners.forEach((listener) => listener(_activeScene));
  },

  getActiveScene(): Scene {
    return _activeScene;
  },

  addActiveSceneChangedListener(callback: (scene: Scene) => void): {remove: () => void} {
    _listeners.push(callback);
    return {
      remove: () => {
        _listeners = _listeners.filter((listener) => callback !== listener);
      },
    };
  },
};

module.exports = SceneTracker;