text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package graphics;

import Shapes.Shape;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;

/**
 * Class that is used to pack a BufferedImage and the detection
 * information about it.
 *
 * @author Jérémi Cyr & Arnaud Paré-Vogt
 */
public class Frame {

    private BufferedImage image, trueImage;
    private List<Shape> shapes;
    private int trackedShapeIndex;

    private boolean validMatches;

    private boolean hasChangedSinceLastRepaint;

    /**
     * Crates a new frame, Containing the image image.
     *
     * @param image the image representad by this frame
     */
    public Frame(BufferedImage image) {
        this.image = image;
        shapes = new LinkedList<>();
        trackedShapeIndex = -1;
        validMatches = false;
        hasChangedSinceLastRepaint = true;
    }

    /**
     * Getter for the image of the frame
     *
     * @return the unaltered image of this frame, as an instance of
     * BufferedImage
     */
    public BufferedImage getImage() {
        return image;
    }
    /*
     trueImage is the original frame, with color
     these are the set and get methods for trueImage
     */

    public BufferedImage getTrueImage() {
        return trueImage;
    }

    public void setTrueImage(BufferedImage i) {
        hasChangedSinceLastRepaint = true;
        trueImage = i;
    }

    /**
     * Adds a new Shape to the currently detected shapes of this
     * frame
     *
     * @param shape the Shape to be added
     */
    public void addShapes(Shape shape) {
        shapes.add(shape);
        hasChangedSinceLastRepaint = true;
    }

    /**
     * Getter for the list of chapes that were detected on this frame. Because
     * the frame itself does not detect the shapes, the result depends completly
     * on the manipulations of the frame.
     *
     * @return a List of shapes linked to this frame.
     */
    public List<Shape> getShapes() {
        return shapes;
    }

    /**
     * sets the tracked shapes index in shapes to "i"s' value
     *
     * @param i the new Index to set
     */
    public void setTrackedShapeIndex(int i) {
        trackedShapeIndex = i;
        hasChangedSinceLastRepaint = true;
    }

    /**
     * @return trackedshapeindex
     */
    public int getTrackedShapeIndex() {
        return trackedShapeIndex;
    }

    /**
     * Returns the current shape match on a shape. Note that the shape match is
     * not guarenteed to be final, or even to have a meaning soly by calling
     * this method, you will have to look at result of
     * isValidMatches().
     *
     * @param shapeIndex the shape index
     * @return the curent match of the shape, or -1 if the shape doesn't exist
     */
    public double getShapeMatch(int shapeIndex) {
        if (shapeIndex >= 0 && shapeIndex < shapes.size()) {
            return shapes.get(shapeIndex).getMatch();
        }
        return -1;
    }

    /**
     * Sets the match percentage of a shape.
     *
     * @param shapeIndex the index of the shape
     * @param shapeMatch the percentage match of the chape
     */
    public void setShapeMatch(int shapeIndex, double shapeMatch) {
        if (shapeIndex >= 0 && shapeIndex < shapes.size()) {
            shapes.get(shapeIndex).setMatch(shapeMatch);
        }
        hasChangedSinceLastRepaint = true;
    }

    public void setValidMatches(boolean validMatches) {
        this.validMatches = validMatches;
        hasChangedSinceLastRepaint = true;
    }

    public boolean isValidMatches() {
        return validMatches;
    }

    /*
     returns the tracked shape if applicable, or null and a warning
     */
    public Shape getTrackedShape() {
        if (shapes.size() > 0 && trackedShapeIndex >= 0) {
            return shapes.get(trackedShapeIndex);
        }
        return null;
    }

    /**
     * called to set the flag hasChangedSinceLastRepaint to false
     */
    public void repaint() {
        this.hasChangedSinceLastRepaint = false;
    }

    /**
     * Says if the frame needs to be repainted.
     * @return if the frame needs to be repainted
     */
    public boolean doesItNeedsRepaint(){
        return hasChangedSinceLastRepaint;
    }

    /**
     * Tells the frame that it needs to be repainted.
     */
    public void hasChangedSinceLastRepaint() {
        this.hasChangedSinceLastRepaint = true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.snowplowanalytics.snowplow.enrich.spark
package good

import scala.io.Source

import org.specs2.mutable.Specification

object CljTomcatTp2MegaEventsSpec {
  val lines = {
    val file = getClass.getResource("CljTomcatTp2MegaEventsSpec.line").getFile
    val source = Source.fromFile(file)
    val line = source.mkString
    source.close()
    EnrichJobSpec.Lines(line)
  }
}

class CljTomcatTp2MegaEventsSpec extends Specification with EnrichJobSpec {
  import EnrichJobSpec._
  override def appName = "clj-tomcat-tp2-mega-events"
  sequential
  "A job which processes a Clojure-Tomcat file containing a POST raw event representing 7,500 " +
  "valid events" should {
    runEnrichJob(CljTomcatTp2MegaEventsSpec.lines, "clj-tomcat", "2", true, List("geo"))

    "correctly output 7,500 events" in {
      val Some(goods) = readPartFile(dirs.output)
      goods.size must_== 7500
    }

    "not write any bad rows" in {
      dirs.badRows must beEmptyDir
    }
  }
}


text:
@implementation GCDSampleiPhoneViewController

@synthesize progress, randomLabel, randomButton, bigTaskButton;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	// The second parameter is unused, so just pass in null. This parameter may have future use.
	progressQueue = dispatch_queue_create("edu.byu.cocoaheads.gcdprogressqueue", NULL);

	// Our "big task" is "critically important," so we want it to run at high priority.
	dispatch_queue_t target = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
	dispatch_set_target_queue(progressQueue, target);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (IBAction) displayRandomNumber {

    // The random number display is just to demonstrate how multithreading, or
    // lack thereof, affects other concurrent tasks.
	[randomLabel setText:[NSString stringWithFormat:@"%d", arc4random() % 100]];
}

- (IBAction) runBigTask {

	// __block keyword is not needed to modify "running" because it's in global memory space.
	static BOOL running = NO;

	// Only allows one block running at a time.
	if(!running) {

		// This should be before the block starts since we don't know when the block will actually start running.
		running = YES;

        // This block is dispatched to the queue we created in the initializer;
        // however, this could be dispatched directly to a global queue using:
        // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Note that these two forms of dispatching have different behaviors.
		dispatch_async(progressQueue, ^{

			// UI updates must be done on the main thread.
			dispatch_async(dispatch_get_main_queue(), ^{

				[progress setProgress:0.0];

			});

            // Simulates a big task by running several smaller tasks.
			for (int i = 0; i < 100; i++) {

				// Simulates a smaller task with a delay.
				[NSThread sleepForTimeInterval:0.1];

				// UI updates must be done on the main thread.
				dispatch_async(dispatch_get_main_queue(), ^{

					[progress setProgress:[progress progress] + 0.01];

				});
			}

			// "Running" must be reset within the block since this block is run by dispatch_async.
			running = NO;
		});
	}
}

- (void)dealloc {
	[progress release];
	[randomLabel release];
	[randomButton release];
	[bigTaskButton release];

	// Notice that GCD objects are C objects and must be released with a C function call.
	dispatch_release(progressQueue);

    [super dealloc];
}

@end


text:
from django import forms
from django.forms import CharField, IntegerField

from mybitbank.libs.connections import connector
from mybitbank.libs import misc

class CoinAccount(CharField):
    def validate(self, value):
        super(CharField, self).validate(value)

class CoinAddress(CharField):
    def validate(self, value):
        super(CharField, self).validate(value)
        if value == "":
            raise forms.ValidationError("Please provide a valid address")

        if len(value) < 27 or 34 > len(value):
            raise forms.ValidationError("Please provide a valid address")

class CoinAmount(CharField):
    def to_python(self, value):
        if not misc.isFloat(value):
            raise forms.ValidationError("Please provide a valid amount eg. 12.3456789")

        return float(value)

    def validate(self, value):
        super(CharField, self).validate(value)
        if not misc.isFloat(value):
            raise forms.ValidationError("Please provide a valid amount eg. 12.3456789")

        if value == 0 or value < 0:
            raise forms.ValidationError("Please provide a valid amount eg. 12.3456789")

class CoinCurrency(CharField):
    def validate(self, value):
        super(CharField, self).validate(value)
        supported_currencies = connector.services.keys()
        if value not in supported_currencies:
            raise forms.ValidationError("This currency is not supported: %s" % value)

class CoinProviderId(IntegerField):
    def validate(self, value):
        super(IntegerField, self).validate(value)
        if value not in connector.config.keys():
            raise forms.ValidationError("This currency provider id is not supported: %s" % value)

    def to_python(self, value):
        try:
            return int(value)
        except:
            return 0

class SendCurrencyForm(forms.Form):
    initial_provider_id = connector.config.keys()[0]

    from_account = CoinAccount(initial="")
    to_address = CoinAddress(initial="")
    to_account = CoinAccount(initial="", required=False)
    comment = forms.CharField(initial="", required=False)
    comment_to = forms.CharField(initial="", required=False)
    amount = CoinAmount(initial=0, required=True)
    provider_id = CoinProviderId(required=True, initial=initial_provider_id)
    passphrase = forms.CharField(initial="", required=False)

    def clean(self):
        cleaned_data = super(SendCurrencyForm, self).clean()
        # from_address = cleaned_data.get('from_address', "")
        # to_address = cleaned_data.get('to_address', "")

        # if from_address == to_address and (from_address and to_address):
        #    raise forms.ValidationError("You cannot move from and to the same account/address")

        return cleaned_data


text:
> How use fetch and store tweets.

This doc covers two approaches supported by Twitterverse:

- [Search tweets](#search-tweets) by a search query.
- [Lookup tweets](#lookup-tweets) with a list of Tweet IDs.

Read about the [Tweet model](/development/models.md#tweets-and-profiles-model.md) section of the docs to understand how tweets, profiles and campaign are used and stored.

## Search tweets

Fetch tweets matching a search query, typically based on the content of the tweet messages. This search be setup to run on schedule, so you can build up a history of tweets.

```bash
$ cd app/utils
```

Without knowing any Twitter handles, you can do a query against the Search API using a search query. Read more in the [search](twitter-api-docs/search.md) doc.

- Use the _Search and Store Tweets_ utility for this.
    ```bash
    $ ./insert/search_and_store_tweets.py -h
    ```
- Or use the extract search utility, which only writes to a CSV. This is detailed in the [Scale](#scale) section.

### Ad hoc query

Specify a query in the terminal and do a search. This makes it easy to test a query before confirming it should be stored as a campaign.

Optionally add the `--no-persist` flag to not store data to the database and print the simplified tweet data (count, handle and message) to the terminal.

Examples:

- PyCon search.
    ```bash
    $ ./insert/search_and_store_tweets.py \
        'to:pyconza OR from:pyconza OR pyconza OR pyconza17 OR za.pycon.org' \
        --no-persist
    ```
- Festival search, using a Bash variable.
    ```bash
    $ TERMS='"MamaCity Improv" OR MCIF OR MamaCityImprovFest OR MamaCityIF'\
    ' OR mamacityimprovfestival.nutickets.co.za OR mamacityimprovfest.com'
    $ ./insert/search_and_store_tweets.py "$TERMS"
    ```

View the logs for more verbose output on the search.

### Store and use query

Add a search query to the database to make it easy to reuse. See instructions below.

View stored campaigns with counts of locally stored tweets.

    $ ./manage/campaigns.py --all
        Campaign                  |  Tweets | Query
    1. Black Friday               |   1,234 | #BlackFriday
    2. ...

Create or update a campaign.

    $ ./manage/campaigns.py --campaign 'Foo bar' \
        --query '"Foo Bar" OR #FooBar OR @Baz'
    Created Campaign: Foo bar | "Foo Bar" OR #FooBar OR @Baz

Search tweets matching a campaign's query. Tweets are stored against the campaign.

    $ ./insert/search_and_store_tweets.py \
        --campaign 'Foo bar' --pages 1000
    Search query: #foo OR #bar
    Generating Application-Only Auth...
    [START] searchStoreAndLabel
    Starting Search. Expected pages: 100,000. Expected tweets: 10,000,000.
    Stored so far: 100
    Stored so far: 200

### Scale

The [insert/search_and_store_tweets.py](https://github.com/MichaelCurrin/twitterverse/blob/master/app/utils/insert/search_and_store_tweets.py) utility script can fetch and store hundreds of tweets in a few seconds, depending on your machine and internet speed course. This method uses the ORM - multiple insert and get queries are made to get a single tweet into the DB. This does not scale well though as it adds to the total time of the query. This is inconvenient especially if you have a lot of separate and high volume searches to do regularly (such as daily or several times a day).

The [extract/search.py](https://github.com/MichaelCurrin/twitterverse/blob/master/app/utils/extract/search.py) utility script is faster as it writes data out to a CSV at intervals. The logic to insert that data into the DB using a single SQL statement in a transaction (to rollback on failure) must still be created and documented here.

Note that there is still an upper limit on the number of tweets to be fetched in 15 min period, due to the API rate limits. So even if you use the more efficient method, you might find that you hit the API limit and the script has to wait a few minutes before it can retry, which is similar to just running slower and more continuously. The tradeoffs still have to be investigated.

## Lookup tweets
> Fetch tweets by ID.

Fetch and store tweet objects from the API by providing _tweet IDs_, either from a previous API query or by looking at the ID of a tweet in the browser. Note that this ID is called a _GUIDs_ within the model.

```bash
$ cd app/utils
```

View help.

```bash
$ ./insert/lookup_and_store_tweets.py --help
```

Example

```bash
$ ./insert/lookup_and_store_tweets.py 1234566915281 125115773299 325882358325
```


text:
'use strict';

var _								= require('lodash'),
SVGSpriteStandalone					= require('./standalone'),
SVGSpriteCss						= require('./css'),
SVGSprite							= require('../sprite');

/**
 * <view> sprite
 *
 * @param {SVGSpriter} spriter		SVG spriter
 * @param {Object} config			Configuration
 * @param {Object} data				Base data
 * @param {String} key				Mode key
 */
function SVGSpriteView(spriter, config, data, key) {
	SVGSpriteCss.apply(this, [spriter, config, data, key]);
}

/**
 * Prototype
 *
 * @type {Object}
 */
SVGSpriteView.prototype = _.create(SVGSpriteCss.prototype, {
	constructor						: SVGSpriteView,
	mode							: SVGSpriteCss.prototype.MODE_VIEW,

	_initData						: SVGSpriteStandalone.prototype._initData
});

/**
 * Refine the root attributes set on each nested shape
 *
 * @param {SVGShape} shape			Shape
 * @param {Number} index			Index
 * @param {Object} rootAttributes	Root element attributes
 * @return {Object}					Refined root element attributes
 */
SVGSpriteView.prototype._refineRootAttributes = function(shape, index, rootAttributes) {

	// If it's the master shape multiple displaced copies
	if (this._displaceable) {
		if (shape.master) {
			delete rootAttributes.id;
			rootAttributes['xlink:href']	= '#' + shape.master.id + '-';
		} else {
			rootAttributes.id				+= '-';
		}

	// Else: Remove the ID attribute
	} else {
		delete rootAttributes.id;
	}

	return rootAttributes;
};

/**
 * Build the CSS sprite
 *
 * @param {String} xmlDeclaration			XML declaration
 * @param {String} doctypeDeclaration		Doctype declaration
 * @return {File}							SVG sprite file
 */
SVGSpriteView.prototype._buildSVG = function(xmlDeclaration, doctypeDeclaration) {
	var rootAttributes				= _.extend(
		{},
		this.config.svg.rootAttributes,
		this.config.svg.dimensionAttributes ? {
			width					: this.data.spriteWidth,
			height					: this.data.spriteHeight
		} : {},
		{
			viewBox					: '0 0 ' + this.data.spriteWidth + ' ' + this.data.spriteHeight
		}
	),
	svg								= new SVGSprite(this.declaration(this.config.svg.xmlDeclaration, xmlDeclaration), this.declaration(this.config.svg.doctypeDeclaration, doctypeDeclaration), rootAttributes, true, this.config.svg.transform);
	this.data.shapes.forEach(function(shape) {
		var viewBox					= [-shape.position.absolute.x, -shape.position.absolute.y, shape.width.outer, shape.height.outer];
		svg.add('<view id="' + shape.name + '" viewBox="' + viewBox.join(' ') + '"/>');
		svg.add(shape.svg);
	});

	return svg.toFile(this._spriter.config.dest, this._addCacheBusting(svg));
};

/**
 * Module export
 */
module.exports = SVGSpriteView;


text:
package qiniu.predem.android.diagnosis;

import com.qiniu.android.netdiag.Output;

import qiniu.predem.android.util.LogUtils;

/**
 * Created by Misty on 2017/8/7.
 */

public final class DiagnosisLogger implements Output {

    @Override
    public void write(String line) {
        LogUtils.i(line);
    }
}


text:
ROOT_DIR=$(cd `dirname $0`/../../..; pwd)
CLASSPATH=$ROOT_DIR/assembly/osx-x86_64-cpu/target/*:$ROOT_DIR/examples/target/*:$ROOT_DIR/examples/target/classes/lib/*

mkdir -p model
java -Xmx4G -cp $CLASSPATH \
	ml.dmlc.mxnetexamples.module.MnistMlp \
  --data-dir "$ROOT_DIR/core/data/" \
  --batch-size 10 \
  --num-epoch 5


text:
gem 'actionpack', '2.3.8'
require 'action_controller'
require 'action_controller/test_process'

require 'pagination'

ActionController::Routing::Routes.draw do |map|
  map.connect 'dummy/page/:page', :controller => 'dummy'
  map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots'
  map.connect 'ibocorp/:page', :controller => 'ibocorp',
                               :requirements => { :page => /\d+/ },
                               :defaults => { :page => 1 }

  map.connect ':controller/:action/:id'
end

ActionController::Base.perform_caching = false

class Pagination::ViewTestCase < Test::Unit::TestCase
  if defined?(ActionController::TestCase::Assertions)
    include ActionController::TestCase::Assertions
  end
  if defined?(ActiveSupport::Testing::Deprecation)
    include ActiveSupport::Testing::Deprecation
  end

  def setup
    super
    @controller  = DummyController.new
    @request     = @controller.request
    @html_result = nil
    @template    = '<%= paginate collection, options do |tmp|; tmp.each do |t|; end; end %>'

    @view = ActionView::Base.new
    @view.assigns['controller'] = @controller
    @view.assigns['_request']   = @request
    @view.assigns['_params']  = @request.params
  end

  def default_test; end

  protected

    def paginate(collection = {}, options = {}, &block)

      Article.destroy_all
      11.times {|i| Article.create!(:id => i, :user => User.create)}

      if collection.instance_of? Hash
        @request.params :page => collection[:page] || 1
        collection = Article.all
      end
      options = {:per_page => 4, :controls => :top}.merge(options)

      locals = { :collection => collection, :options => options }

      unless @view.respond_to? :render_template
        # Rails 2.2
        @html_result = ActionView::InlineTemplate.new(@template).render(@view, locals)
      else
        if defined? ActionView::InlineTemplate
          # Rails 2.1
          args = [ ActionView::InlineTemplate.new(@view, @template, locals) ]
        else
          # older Rails versions
          args = [nil, @template, nil, locals]
        end

        @html_result = @view.render_template(*args)
      end

      @html_document = HTML::Document.new(@html_result, true, false)

      if block_given?
        classname = options[:class] || Pagination::ViewHelpers.pagination_options[:class]
        assert_select("div.#{classname}",1 , 'no main DIV', &block)
      end

    end

    def response_from_page_or_rjs
      @html_document.root
    end

    def validate_page_numbers expected, links, param_name = :page
      param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/

      assert_equal(expected, links.map { |e|
        e['href'] =~ param_pattern
        $1 ? $1.to_i : $1
      })
    end

    def assert_links_match pattern, links = nil, numbers = nil
      links ||= assert_select 'div.pagination a[href]' do |elements|
        elements
      end

      pages = [] if numbers

      links.each do |el|
        assert_match pattern, el['href']
        if numbers
          el['href'] =~ pattern
          pages << ($1.nil?? nil : $1.to_i)
        end
      end

      assert_equal numbers, pages, "page numbers don't match" if numbers
    end

    def assert_no_links_match pattern
      assert_select 'div.pagination a[href]' do |elements|
        elements.each do |el|
          assert_no_match pattern, el['href']
        end
      end
    end
end

class DummyRequest
  attr_accessor :symbolized_path_parameters

  def initialize
    @get = true
    @params = {}
    @symbolized_path_parameters = { :controller => 'foo', :action => 'bar'}
  end

  def get?
    @get
  end

  def post
    @get = false
  end

  def relative_url_root
    ''
  end

  def params(more = nil)
    @params.update(more) if more
    @params
  end
end

class DummyController
  attr_reader :request
  attr_accessor :controller_name

  def initialize
    @request = DummyRequest.new
    @url = ActionController::UrlRewriter.new(@request, @request.params)
  end

  def params
    @request.params
  end

  def url_for(params)
    @url.rewrite(params)
  end
end

module HTML
  Node.class_eval do
    def inner_text
      children.map(&:inner_text).join('')
    end
  end

  Text.class_eval do
    def inner_text
      self.to_s
    end
  end

  Tag.class_eval do
    def inner_text
      childless?? '' : super
    end
  end
end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>C++ Web Framework: Class Hierarchy</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

C++ Web Framework
    3.0

Class Hierarchy

Go to the textual class hierarchy

<address class="footer">
Generated on Mon May 28 2018 11:09:09 for C++ Web Framework by

 1.8.13
</address>


text:
using namespace std;
using namespace ha;

using ::testing::Return;
using ::testing::DoAll;
using ::testing::SetArgReferee;
using ::testing::AtLeast;
using ::testing::_;

namespace ForceTorqueSensorTest {
    class MockSystem : public ha::System {
    public:
        MOCK_CONST_METHOD0(getDof, int () );
        MOCK_CONST_METHOD0(getJointConfiguration, ::Eigen::MatrixXd () );
        MOCK_CONST_METHOD0(getJointVelocity, ::Eigen::MatrixXd () );
        MOCK_CONST_METHOD1(getForceTorqueMeasurement, ::Eigen::MatrixXd (const int& port) );
        MOCK_CONST_METHOD0(getCurrentTime, ::Eigen::MatrixXd () );
        MOCK_CONST_METHOD1(getFramePose, ::Eigen::MatrixXd (const std::string& frame_id) );
    };
}

TEST(ForceTorqueSensor, FrameId) {
    using ::testing::Invoke;

    ForceTorqueSensorTest::MockSystem* _ms = new ForceTorqueSensorTest::MockSystem();
    System::ConstPtr ms(_ms);

    //The sensor reading of the system - we will mock it as constant
    ::Eigen::MatrixXd ftSensorMat(6,1);
    ftSensorMat<<1.0,2.0,3.0,4.0,5.0,6.0;
    EXPECT_CALL(*_ms, getForceTorqueMeasurement(DEFAULT_FT_PORT))
        .WillRepeatedly(Return(ftSensorMat));

    ::Eigen::MatrixXd poseMat(4,4);
    poseMat.row(0) << 0.0,1.0,0.0,   0.; //1.0;
    poseMat.row(1) << 1.0,0.0,0.0,   0.; //2.0;
    poseMat.row(2) << 0.0,0.0,1.0,   0.; //3.0;
    poseMat.row(3) << 0.0,0.0,0.0,   1.0;

    EXPECT_CALL(*_ms, getFramePose(_))
        .WillRepeatedly(Return(poseMat));

    ::Eigen::MatrixXd ftSensorMatTransformed(6,1);
    ftSensorMatTransformed << 2.0,1.0,3.0,5.0,4.0,6.0;

    //std::map<std::string, std::string> add_args;
    //fillMap(add_args);

    // FIRST TEST: no frame ID

    {
    // Mocked description used to deserialize force torque sensor
    MockDescriptionTreeNode::Ptr ft_node(new MockDescriptionTreeNode);

    ForceTorqueSensor::Ptr ftsensor(new ForceTorqueSensor);
    EXPECT_CALL(*ft_node, getType()).WillRepeatedly(Return("Sensor"));
    EXPECT_CALL(*ft_node, getAttributeString(_, _))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*ft_node, getAttributeString(std::string("type"), _))
        .WillRepeatedly(DoAll(SetArgReferee<1>("ForceTorqueSensor"),Return(true)));
    EXPECT_CALL(*ft_node, getAttributeString(std::string("frame_id"), _))
        .WillRepeatedly(DoAll(SetArgReferee<1>(""),Return(true)));

    HybridAutomaton ha;
    ftsensor->deserialize(ft_node, ms, &ha);

    EXPECT_EQ("ForceTorqueSensor", ftsensor->getType());

    ::Eigen::MatrixXd ret = ftsensor->getCurrentValue();
    EXPECT_EQ(ftSensorMat, ret);

    }

    // SECOND TEST: now check transformation
    {
    // Mocked description used to deserialize force torque sensor
    MockDescriptionTreeNode::Ptr ft_node(new MockDescriptionTreeNode);

    ForceTorqueSensor::Ptr ftsensor(new ForceTorqueSensor);
    EXPECT_CALL(*ft_node, getType()).WillRepeatedly(Return("Sensor"));
    EXPECT_CALL(*ft_node, getAttributeString(_, _))
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*ft_node, getAttributeString(std::string("type"), _))
        .WillRepeatedly(DoAll(SetArgReferee<1>("ForceTorqueSensor"),Return(true)));
    EXPECT_CALL(*ft_node, getAttributeString(std::string("frame_id"), _))
        .WillRepeatedly(DoAll(SetArgReferee<1>("base"),Return(true)));

    HybridAutomaton ha;
    ftsensor->deserialize(ft_node, ms, &ha);

    EXPECT_EQ("ForceTorqueSensor", ftsensor->getType());

    ::Eigen::MatrixXd ret = ftsensor->getCurrentValue();
    //cout << ret << endl;
    EXPECT_EQ(ftSensorMatTransformed, ret);

    }

//    std::string val;
//    ctrl->getArgument("extra_arg", val);
//    EXPECT_EQ(add_args["extra_arg"], val);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Ionic.Zip;
using System.Web.Script.Serialization;
using GerberLibrary;

namespace DirtyPCB_BoardStats
{
    class DirtyPCB_BoardStats
    {
        static void Main(string[] args)
        {
            if (args.Count()<1)
            {
                Console.WriteLine("Usage: DirtyPCB_BoardStats.exe <infile>|<infolder>|<inzip>");
                return;
            }

            Stats TheStats = new Stats();
            if (Directory.Exists(args[0]))
            {
                GerberLibrary.GerberImageCreator GIC = new GerberLibrary.GerberImageCreator();

                foreach(var L in Directory.GetFiles(args[0]).ToList())
                {
                    TheStats.AddFile(new GerberLibrary.StandardConsoleLog(), L);
                }

            }
            else
            if (File.Exists(args[0]))
            {
                if (Path.GetExtension(args[0]).ToLower() == ".zip")
                {
                    using (ZipFile zip1 = ZipFile.Read(args[0]))
                    {
                        foreach (ZipEntry e in zip1)
                        {
                            MemoryStream MS = new MemoryStream();
                            if (e.IsDirectory == false)
                            {
                                e.Extract(MS);
                                MS.Seek(0, SeekOrigin.Begin);
                                TheStats.AddFile(new GerberLibrary.StandardConsoleLog(), MS, e.FileName);
                            }
                        }
                    }
                }
                else
                {
                    TheStats.AddFile(new GerberLibrary.StandardConsoleLog(), args[0]);
                }

            }
            TheStats.Complete();

            var json = new JavaScriptSerializer().Serialize(TheStats);
            Console.WriteLine(json);

        }

        public class Stats
        {
            public int DrillCount;
            public double Width;
            public double Height;
            private GerberLibrary.Bounds Box = new GerberLibrary.Bounds();

            public void AddFile(GerberLibrary.ProgressLog log, MemoryStream L, string filename)
            {
                L.Seek(0, SeekOrigin.Begin);

                var T = GerberLibrary.Gerber.FindFileTypeFromStream(new StreamReader(L), filename);
                switch (T)
                {
                    case GerberLibrary.Core.BoardFileType.Drill:
                        {
                            GerberLibrary.ExcellonFile EF = new GerberLibrary.ExcellonFile();
                            L.Seek(0, SeekOrigin.Begin);

                            EF.Load(log, new StreamReader(L));
                            DrillCount += EF.TotalDrillCount();
                        }
                        break;
                    case GerberLibrary.Core.BoardFileType.Gerber:
                        {
                            GerberLibrary.Core.BoardSide Side;
                            GerberLibrary.Core.BoardLayer Layer;
                            GerberLibrary.Gerber.DetermineBoardSideAndLayer(filename, out Side, out Layer);
                            if (Layer == GerberLibrary.Core.BoardLayer.Outline || Layer == GerberLibrary.Core.BoardLayer.Mill)
                            {
                                L.Seek(0, SeekOrigin.Begin);
                                var G = GerberLibrary.PolyLineSet.LoadGerberFileFromStream(new StandardConsoleLog(), new StreamReader(L), filename);
                                Box.AddBox(G.BoundingBox);
                            }
                        }
                        break;
                }

            }

            public void AddFile(GerberLibrary.ProgressLog log, string L)
            {
                var T = GerberLibrary.Gerber.FindFileType(L);
                switch (T)
                {
                    case GerberLibrary.Core.BoardFileType.Drill:
                        {
                            GerberLibrary.ExcellonFile EF = new GerberLibrary.ExcellonFile();
                            EF.Load(log, L);
                            DrillCount += EF.TotalDrillCount();
                        }
                        break;
                    case GerberLibrary.Core.BoardFileType.Gerber:
                        {
                            GerberLibrary.Core.BoardSide Side;
                            GerberLibrary.Core.BoardLayer Layer;
                            GerberLibrary.Gerber.DetermineBoardSideAndLayer(L, out Side, out Layer);
                            if (Layer == GerberLibrary.Core.BoardLayer.Outline || Layer == GerberLibrary.Core.BoardLayer.Mill)
                            {
                                var G = GerberLibrary.PolyLineSet.LoadGerberFile(log, L);
                                Box.AddBox(G.BoundingBox);
                            }
                        }
                        break;
                }

            }

            public void Complete()
            {
                Width = Box.Width();
                Height = Box.Height();
            }
        }

    }
}


text:
package ru.job4j.tictactoe.io;

import ru.job4j.tictactoe.game.Player;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Класс, реализующий ввод данных от игроков.
 */
public class ConsoleInput implements Input {
    /**
     * Поток ввода - стандартный поток ввода с консоли.
     */
    private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    /**
     * Запросить данные для совершения хода игроком или сигнал для выхода из игры.
     *
     * @param player игрок, от которого ожидается ход.
     * @return координаты хода.
     */
    @Override
    public String askMove(Player player) {
        String result = "";
        System.out.println("Waiting move from player " + player.getMark().getType());
        try {
            String answer = "";
            boolean valid = false;
            while (!valid) {
                answer = reader.readLine();
                if (answer.equals("exit")) {
                    break;
                }
                valid = isCoordinates(answer);
                if (!valid) {
                    System.out.println("Enter two integer coordinates!");
                }
            }
            result = answer;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Запросить размер игрового поля или сигнал о выходе из игры.
     *
     * @return размер игрового поля.
     */
    @Override
    public String askBoardSize() {
        String line = System.lineSeparator();
        String result = null;
        System.out.println("Welcome to TicTacToe!" + line
                + "----------------------------" + line
                + "Enter board size (one integer number) or type 'exit' to exit:");
        try {
            String answer = "";
            boolean validSize = false;
            while (!validSize) {
                answer = reader.readLine();
                if (answer.equals("exit")) {
                    result = answer;
                    break;
                }
                try {
                    int size = Integer.parseInt(answer);
                    if (size > 0) {
                        validSize = true;
                        result = Integer.toString(size);
                    } else {
                        System.out.println("Board size must be positive number, at least 1!");
                    }
                } catch (NumberFormatException e) {
                    System.out.println("Enter one integer digit!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Вспомогательный метод для проверки, является ли строка координатами.
     *
     * @param string строка для проверки.
     * @return строка содержит координаты или нет.
     */
    private boolean isCoordinates(String string) {
        boolean result = false;
        String[] parts = string.split(",");
        if (parts.length == 2) {
            try {
                Integer.parseInt(parts[0].trim());
                Integer.parseInt(parts[1].trim());
                result = true;
            } catch (NumberFormatException e) {
                result = false;
            }
        }
        return result;
    }
}


text:
package org.zstack.utils.ssh;

public class SshResult {
	private int returnCode;
	private String stdout;
	private String stderr;
	private String exitErrorMessage;
	private String commandToExecute;
    private boolean isSshFailure;

    public void raiseExceptionIfFailed(int retCode) {
        if (retCode != returnCode) {
            throw new SshException(toString());
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("\nssh command failed");
        sb.append(String.format("\ncommand: %s", commandToExecute));
        sb.append(String.format("\nreturn code: %s", returnCode));
        sb.append(String.format("\nstdout: %s", stdout));
        sb.append(String.format("\nstderr: %s", stderr));
        sb.append(String.format("\nexitErrorMessage: %s", exitErrorMessage));
        return sb.toString();
    }

    public boolean isSshFailure() {
        return isSshFailure;
    }

    public void setSshFailure(boolean isSshFailure) {
        this.isSshFailure = isSshFailure;
    }

    public void raiseExceptionIfFailed() {
        raiseExceptionIfFailed(0);
    }

    public int getReturnCode() {
		return returnCode;
	}
	public void setReturnCode(int returnCode) {
		this.returnCode = returnCode;
	}
	public String getStdout() {
		return stdout;
	}
	public void setStdout(String stdout) {
		this.stdout = stdout;
	}
	public String getStderr() {
		return stderr;
	}
	public void setStderr(String stderr) {
		this.stderr = stderr;
	}
	public String getExitErrorMessage() {
		return exitErrorMessage;
	}
	public void setExitErrorMessage(String exitErrorMessage) {
		this.exitErrorMessage = exitErrorMessage;
	}
	public String getCommandToExecute() {
		return commandToExecute;
	}
	public void setCommandToExecute(String commandToExecute) {
		this.commandToExecute = commandToExecute;
	}
}


text:
//
//  DGSKRGBDrawContextStylingProvider.m
//  SpiralKit by Digital Generalists
//
//  Created by Mark Johnson on 7/21/12.
//  Copyright (c) 2015 Digital Generalists, LLC.
//

#import "DGSKRGBDrawContextStylingProvider.h"

#import "SpiralKitTypes.h"

#import "DGSKDrawContextStylingProviderProtocol.h"
#import "DGSKDrawEffectsEngineProtocol.h"

#import "DGSKGraphicsUtils.h"

#define DRAW_CONTEXT_STYLE_DEFAULT_COLOR_ALPHA 1.0
#define DRAW_CONTEXT_STYLE_DEFAULT_COLOR_RED 0.0
#define DRAW_CONTEXT_STYLE_DEFAULT_COLOR_GREEN 0.0
#define DRAW_CONTEXT_STYLE_DEFAULT_COLOR_BLUE 0.0

#define ENCODING_PROPERTY_COLOR_ALPHA @"colorAlpha"
#define ENCODING_PROPERTY_COLOR_RED @"colorRed"
#define ENCODING_PROPERTY_COLOR_GREEN @"colorGreen"
#define ENCODING_PROPERTY_COLOR_BLUE @"colorBlue"

@interface DGSKRGBDrawContextStylingProvider()

@end

@implementation DGSKRGBDrawContextStylingProvider

@synthesize CreateStylingColorSpace = _CreateStylingColorSpace;

@synthesize colorComponentRed = _colorComponentRed;
@synthesize colorComponentGreen = _colorComponentGreen;
@synthesize colorComponentBlue = _colorComponentBlue;
@synthesize colorComponentAlpha = _colorComponentAlpha;

- (id) init
{
    self = [super init];
    if (self)
    {
        _CreateStylingColorSpace = &CGColorSpaceCreateDeviceRGB;

        self.colorComponentRed = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_RED;
        self.colorComponentGreen = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_GREEN;
        self.colorComponentBlue = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_BLUE;
        self.colorComponentAlpha = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_ALPHA;
    }
    return self;
}

- (id) initWithStylingProvider:(id<DGSKDrawContextStylingProviderProtocol>)provider
{
    self = [super initWithStylingProvider:provider];
    if (self)
    {
        if ([provider isKindOfClass:[DGSKRGBDrawContextStylingProvider class]])
        {
            DGSKRGBDrawContextStylingProvider *typedProvider = (DGSKRGBDrawContextStylingProvider *)provider;
            self.colorComponentRed = typedProvider.colorComponentRed;
            self.colorComponentGreen = typedProvider.colorComponentGreen;
            self.colorComponentBlue = typedProvider.colorComponentBlue;
            self.colorComponentAlpha = typedProvider.colorComponentAlpha;
        }

        id<DGSKDrawEffectsEngineProtocol> effectsEngine = provider.effectsEngine;
        // The reset of effects is performed here because the
        // assigment of the effectsEngine should calibrate the
        // effects engine to the styling provider on assignment.
        [effectsEngine resetEffectsForStylingProvider:self];
        self.effectsEngine = effectsEngine;
    }
    return self;
}

- (id) initAsToolType:(DGSKDrawToolType)type
{
    self = [super initAsToolType:type];
    if (self)
    {
        _CreateStylingColorSpace = &CGColorSpaceCreateDeviceRGB;

        self.colorComponentRed = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_RED;
        self.colorComponentGreen = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_GREEN;
        self.colorComponentBlue = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_BLUE;
        self.colorComponentAlpha = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_ALPHA;
    }
    return self;
}

- (id) initWithEffectsEngine:(id<DGSKDrawEffectsEngineProtocol>)effectsEngine
{
    self = [self initAsToolType:DGSKDrawToolTypeNormal withEffectsEngine:effectsEngine];
    if (self)
    {

    }
    return self;
}

- (id) initAsToolType:(DGSKDrawToolType)type withEffectsEngine:(id<DGSKDrawEffectsEngineProtocol>)effectsEngine
{
    self = [self initAsToolType:type];
    if (self)
    {
        switch (self.drawToolType)
        {
            case DGSKDrawToolTypeNormal:
                // The default, parameterless init call sets these up properly.
                // Setting the value here would be harmless and redundant, so
                // not placing here to save a few minimal processor cycles.
                break;
            case DGSKDrawToolTypeHighlighter:
                {
                    // NOTE:  If this is changed to a monochrome color, the components will need to be mapped
                    // to accomodate that!
                    UIColor *defaultHighlighterColor = [UIColor orangeColor];
                    const CGFloat *components = CGColorGetComponents(defaultHighlighterColor.CGColor);
                    self.colorComponentRed = components[0];
                    self.colorComponentGreen = components[1];
                    self.colorComponentBlue = components[2];
                }
                break;
            case DGSKDrawToolTypeEraser:
                // The default, parameterless init call sets these up properly.
                // Setting the value here would be harmless and redundant, so
                // not placing here to save a few minimal processor cycles.
                break;
            default:
                break;
        }

        self.effectsEngine = effectsEngine;
    }
    return self;
}

- (void) encodeWithCoder:(NSCoder *)coder
{
    [super encodeWithCoder:coder];

    [coder encodeFloat:self.colorComponentAlpha forKey:ENCODING_PROPERTY_COLOR_ALPHA];
    [coder encodeFloat:self.colorComponentRed forKey:ENCODING_PROPERTY_COLOR_RED];
    [coder encodeFloat:self.colorComponentGreen forKey:ENCODING_PROPERTY_COLOR_GREEN];
    [coder encodeFloat:self.colorComponentBlue forKey:ENCODING_PROPERTY_COLOR_BLUE];
}

- (id) initWithCoder:(NSCoder *)decoder
{
    self = [super initWithCoder:decoder];
    if (self)
    {
        _colorComponentAlpha = [decoder decodeFloatForKey:ENCODING_PROPERTY_COLOR_ALPHA];
        _colorComponentRed = [decoder decodeFloatForKey:ENCODING_PROPERTY_COLOR_RED];
        _colorComponentGreen = [decoder decodeFloatForKey:ENCODING_PROPERTY_COLOR_GREEN];
        _colorComponentBlue = [decoder decodeFloatForKey:ENCODING_PROPERTY_COLOR_BLUE];
    }
    return self;
}

- (UIColor *) color
{
    UIColor *activeColor = [UIColor colorWithRed:(self.colorComponentRed) green:(self.colorComponentGreen) blue:(self.colorComponentBlue) alpha:DRAW_CONTEXT_STYLE_DEFAULT_COLOR_ALPHA];
    return [self applyStyleToProvidedColor:activeColor];
}

- (void) setColor:(UIColor *)color
{
    if (CGColorGetNumberOfComponents(color.CGColor) == 4)
    {
        const CGFloat *colorComponents = CGColorGetComponents(color.CGColor);
        //self.colorComponentAlpha = colorComponents[3]; // Highlighter manages alpha
        self.colorComponentRed = colorComponents[0];
        self.colorComponentGreen = colorComponents[1];
        self.colorComponentBlue = colorComponents[2];
    }
    // Monochromatic colors
    else if (CGColorGetNumberOfComponents(color.CGColor) == 2)
    {
        // Monochromatic colors (black-to-white with grayscale in between)
        // are represented by the same scale value across red, green, and blue.
        const CGFloat *colorComponents = CGColorGetComponents(color.CGColor);
        //self.colorComponentAlpha = colorComponents[1]; // Highlighter manages alpha
        self.colorComponentRed = colorComponents[0];
        self.colorComponentGreen = colorComponents[0];
        self.colorComponentBlue = colorComponents[0];
    }
}

- (UIColor *) applyStyleToProvidedColor:(UIColor *)color
{
    [self.effectsEngine applyEffectsBasedOnPoints:nil toStylingProvider:self];

    CGFloat redComponent = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_RED;
    CGFloat greenComponent = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_GREEN;
    CGFloat blueComponent = DRAW_CONTEXT_STYLE_DEFAULT_COLOR_BLUE;

    const CGFloat *components = CGColorGetComponents(color.CGColor);
    if(CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelMonochrome)
    {
        redComponent = components[0];
        greenComponent = components[0];
        blueComponent = components[0];
    }
    else if(CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelRGB)
    {
        redComponent = components[0];
        greenComponent = components[1];
        blueComponent = components[2];
    }
    // NOTE: The eraser tool will essentially have a transparent color.  If the UI of the application intends to
    // provide a visual indicator for the eraser tool based on the color, the caller is responsible for substituting
    // the appropriate visual indicator to the application UI.
    UIColor *styledColor = [UIColor colorWithRed:(redComponent) green:(greenComponent) blue:(blueComponent) alpha:self.colorComponentAlpha];
    return styledColor;
}

- (bool) applyPropertiesToContext:(CGContextRef)context
{
    if ([super applyPropertiesToContext:context])
    {
        CGColorSpaceRef colorspace = [self CreateStylingColorSpace]();
        CGFloat components[] = {self.colorComponentRed, self.colorComponentGreen, self.colorComponentBlue, self.colorComponentAlpha};
        CGColorRef color = CGColorCreate(colorspace, components);
        CGContextSetStrokeColorWithColor(context, color);

        CGColorSpaceRelease(colorspace);
        CGColorRelease(color);

        return true;
    }
    else
    {
        return false;
    }
}

- (void) applyToolType:(DGSKDrawToolType)toolType
{
    [super applyToolType:toolType];
}

@end


text:
layout: post
title:  Change Extension
categories: XAP97
parent: change-api.html
weight: 200
---

{% summary %}This page covers the Change API, its usage and behavior.{% endsummary %}

# Overview

The `ChangeExtension` provides utility methods on top of the [Change API](./change-api.html) that simplify the common use cases of the `change` operation.

# Add and Get operation

A common usage pattern is to increment a numeric property of a specific entry and needing the updated value after the increment was applied.
Using the `addAndGet` operation you can do that using one method call and get an atomic add and get operation semantics.
Following is an example of incrementing a property named `counter` inside an entry of type `WordCount`:

{% highlight java %}
GigaSpace space = // ... obtain a space reference
Uuid id = ...;
IdQuery<WordCount> idQuery = new IdQuery<WordCount>(WordCount.class, id, routing);
Integer newCounter = ChangeExtension.addAndGet(space, idQuery, "counter", 1);
{% endhighlight %}

You should use the primitive wrapper types as the operation semantic is to return null if there is no object matching the provided id query

{% info %}You can use `import static org.openspaces.extensions.ChangeExtension.` in order to remove the need to prefix the call with `ChangeExtension'.{% endinfo %}


text:
/* DO NOT EDIT - THIS FILE GENERATED BY THE state_isenabled.py SCRIPT */
#include <stdio.h>
#include <math.h>

#include "state.h"
#include "state/cr_statetypes.h"

GLboolean STATE_APIENTRY crStateIsEnabled( GLenum pname )
{
	CRContext *g = GetCurrentContext();

	if (g->current.inBeginEnd)
	{
		crStateError(__LINE__, __FILE__, GL_INVALID_OPERATION, "glGet called in Begin/End");
		return 0;
	}

    switch ( pname ) {

	case GL_ALPHA_TEST:
		return g->buffer.alphaTest;
	case GL_AUTO_NORMAL:
		return g->eval.autoNormal;
	case GL_BLEND:
		return g->buffer.blend;
	case GL_CLIP_PLANE0:
		return g->transform.clip[0];
	case GL_CLIP_PLANE1:
		return g->transform.clip[1];
	case GL_CLIP_PLANE2:
		return g->transform.clip[2];
	case GL_CLIP_PLANE3:
		return g->transform.clip[3];
	case GL_CLIP_PLANE4:
		return g->transform.clip[4];
	case GL_CLIP_PLANE5:
		return g->transform.clip[5];
	case GL_COLOR_LOGIC_OP:
		return g->buffer.logicOp;
	case GL_COLOR_MATERIAL:
		return GL_FALSE;
	case GL_COLOR_SUM_EXT:
		return g->lighting.colorSumEXT;
	case GL_CULL_FACE:
		return g->polygon.cullFace;
	case GL_DEPTH_TEST:
		return g->buffer.depthTest;
	case GL_DEPTH_WRITEMASK:
		return g->buffer.depthMask;
	case GL_DITHER:
		return g->buffer.dither;
	case GL_FOG:
		return g->fog.enable;
	case GL_INDEX_LOGIC_OP:
		return g->buffer.indexLogicOp;
	case GL_LIGHT0:
		return g->lighting.light[0].enable;
	case GL_LIGHT1:
		return g->lighting.light[1].enable;
	case GL_LIGHT2:
		return g->lighting.light[2].enable;
	case GL_LIGHT3:
		return g->lighting.light[3].enable;
	case GL_LIGHT4:
		return g->lighting.light[4].enable;
	case GL_LIGHT5:
		return g->lighting.light[5].enable;
	case GL_LIGHT6:
		return g->lighting.light[6].enable;
	case GL_LIGHT7:
		return g->lighting.light[7].enable;
	case GL_LIGHTING:
		return g->lighting.lighting;
	case GL_LINE_SMOOTH:
		return g->line.lineSmooth;
	case GL_LINE_STIPPLE:
		return g->line.lineStipple;
	case GL_MAP1_COLOR_4:
		return g->eval.enable1D[GL_MAP1_COLOR_4-GL_MAP1_COLOR_4];
	case GL_MAP1_INDEX:
		return g->eval.enable1D[GL_MAP1_INDEX-GL_MAP1_COLOR_4];
	case GL_MAP1_NORMAL:
		return g->eval.enable1D[GL_MAP1_NORMAL-GL_MAP1_COLOR_4];
	case GL_MAP1_TEXTURE_COORD_1:
		return g->eval.enable1D[GL_MAP1_TEXTURE_COORD_1-GL_MAP1_COLOR_4];
	case GL_MAP1_TEXTURE_COORD_2:
		return g->eval.enable1D[GL_MAP1_TEXTURE_COORD_2-GL_MAP1_COLOR_4];
	case GL_MAP1_TEXTURE_COORD_3:
		return g->eval.enable1D[GL_MAP1_TEXTURE_COORD_3-GL_MAP1_COLOR_4];
	case GL_MAP1_TEXTURE_COORD_4:
		return g->eval.enable1D[GL_MAP1_TEXTURE_COORD_4-GL_MAP1_COLOR_4];
	case GL_MAP1_VERTEX_3:
		return g->eval.enable1D[GL_MAP1_VERTEX_3-GL_MAP1_COLOR_4];
	case GL_MAP1_VERTEX_4:
		return g->eval.enable1D[GL_MAP1_VERTEX_4-GL_MAP1_COLOR_4];
	case GL_MAP2_COLOR_4:
		return g->eval.enable2D[GL_MAP2_COLOR_4-GL_MAP2_COLOR_4];
	case GL_MAP2_INDEX:
		return g->eval.enable2D[GL_MAP2_INDEX-GL_MAP2_COLOR_4];
	case GL_MAP2_NORMAL:
		return g->eval.enable2D[GL_MAP2_NORMAL-GL_MAP2_COLOR_4];
	case GL_MAP2_TEXTURE_COORD_1:
		return g->eval.enable2D[GL_MAP2_TEXTURE_COORD_1-GL_MAP2_COLOR_4];
	case GL_MAP2_TEXTURE_COORD_2:
		return g->eval.enable2D[GL_MAP2_TEXTURE_COORD_2-GL_MAP2_COLOR_4];
	case GL_MAP2_TEXTURE_COORD_3:
		return g->eval.enable2D[GL_MAP2_TEXTURE_COORD_3-GL_MAP2_COLOR_4];
	case GL_MAP2_TEXTURE_COORD_4:
		return g->eval.enable2D[GL_MAP2_TEXTURE_COORD_4-GL_MAP2_COLOR_4];
	case GL_MAP2_VERTEX_3:
		return g->eval.enable2D[GL_MAP2_VERTEX_3-GL_MAP2_COLOR_4];
	case GL_MAP2_VERTEX_4:
		return g->eval.enable2D[GL_MAP2_VERTEX_4-GL_MAP2_COLOR_4];
	case GL_NORMALIZE:
		return g->transform.normalize;
	case GL_PACK_LSB_FIRST:
		return g->client.pack.psLSBFirst;
	case GL_PACK_SWAP_BYTES:
		return g->client.pack.swapBytes;
	case GL_PER_STAGE_CONSTANTS_NV:
		return g->regcombiner.enabledPerStageConstants;
	case GL_POINT_SMOOTH:
		return g->point.pointSmooth;
	case GL_POLYGON_OFFSET_FILL:
		return g->polygon.polygonOffsetFill;
	case GL_POLYGON_OFFSET_LINE:
		return g->polygon.polygonOffsetLine;
	case GL_POLYGON_OFFSET_POINT:
		return g->polygon.polygonOffsetPoint;
	case GL_POLYGON_SMOOTH:
		return g->polygon.polygonSmooth;
	case GL_POLYGON_STIPPLE:
		return g->polygon.polygonStipple;
	case GL_REGISTER_COMBINERS_NV:
		return g->regcombiner.enabledRegCombiners;
	case GL_RGBA_MODE:
		return GL_TRUE;
	case GL_SCISSOR_TEST:
		return g->viewport.scissorTest;
	case GL_STENCIL_TEST:
		return g->stencil.stencilTest;
	case GL_TEXTURE_1D:
		return g->texture.unit[g->texture.curTextureUnit].enabled1D;
	case GL_TEXTURE_2D:
		return g->texture.unit[g->texture.curTextureUnit].enabled2D;
	case GL_TEXTURE_CUBE_MAP_ARB:
		return g->texture.unit[g->texture.curTextureUnit].enabledCubeMap;
	case GL_TEXTURE_GEN_Q:
		return g->texture.unit[g->texture.curTextureUnit].textureGen.q;
	case GL_TEXTURE_GEN_R:
		return g->texture.unit[g->texture.curTextureUnit].textureGen.r;
	case GL_TEXTURE_GEN_S:
		return g->texture.unit[g->texture.curTextureUnit].textureGen.s;
	case GL_TEXTURE_GEN_T:
		return g->texture.unit[g->texture.curTextureUnit].textureGen.t;
	case GL_UNPACK_LSB_FIRST:
		return g->client.unpack.psLSBFirst;
	case GL_UNPACK_SWAP_BYTES:
		return g->client.unpack.swapBytes;
#ifdef CR_EXT_fog_coord
	case GL_FOG_COORDINATE_ARRAY_EXT:
		return g->client.array.f.enabled;
#endif /* CR_EXT_fog_coord */
#ifdef CR_ARB_fragment_program
	case GL_FRAGMENT_PROGRAM_ARB:
		return g->program.fpEnabledARB;
#endif /* CR_ARB_fragment_program */
#ifdef CR_NV_fragment_program
	case GL_FRAGMENT_PROGRAM_NV:
		return g->program.fpEnabled;
#endif /* CR_NV_fragment_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB0_4_NV:
		return g->eval.enableAttrib1D[0];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB10_4_NV:
		return g->eval.enableAttrib1D[10];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB11_4_NV:
		return g->eval.enableAttrib1D[11];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB12_4_NV:
		return g->eval.enableAttrib1D[12];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB13_4_NV:
		return g->eval.enableAttrib1D[13];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB14_4_NV:
		return g->eval.enableAttrib1D[14];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB15_4_NV:
		return g->eval.enableAttrib1D[15];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB1_4_NV:
		return g->eval.enableAttrib1D[1];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB2_4_NV:
		return g->eval.enableAttrib1D[2];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB3_4_NV:
		return g->eval.enableAttrib1D[3];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB4_4_NV:
		return g->eval.enableAttrib1D[4];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB5_4_NV:
		return g->eval.enableAttrib1D[5];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB6_4_NV:
		return g->eval.enableAttrib1D[6];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB7_4_NV:
		return g->eval.enableAttrib1D[7];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB8_4_NV:
		return g->eval.enableAttrib1D[8];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP1_VERTEX_ATTRIB9_4_NV:
		return g->eval.enableAttrib1D[9];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB0_4_NV:
		return g->eval.enableAttrib2D[0];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB10_4_NV:
		return g->eval.enableAttrib2D[10];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB11_4_NV:
		return g->eval.enableAttrib2D[11];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB12_4_NV:
		return g->eval.enableAttrib2D[12];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB13_4_NV:
		return g->eval.enableAttrib2D[13];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB14_4_NV:
		return g->eval.enableAttrib2D[14];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB15_4_NV:
		return g->eval.enableAttrib2D[15];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB1_4_NV:
		return g->eval.enableAttrib2D[1];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB2_4_NV:
		return g->eval.enableAttrib2D[2];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB3_4_NV:
		return g->eval.enableAttrib2D[3];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB4_4_NV:
		return g->eval.enableAttrib2D[4];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB5_4_NV:
		return g->eval.enableAttrib2D[5];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB6_4_NV:
		return g->eval.enableAttrib2D[6];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB7_4_NV:
		return g->eval.enableAttrib2D[7];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB8_4_NV:
		return g->eval.enableAttrib2D[8];
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_MAP2_VERTEX_ATTRIB9_4_NV:
		return g->eval.enableAttrib2D[9];
#endif /* CR_NV_vertex_program */
#ifdef CR_ARB_multisample
	case GL_MULTISAMPLE_ARB:
		return g->multisample.enabled;
#endif /* CR_ARB_multisample */
#ifdef CR_IBM_rasterpos_clip
	case GL_RASTER_POSITION_UNCLIPPED_IBM:
		return g->transform.rasterPositionUnclipped;
#endif /* CR_IBM_rasterpos_clip */
#ifdef CR_OPENGL_VERSION_1_2
	case GL_RESCALE_NORMAL:
		return g->transform.rescaleNormals;
#endif /* CR_OPENGL_VERSION_1_2 */
#ifdef CR_ARB_multisample
	case GL_SAMPLE_ALPHA_TO_COVERAGE_ARB:
		return g->multisample.sampleAlphaToCoverage;
#endif /* CR_ARB_multisample */
#ifdef CR_ARB_multisample
	case GL_SAMPLE_ALPHA_TO_ONE_ARB:
		return g->multisample.sampleAlphaToOne;
#endif /* CR_ARB_multisample */
#ifdef CR_ARB_multisample
	case GL_SAMPLE_COVERAGE_ARB:
		return g->multisample.sampleCoverage;
#endif /* CR_ARB_multisample */
#ifdef CR_EXT_secondary_color
	case GL_SECONDARY_COLOR_ARRAY_EXT:
		return g->client.array.s.enabled;
#endif /* CR_EXT_secondary_color */
#ifdef CR_OPENGL_VERSION_1_2
	case GL_TEXTURE_3D:
		return g->texture.unit[g->texture.curTextureUnit].enabled3D;
#endif /* CR_OPENGL_VERSION_1_2 */
#ifdef CR_NV_texture_rectangle
	case GL_TEXTURE_RECTANGLE_NV:
		return g->texture.unit[g->texture.curTextureUnit].enabledRect;
#endif /* CR_NV_texture_rectangle */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY0_NV:
		return g->client.array.a[0].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY10_NV:
		return g->client.array.a[10].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY11_NV:
		return g->client.array.a[11].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY12_NV:
		return g->client.array.a[12].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY13_NV:
		return g->client.array.a[13].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY14_NV:
		return g->client.array.a[14].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY15_NV:
		return g->client.array.a[15].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY1_NV:
		return g->client.array.a[1].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY2_NV:
		return g->client.array.a[2].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY3_NV:
		return g->client.array.a[3].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY4_NV:
		return g->client.array.a[4].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY5_NV:
		return g->client.array.a[5].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY6_NV:
		return g->client.array.a[6].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY7_NV:
		return g->client.array.a[7].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY8_NV:
		return g->client.array.a[8].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_ATTRIB_ARRAY9_NV:
		return g->client.array.a[9].enabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_PROGRAM_NV:
		return g->program.vpEnabled;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_PROGRAM_POINT_SIZE_NV:
		return g->program.vpPointSize;
#endif /* CR_NV_vertex_program */
#ifdef CR_NV_vertex_program
	case GL_VERTEX_PROGRAM_TWO_SIDE_NV:
		return g->program.vpTwoSide;
#endif /* CR_NV_vertex_program */
	default:
		crStateError(__LINE__, __FILE__, GL_INVALID_ENUM, "glIsEnabled: Unknown enum: %d", pname);
		return 0;
	}
}


text:
Variables to `theme` the terra-demographics-banner component.

| Variable Name                       | Default value   | Usage                                                        |
|-------------------------------------|-----------------|--------------------------------------------------------------|
| $demographics-background            | $terra-blue-100 | Background of the Demographics Banner.                       |
| $demographics-foreground            | $terra-white    | Foreground of the Demographics Banner.                       |
| $demographics-background-deceased   | $terra-dark     | Background of the Demographics Banner for a deceased person. |
| $demographics-foreground-deceased   | $terra-white    | Foreground of the Demographics Banner for a deceased person. |


text:
package javax.swing.plaf;

/**
 * Pluggable look and feel interface for JTable.
 *
 * @author Alan Chung
 */
public abstract class TableUI extends ComponentUI {
    /**
     * Constructor for subclasses to call.
     */
    protected TableUI() {}
}


text:
import React, { Component } from 'react';
import './options.css';

import GpsOrManual from "./components/GpsOrManual"
import LocationInput from "./components/LocationInput"

class Options extends Component {
  state = {
    component: "gpsOrManual"
  }
  toggleComponent = (component) => () => {
    this.setState({
      component
    })
  }
  render() {
    const components = {
      gpsOrManual: (
        <GpsOrManual
          onOptionClick={this.toggleComponent}
          mobile={this.props.mobile}
        />
      ),
      location: (
        <LocationInput
          onOptionClick={this.toggleComponent}
          goToMap={this.props.goToMap}
          mobile={this.props.mobile}
        />
      ),
    }
    return (
      <div className="options-container">
        {
          components[this.state.component]
        }
      </div>
    );
  }
}

export default Options


text:
from __future__ import print_function
import six
from six.moves.urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
import re

default_server = 'http://dmp.climate-cms.org:3000'

class DMPOnline(object):
    """
    A connection to DMPonline
    """
    plan_re = re.compile('.*/projects/(?P<project_id>[^/]+)/plans/(?P<plan_id>[^/]+)/edit$')

    def __init__(self, server = default_server):
        self.server = server
        self._projects_cache = None
        self.session = requests.Session()

    def login(self, email, password):
        """
        Log in to DMPOnline
        """
        r = self._get('users/sign_in')
        soup = BeautifulSoup(r.text, 'html.parser')
        token = soup.find('input', attrs={'name':'authenticity_token'})['value']
        r = self._post('users/sign_in',
                data={'user[email]': email,
                    'user[password]': password,
                    'authenticity_token': token})

    def projects(self):
        """
        Get the available projects
        """
        if self._projects_cache is None:
            r = self._get('projects.json')
            self._projects_cache = [Project(self, p) for p in r.json()]
        return self._projects_cache

    def project(self, id):
        """
        Get a single project given the ID

        :param id: Project ID
        """
        r = self.get('projects/%s.json'%id)
        return Project(self, r.json())

    def requests(self):
        """
        Get the available requests
        """
        if self._requests_cache is None:
            r = self._get('requests.json')
            self._requests_cache = [Request(self, p) for p in r.json()]
        return self._requests_cache

    def request(self, id):
        """
        Get a single request given the ID

        :param id: Request ID
        """
        r = self.get('requests/%s.json'%id)
        return Project(self, r.json())

    def _post(self, url, **kwargs):
        fullurl = urljoin(self.server, url)
        r = self.session.post(fullurl, **kwargs)
        try:
            r.raise_for_status()
        except requests.HTTPError:
            print(r.headers)
            raise

        return r

    def _get(self, url, **kwargs):
        fullurl = urljoin(self.server, url)
        r = self.session.get(fullurl, **kwargs)
        try:
            r.raise_for_status()
        except requests.HTTPError:
            print(r.request.headers)
            print(r.headers)
            raise
        return r

class Project(object):
    """
    A DMPOnline project

    Contains the same attributes as you'll find in DMPOnline's ``/projects.json``
    """

    def __init__(self, server, json):
        self.server = server
        # Set attributes automatically from the Json
        [setattr(self, k, v) for k, v in six.iteritems(json)]
        self.json = json

    def __str__(self):
        return self.title

    def __repr__(self):
        return '<%s>'%self.url

    @property
    def url_path(self):
        return 'projects/%s'%self.slug

    @property
    def url(self):
        return urljoin(self.server.server, self.url_path)

    def plan_urls(self):
        """
        Returns the plans attached to this project as a dictionary
        """
        _plans = {}

        # Get the tab links
        r = self.server._get(self.url_path)
        soup = BeautifulSoup(r.text, 'html.parser')
        links = soup.find(id='project-tabs').find_all('a')

        # Get the plan URLs
        for link in links:
            match = plan_re.match(link.href)
            if match is not None:
                plan_id = match.groupdict()['plan_id']
                _plans[link.text] = '%s/plans/%s'%(self.url_path, plan_id)
        return _plans

    def export_plans(form):
        """
        Export this project's plans

        :param str form: Output format
        """
        urls = self.plan_urls()
        _plans = {}

        for k, v in six.iteritems(urls):
            if form in ['json', 'xml', 'text', 'csv']:
                _plans[k] = self.server._get('%s/export'%v, data={'format': form}).text
            else:
                _plans[k] = self.server._get('%s/export'%v, data={'format': form}).content
        return _plans


text:
package global.namespace.truelicense.api.passwd;

/** Enumerates the password usages. */
public enum PasswordUsage {

    /** The password will be used to decrypt or verify some content. */
    DECRYPTION,

    /**
     * The password will be used to encrypt or sign some content.
     * This may trigger some additional checks, e.g. compliance to a
     * {@link PasswordPolicy}.
     */
    ENCRYPTION
}


text:
package com.example.core.model.more_movie_list.box_office;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class BoxOffice implements Parcelable
{

    @SerializedName("revenue")
    @Expose
    private Double revenue;
    @SerializedName("movie")
    @Expose
    private Movie movie;
    public final static Creator<BoxOffice> CREATOR = new Creator<BoxOffice>() {

        @SuppressWarnings({
            "unchecked"
        })
        public BoxOffice createFromParcel(Parcel in) {
            BoxOffice instance = new BoxOffice();
            instance.revenue = ((Double) in.readValue((Integer.class.getClassLoader())));
            instance.movie = ((Movie) in.readValue((Movie.class.getClassLoader())));
            return instance;
        }

        public BoxOffice[] newArray(int size) {
            return (new BoxOffice[size]);
        }

    }
    ;

    public Double getRevenue() {
        return revenue;
    }

    public void setRevenue(Double revenue) {
        this.revenue = revenue;
    }

    public Movie getMovie() {
        return movie;
    }

    public void setMovie(Movie movie) {
        this.movie = movie;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(revenue);
        dest.writeValue(movie);
    }

    public int describeContents() {
        return  0;
    }

}


text:
package com.company;

import java.io.Closeable;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * An iterator class to input specific data types from an input stream without throwing any
 * exceptions.  If there are any errors during use of the iterator then a message is output to
 * the standard output and the program terminates.
 *

 *
This is just a simple wrapper around Scanner that implements a subset of the
 * Scanner public interface.

 *

 *
This class is useful for people new to Java since it allows them to write programs using
 * input without having to fully understand the read / parse / handle exceptions model of the
 * standard Java classes and in particular Scanner.  So once exceptions and object
 * chaining are covered this class ought not to be used, it is definitely just an "early
 * stepping stone" utility class for initial learning.

 *
 * @author Russel Winder
 * @version 2004-12-16
 */
public class Input implements Closeable, Iterator<String>
{
    /**
     * A reference to the associated Scanner that supplies all the actual input
     * functionality.
     *

     *
This is protected and not final rather than private and final (as we might have
     * expected it to be) so that FileInput can access the variable.  This is
     * necessary because FileInput needs to capture all exceptions that can happen
     * during construction, which means that the super constructor call cannot be
     * used.  This appears to be something of a misfeature of Java.

     */
    protected Scanner scanner;

    /**
     * The default constructor of an Input that assumes System.in is to
     * be the InputStream used.
     */
    public Input()
    {
        this(System.in);
    }

    /**
     * Constructor of an Input object given an InputStream object.
     */
    public Input(final InputStream in)
    {
        scanner = new Scanner(in);
    }

    /**
     * A finalizer to ensure all files are closed if an Input object is garbage
     * collected.
     */
    public void finalize()
    {
        close();
    }

    /**
     * Close the file when finished with it.
     */
    public void close()
    {
        scanner.close();
    }

    /**
     * @return true if there is more input, false otherwise.
     */
    public boolean hasNext()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNext();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next token (sequence of characters terminated by a whitespace) in the input
     * stream.
     */
    public String next()
    {
        String returnValue = null;
        try
        {
            returnValue = scanner.next();
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * This operation is required in order to conform to Iterator<String> but is
     * not supported.  Normally an UnsupportedOperationException would be thrown to
     * indicate this situation but the whole point is not to throw exceptions so this is simply a
     * "do nothing" method.
     */
    public void remove()
    {
    }

    /**
     * NB This method currently has a mis-feature in that it returns false incorrectly when there
     * is a single end-of-line left in the file.
     *
     * @return true if there is a char to input, false
     * otherwise.
     */
    public boolean hasNextChar()
    {

        //  Why doesn't this work, it used to.

        //boolean returnValue = false ;
        //try { returnValue = scanner.hasNext ( "(?s)." ) ; }
        //catch ( IllegalStateException e ) { illegalStateExceptionHandler ( ) ; }
        //return returnValue ;

        return hasNext();
    }

    /**
     * @return the next char in the input stream.
     */
    public char nextChar()
    {
        char returnValue = '\0';
        try
        {
            returnValue = scanner.findWithinHorizon("(?s).", 1).charAt(0);
        }
        catch (IllegalArgumentException iae)
        {
            //  This cannot happen as it is clear in the statement that the horizon is 1 which is > 0 and
            //  this exception only happens for negative horizons.
            System.exit(1);
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is an int to input, false
     * otherwise.
     */
    public boolean hasNextInt()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextInt();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next int in the input stream assumed to be in the default radix
     * which is 10.
     */
    public int nextInt()
    {
        int returnValue = 0;
        try
        {
            returnValue = scanner.nextInt();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("int");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @param radix the radix of the input.
     * @return the next int in the input stream using the radix
     * radix.
     */
    public int nextInt(final int radix)
    {
        int returnValue = 0;
        try
        {
            returnValue = scanner.nextInt(radix);
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("int");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is a long to input, false
     * otherwise.
     */
    public boolean hasNextLong()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextLong();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next long in the input stream assumed to be in the default radix
     * which is 10.
     */
    public long nextLong()
    {
        long returnValue = 0;
        try
        {
            returnValue = scanner.nextLong();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("long");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @param radix the radix of the input sequence.
     * @return the next long in the input stream using the radix
     * radix.
     */
    public long nextLong(final int radix)
    {
        long returnValue = 0;
        try
        {
            returnValue = scanner.nextLong(radix);
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("long");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is a BigInteger to input, false
     * otherwise.
     */
    public boolean hasNextBigInteger()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextBigInteger();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next BigInteger in the input stream assumed to be in the default
     * radix which is 10.
     */
    public BigInteger nextBigInteger()
    {
        BigInteger returnValue = new BigInteger("0");
        try
        {
            returnValue = scanner.nextBigInteger();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("BigInteger");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @param radix the radix of the input sequence.
     * @return the next BigInteger in the input stream using the radix
     * radix</code.
     */
    public BigInteger nextBigInteger(final int radix)
    {
        BigInteger returnValue = new BigInteger("0");
        try
        {
            returnValue = scanner.nextBigInteger(radix);
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("BigInteger");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is a float to input, false
     * otherwise.
     */
    public boolean hasNextFloat()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextFloat();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next float in the input stream.
     */
    public float nextFloat()
    {
        float returnValue = 0;
        try
        {
            returnValue = scanner.nextFloat();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("float");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is a double to input, false
     * otherwise.
     */
    public boolean hasNextDouble()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextDouble();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next double in the input stream.
     */
    public double nextDouble()
    {
        double returnValue = 0;
        try
        {
            returnValue = scanner.nextDouble();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("double");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is a BigDecimal to input,
     * false otherwise.
     */
    public boolean hasNextBigDecimal()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextBigDecimal();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return the next BigDecimal in the input stream.
     */
    public BigDecimal nextBigDecimal()
    {
        BigDecimal returnValue = new BigDecimal("0");
        try
        {
            returnValue = scanner.nextBigDecimal();
        }
        catch (InputMismatchException ime)
        {
            inputMismatchExceptionHandler("BigDecimal");
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return true if there is more input including an end of line marker,
     * false otherwise.
     */
    public boolean hasNextLine()
    {
        boolean returnValue = false;
        try
        {
            returnValue = scanner.hasNextLine();
        }
        catch (IllegalStateException e)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * @return all the characters in the input stream up to and including the next end of line
     * marker in the input stream.
     */
    public String nextLine()
    {
        String returnValue = null;
        try
        {
            returnValue = scanner.nextLine();
        }
        catch (NoSuchElementException nsee)
        {
            noSuchElementHandler();
        }
        catch (IllegalStateException ise)
        {
            illegalStateExceptionHandler();
        }
        return returnValue;
    }

    /**
     * The method to handle an IllegalStateException.
     */
    private void illegalStateExceptionHandler()
    {
        System.err.println("Input has been closed.");
        System.exit(1);
    }

    /**
     * The method to handle an InputMismatchException.
     */
    private void inputMismatchExceptionHandler(final String type)
    {
        System.err.println("Input did not represent " +
                (type.equals("int") ? "an" : "a") + " " + type + " value.");
        System.exit(1);
    }

    /**
     * The method to handle an NoSuchElementException.
     */
    private void noSuchElementHandler()
    {
        System.err.println("No input to be read.");
        System.exit(1);
    }
}


text:
> 前后端分离,文档非常重要。自己写的文档,有一定的滞后性,而DRF提供了强大的自动文档功能。

项目url配置文件:

```python
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.documentation import include_docs_urls

urlpatterns = [
    url(r'^admin', admin.site.urls),
    url(r'^api/1.0/', include('devops.urls.api', namespace='api')),
    url(r'^docs/', include_docs_urls(title="DevOps API文档")),
]
```


text:
require('browsernizr/test/touchevents');
require('browsernizr/lib/prefixed');
var Modernizr = require('browsernizr');

var Effeckt = {

  isTouchDevice: Modernizr.touch,
  buttonPressedEvent: ( this.isTouchDevice ) ? 'touchstart' : 'click',

  animationEndEventNames: {
    'WebkitAnimation' : 'webkitAnimationEnd',
    'OAnimation' : 'oAnimationEnd',
    'msAnimation' : 'MSAnimationEnd',
    'animation' : 'animationend'
  },

  transitionEndEventNames: {
    'WebkitTransition' : 'webkitTransitionEnd',
    'OTransition' : 'oTransitionEnd',
    'msTransition' : 'MSTransitionEnd',
    'transition' : 'transitionend'
  },

  init: function() {

    //event trigger after animation/transition end.
    this.transitionEndEventName = this.transitionEndEventNames[Modernizr.prefixed('transition')];
    this.animationEndEventName = this.animationEndEventNames[Modernizr.prefixed('animation')];
    this.transitionAnimationEndEvent = this.animationEndEventName + ' ' + this.transitionEndEventName;

  }
};

Effeckt.init();

module.exports = Effeckt;