text:
let currentDateActual = new Date(new Date().getTime() + -(new Date().getTimezoneOffset() / 60) * 3600 * 1000);
console.log("Running HN_Vimmy_Bot Scan: " + currentDateActual);

var request = require("request")
var Twitter = require("twitter")
var async = require('async');
var util = require('util');
var admin = require("firebase-admin");

var chatEmoji = '💬';
var linkEmoji = '🔗';

var shortUrl = require('node-url-shortener');

var client;
var searchTerm;
var locationIs;

if (new Date().getMinutes() < 30) {
    console.log("Loading VIM Profile");
    client = new Twitter({
        consumer_key: process.env.twitter_consumer_key,
        consumer_secret: process.env.twitter_consumer_secret,
        access_token_key: process.env.twitter_access_token_key,
        access_token_secret: process.env.twitter_access_token_secret
    });

    searchTerm = "vim";
    locationIs = "hnvimmybot";
} else {
    console.log("Loading Kotlin Profile");
    client = new Twitter({
        consumer_key: process.env.twitter_kotlin_consumer_key,
        consumer_secret: process.env.twitter_kotlin_consumer_secret,
        access_token_key: process.env.twitter_kotlin_access_token_key,
        access_token_secret: process.env.twitter_kotlin_access_token_secret
    });
    searchTerm = "kotlin"
    locationIs = "hnkotlinbot";
}

admin.initializeApp({
    credential: admin.credential.cert("/home/pi/newDayPi/HN_Vimmy_Bot/config/hnbot-8bb67-firebase-adminsdk-rszpo-c0cd32c24f.json"),
    // credential: admin.credential.cert("./config/hnbot-8bb67-firebase-adminsdk-rszpo-c0cd32c24f.json"),
    databaseURL: "https://hnbot-8bb67.firebaseio.com/"
});

var db = admin.database();
var ref = db.ref("/bots");

function grabDBSnapshot(callback) {
    ref.on("value", function (snapshot) {
        ref.off();
        callback(snapshot.val());
    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
        process.exit(1);
    });
};

function saveNewStory(botPWD, savePackage, saveCallback) {
    console.log("Saving User Infomation To Database");
    ref.child(botPWD).update(savePackage).then(function () {
        console.log("Successfully Saved User Info to Database");
        saveCallback();
    }).catch(function (error) {
        console.log("Firebase Error: " + error);
        saveCallback();
    });
}

// Async makes sure to keep callback straight
var q = async.queue(function (task, finalCallback) {
    async.waterfall([
        function (mainCallback) {
            request(task.url, { timeout: 8000 }, function (err, res, body) {
                if (err) {
                    console.log(util.inspect("Error in fetchStory " + err, false, null));
                    finalCallback();
                } else if (res.statusCode != 200) {
                    console.log(util.inspect("Error in fetchStory response not 200 " + res.statusCode, false, null));
                    finalCallback();
                } else {
                    mainCallback(null, body)
                }
            });
        },
        function (body, mainCallback) {
            var storyActualJSON = JSON.parse(body);

            // check title for stories with "vim" in the title
            var re = new RegExp("\\b" + searchTerm + "\\b", "gi");
            if (storyActualJSON.title.match(re)) {
                // shorten HN Link
                console.log("Found story on VIM: " + storyActualJSON.title);
                console.log("Shortening HN Discussion Link", storyActualJSON.id);
                shortUrl.short('https://news.ycombinator.com/item?id=' + storyActualJSON.id, function (err, url) {
                    // Shorten Story Link
                    if (err) {
                        console.log(util.inspect("Hacker News Link Error: " + err, false, null));
                        finalCallback();
                    } else {
                        console.log("Link Successfully Shortened");
                        mainCallback(null, storyActualJSON, url);
                    }
                })
            } else {
                // console.log("no match for " + storyActualJSON.title)
                finalCallback();
            }
        },
        function (storyActualJSON, hnLink, mainCallback) {
            console.log("Checking to see if story is \"ASK HN:\"");
            // check to see if post is "Ask HN:" and thus no story link
            if (storyActualJSON.url == undefined) {
                var outgoingTweet = storyActualJSON.title + "\n" + chatEmoji + ": " + hnLink + "\n#HackerNews #VIM";
                mainCallback(null, outgoingTweet);
            } else {
                console.log("Shortening Story Link");
                shortUrl.short(storyActualJSON.url, function (err, url) {
                    if (err) {
                        console.log(util.inspect("Story Link Error: " + err, false, null));
                        finalCallback();
                    } else {
                        console.log("Successfully Shortened Story Link");
                        var outgoingTweet = storyActualJSON.title + "\n" + chatEmoji + " " + hnLink + "\n" + linkEmoji + " " + url + "\n#HackerNews #" + searchTerm.toUpperCase();
                        mainCallback(null, outgoingTweet)
                    }
                })
            }
        },
        function (outgoingTweet, mainCallback) {
            console.log("Tweeting out Story");
            client.post('statuses/update', { status: outgoingTweet }, function (error, tweet, response) {
                if (!error && response.statusCode === 200) {
                    console.log("Just Successfully Tweeted");
                    mainCallback();
                } else if (error) {
                    console.log(util.inspect("Tweet Error: " + error, false, null));
                    finalCallback();
                } else {
                    finalCallback();
                }
            });
        },
        function (mainCallback) {
            let savePackage = {};
            savePackage[task.storyID] = { status: "sent" };
            saveNewStory(locationIs + "/", savePackage, function () {
                finalCallback();
            });
        },
    ]);
}, 10);

q.drain = function () {
    console.log("----------------------------------- SCAN COMPLETE -----------------------------------");
    process.exit(1);
};

// Grab top 500 stories
function fetchTopStories() {
    var postedStories = {};
    async.waterfall([
        function (outsideCallback) {
            grabDBSnapshot(function (snapshotOfDB) {
                postedStories[locationIs] = snapshotOfDB[locationIs]
                outsideCallback();
            });
        },
        function (outsideCallback) {
            request({
                url: "https://hacker-news.firebaseio.com/v0/topstories.json",
                json: true
            }, function (error, response, groupOfStories) {
                if (!error && response.statusCode === 200) {
                    let arrayOfStoryIDs = Object.keys(postedStories[locationIs]);

                    let cleanStoriesList = groupOfStories.filter(function (val) {
                        let stringVal = val.toString();
                        return arrayOfStoryIDs.indexOf(stringVal) == -1;
                    });

                    for (i = 0; i < cleanStoriesList.length; i++) {
                        // fetch actual story to check it's title
                        q.push({
                            url: 'https://hacker-news.firebaseio.com/v0/item/' + cleanStoriesList[i] + '.json', storyID: cleanStoriesList[i]
                        });
                    }
                    outsideCallback();
                } else {
                    console.log(util.inspect("Error on fetchTopStories: " + error, false, null));
                }
            })
        },
    ]);
}

// start script
fetchTopStories();


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/ll__place_operator"
  style="@style/PlacePageItemFrame"
  android:tag="operator"
  tools:background="#4000FFFF"
  tools:visibility="visible">

  <ImageView
    android:id="@+id/iv__place_operator"
    style="@style/PlacePageMetadataIcon"
    android:src="@drawable/ic_bank" />

  <TextView
    android:id="@+id/tv__place_operator"
    style="@style/PlacePageMetadataText"
    tools:text="Operator" />
</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
typedef enum {
  TRI_FULLTEXT_COMPLETE,
  TRI_FULLTEXT_PREFIX,
  TRI_FULLTEXT_SUBSTRING   // currently not implemented, maybe later
}
TRI_fulltext_query_match_e;

////////////////////////////////////////////////////////////////////////////////
/// @brief fulltext query logical operators
////////////////////////////////////////////////////////////////////////////////

typedef enum {
  TRI_FULLTEXT_AND,
  TRI_FULLTEXT_OR,
  TRI_FULLTEXT_EXCLUDE
}
TRI_fulltext_query_operation_e;

////////////////////////////////////////////////////////////////////////////////
/// @brief fulltext query
////////////////////////////////////////////////////////////////////////////////

typedef struct TRI_fulltext_query_s {
  size_t                          _numWords;
  char**                          _words;
  TRI_fulltext_query_match_e*     _matches;
  TRI_fulltext_query_operation_e* _operations;
}
TRI_fulltext_query_t;

// -----------------------------------------------------------------------------
// --SECTION--                                        constructors / destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief create a fulltext query
////////////////////////////////////////////////////////////////////////////////

TRI_fulltext_query_t* TRI_CreateQueryFulltextIndex (size_t);

////////////////////////////////////////////////////////////////////////////////
/// @brief free a fulltext query
////////////////////////////////////////////////////////////////////////////////

void TRI_FreeQueryFulltextIndex (TRI_fulltext_query_t*);

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief create a fulltext query from a query string
////////////////////////////////////////////////////////////////////////////////

int TRI_ParseQueryFulltextIndex (TRI_fulltext_query_t*,
                                 char const*,
                                 bool*);

////////////////////////////////////////////////////////////////////////////////
/// @brief set a search word & option for a query
/// the query will take ownership of the search word
/// the caller must not free the word itself
////////////////////////////////////////////////////////////////////////////////

bool TRI_SetQueryFulltextIndex (TRI_fulltext_query_t*,
                                size_t,
                                char const*,
                                size_t,
                                TRI_fulltext_query_match_e,
                                TRI_fulltext_query_operation_e);

#endif

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
var gulp = require('gulp')
var concat = require('gulp-concat')
var uglify = require('gulp-uglify')
var ngAnnotate = require('gulp-ng-annotate')

gulp.task('js', function () {
  gulp.src([
    'app/bower_components/angular/angular.js',
    'app/bower_components/angular-route/angular-route.js',
    'app/bower_components/angular-bootstrap/ui-bootstrap.js',
    'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
    'app/bower_components/lodash/dist/lodash.js',
    'app/bower_components/angular-google-maps/dist/angular-google-maps.js',
    'app/components/angular-ajax-tabs.js',
    'app/app.js',
    'app/customer_detail/*.js',
    '!**/*_test.js'
    ])
    .pipe(concat('dist.js'))
    // .pipe(ngAnnotate())
    // .pipe(uglify())
    .pipe(gulp.dest('.'))
})

gulp.task('watch', ['js'], function () {
  gulp.watch('app/**/*.js', ['js'])
})


text:
(function(sunlight, undefined){

	if (sunlight === undefined || sunlight["registerLanguage"] === undefined) {
		throw "Include sunlight.js before including language files";
	}

	sunlight.registerLanguage("haskell", {
		//http://www.haskell.org/haskellwiki/Keywords
		keywords: [
			"as","case","of","class","datafamily","datainstance","data","default","derivinginstance","deriving",
			"do","forall","foreign","hiding","if","then","else","import","infix","infixl","infixr","instance",
			"let","in","mdo","module","newtype","proc","qualified","rec","typefamily","typeinstance","type","where"
		],

		customParseRules: [
			//character literals, e.g. 'a'
			function(context) {
				var peek = context.reader.peek(),
					expectedEnd = 2,
					line = context.reader.getLine(),
					column = context.reader.getColumn();

				if (context.reader.current() !== "'" && peek !== "'") {
					return null;
				}

				//to differentiate from template haskell, we'll just assume that character literals
				//are exactly one character long (or two for \' and \\) and delimited by '

				if (peek && peek === "\\") {
					expectedEnd++;
				}

				if (!/'$/.test(context.reader.peek(expectedEnd))) {
					//doesn't end with an apostrophe, so it's a template operator
					return null;
				}

				return context.createToken("char", "'" + context.reader.read(expectedEnd), line, column);
			},

			//look for user defined functions
			function(context) {
				var peek,
					count = 0,
					ident,
					prevToken,
					line = context.reader.getLine(),
					column = context.reader.getColumn();

				//read the ident, if a :: operator follows it, then it's a function definition (i guess, like i know anything about haskell)
				//or if follows newtype, class or data, we keep track of it as well
				if (!/[A-Za-z_]/.test(context.reader.current())) {
					return null;
				}

				while ((peek = context.reader.peek(++count)) && peek.length === count) {
					if (!/[\w']$/.test(peek)) {
						break;
					}
				}

				ident = context.reader.current() + peek.substring(0, peek.length - 1);

				//if it follows class, newtype, type or data
				prevToken = context.token(context.count() - 1);
				if (prevToken && prevToken.name === "keyword" && sunlight.util.contains(["class", "newtype", "data", "type"], prevToken.value)) {
					context.items.userDefinedFunctions.push(ident);
					context.reader.read(ident.length - 1); //already read the first character
					return context.createToken("ident", ident, line, column);
				}

				//function definitions: start of line followed by ::
				if (context.reader.isSolWs()) {
					//should be some whitespace, and then ::
					while ((peek = context.reader.peek(++count)) && peek.length === count) {
						if (!/\s$/.test(peek)) {
							if (!/::$/.test(context.reader.peek(++count))) {
								return null;
							}

							//yay it's a function!

							context.items.userDefinedFunctions.push(ident);
							context.reader.read(ident.length - 1); //already read the first character
							return context.createToken("ident", ident, line, column);
						}
					}
				}

				return null;
			}
		],

		customTokens: {
			"function": {
				values: [
					"abs","acosh","acos","all","and","any","appendFile","asinh","asin","asTypeOf","atan2","atanh",
					"atan","break","catch","ceiling","compare","concatMap","concat","const","cosh","cos","curry",
					"cycle","decodeFloat","divMod","div","dropWhile","drop","either","elem","encodeFloat","enumFromThenTo",
					"enumFromThen","enumFromTo","enumFrom","error","even","exponent","exp","fail","filter","flip",
					"floatDigits","floatRadix","floatRange","floor","fmap","foldl1","foldl","foldr1","foldr","fromEnum",
					"fromInteger","fromIntegral","fromRational","fst","gcd","getChar","getContents","getLine","head",
					"id","init","interact","ioError","isDenormalized","isIEEE","isInfinite","isNaN","isNegativeZero",
					"iterate","last","lcm","length","lex","lines","logBase","log","lookup","mapM_","mapM","map",
					"maxBound","maximum","max","maybe","minBound","minimum","min","mod","negate","notElem","not",
					"null","odd","or","otherwise","pi","pred","print","product","properFraction","putChar","putStrLn",
					"putStr","quotRem","quot","readFile","readIO","readList","readLn","readParen","readsPrec","reads",
					"realToFrac","read","recip","rem","repeat","replicate","return","reverse","round","scaleFloat",
					"scanl1","scanl","scanr1","scanr","sequence_","sequence","seq","showChar","showList","showParen",
					"showsPrec","showString","shows","show","significand","signum","sinh","sin","snd","splitAt","sqrt",
					"subtract","succ","sum","tail","takeWhile","take","tanh","tan","toEnum","toInteger","toRational",
					"truncate","uncurry","undefined","unlines","until","unwords","unzip3","unzip","userError","words",
					"writeFile","zip3","zipWith3","zipWith","zip"
				],
				boundary: "\\b"
			},

			"class": {
				values: [
					"Bounded", "Enum", "Eq", "Floating", "Fractional", "Functor", "Integral", "Monad", "Num", "Ord",
					"Read", "RealFloat", "RealFrac", "Real", "Show"
				],
				boundary: "\\b"
			},

			"type": {
				values: [
					"Bool", "Char", "Double", "Either", "FilePath", "Float", "Integer", "Int", "IOError", "IO",
					"Maybe", "Ordering", "ReadS", "ShowS", "String",

					"False", "True", "LT", "GT", "EQ", "Nothing", "Just", "Left", "Right"
				],
				boundary: "\\b"
			}
		},

		scopes: {
			string: [ ["\"", "\"", sunlight.util.escapeSequences.concat(["\\\""])] ],
			comment: [ ["--", "\n", null, true], ["{-", "-}"] ],
			infixOperator: [ ["`", "`", ["\\`"]] ]
		},

		identFirstLetter: /[A-Za-z_]/,
		identAfterFirstLetter: /[\w']/,

		namedIdentRules: {
			custom: [
				function(context) {
					return sunlight.util.contains(context.items.userDefinedFunctions, context.tokens[context.index].value);
				}
			]
		},

		contextItems: {
			userDefinedFunctions: []
		},

		operators: [
			"::", ":",

			"=>", "==", "=",
			"@",
			"[|", "|]",
			"\\\\", "\\",
			"/=", "/",
			"++", "+",
			"-<<", "-<", "->", "-",
			"&&",

			"!!", "!",
			"''", "'",
			"??", "?",
			"#",
			"<-", "<=", "<",
			">@>", ">>=", ">>", ">=", ">",
			"^^", "^",
			"**", "*",
			"||", "|",
			"~",
			"_",
			"..", "."
		]
	});
}(this["Sunlight"]));


text:
<?php

/**
 * Created by PhpStorm.
 * User: huge
 * Date: 2017/2/26
 * Time: 13:31
 */
class Test_tof_model extends CI_Model
{
    /**
     * test_info:character_shape、picture_char、tof
     * @param $test_info
     * @return bool|CI_DB_active_record|CI_DB_result
     */
    public function insert_new_test($test_info){
        if(isset($test_info['character_shape'])&&isset($test_info['picture_char'])&&isset($test_info['tof'])){
            $this->load->model('Character_model');
            $relation_char=$this->Character_model->get_character_by_shape($test_info['character_shape']);
            $picture_char=$this->Character_model->get_character_by_shape($test_info['picture_char']);
            if($relation_char!=null&&$picture_char!=null){
                $data['tof']=$test_info['tof'];
                $data['relation_character_id']=$relation_char['ID'];
                $data['character_shape']=$relation_char['character_shape'];
                $data['picture']=$picture_char['ID'].'.jpg';
                return $this->db->insert('hzw_test_tof',$data);
            }
        }
        return false;
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JohnLambe.Util.Collections
{
    /*
    public class EnumerableCaster<TOut, TIn> : IEnumerable<TOut>
    {
        public EnumerableCaster(IEnumerable<TIn> inner)
        {
            _inner = inner;
        }

        protected IEnumerable<TIn> _inner;

        public virtual IEnumerator<TOut> GetEnumerator()
        {
            return new EnumeratorCaster(_inner.GetEnumerator<TIn>());
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new EnumeratorCaster(_inner.GetEnumerator());
        }

        public class EnumeratorCaster<TOut,TIn> : IEnumerator<TOut>
        {
            public EnumeratorCaster(IEnumerator<TIn> inner)
            {

            }

            public virtual TOut Current
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            object IEnumerator.Current
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public virtual void Dispose()
            {
                _inner.Dispose();
            }

            public virtual bool MoveNext()
            {
                return _inner.MoveNext();
            }

            public virtual void Reset()
            {
                _inner.Reset();
            }

            protected IEnumerator<TIn> _inner;
        }
    }
    */
}


text:
require 'rubygems'
require 'bundler/setup'
require 'dm-core'
require 'dm-timestamps'
require 'dm-validations'
require 'dm-aggregates'
require 'dm-migrations'
require 'haml'
require 'ostruct'

require 'sinatra' unless defined?(Sinatra)

configure do
  SiteConfig = OpenStruct.new(
                 :title => 'Your Application Name',
                 :author => 'Your Name',
                 :url_base => 'http://localhost:4567/'
               )

  # load models
  $LOAD_PATH.unshift("#{File.dirname(__FILE__)}/lib")
  Dir.glob("#{File.dirname(__FILE__)}/lib/*.rb") { |lib| require File.basename(lib, '.*') }

  DataMapper.setup(:default, (ENV["DATABASE_URL"] || "sqlite3:///#{File.expand_path(File.dirname(__FILE__))}/#{Sinatra::Base.environment}.db"))
end


text:
package fake

import (
	api "k8s.io/client-go/1.5/pkg/api"
	unversioned "k8s.io/client-go/1.5/pkg/api/unversioned"
	v1 "k8s.io/client-go/1.5/pkg/api/v1"
	labels "k8s.io/client-go/1.5/pkg/labels"
	watch "k8s.io/client-go/1.5/pkg/watch"
	testing "k8s.io/client-go/1.5/testing"
)

// FakeNamespaces implements NamespaceInterface
type FakeNamespaces struct {
	Fake *FakeCore
}

var namespacesResource = unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"}

func (c *FakeNamespaces) Create(namespace *v1.Namespace) (result *v1.Namespace, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootCreateAction(namespacesResource, namespace), &v1.Namespace{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Namespace), err
}

func (c *FakeNamespaces) Update(namespace *v1.Namespace) (result *v1.Namespace, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(namespacesResource, namespace), &v1.Namespace{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Namespace), err
}

func (c *FakeNamespaces) UpdateStatus(namespace *v1.Namespace) (*v1.Namespace, error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateSubresourceAction(namespacesResource, "status", namespace), &v1.Namespace{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Namespace), err
}

func (c *FakeNamespaces) Delete(name string, options *api.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(namespacesResource, name), &v1.Namespace{})
	return err
}

func (c *FakeNamespaces) DeleteCollection(options *api.DeleteOptions, listOptions api.ListOptions) error {
	action := testing.NewRootDeleteCollectionAction(namespacesResource, listOptions)

	_, err := c.Fake.Invokes(action, &v1.NamespaceList{})
	return err
}

func (c *FakeNamespaces) Get(name string) (result *v1.Namespace, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootGetAction(namespacesResource, name), &v1.Namespace{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Namespace), err
}

func (c *FakeNamespaces) List(opts api.ListOptions) (result *v1.NamespaceList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootListAction(namespacesResource, opts), &v1.NamespaceList{})
	if obj == nil {
		return nil, err
	}

	label := opts.LabelSelector
	if label == nil {
		label = labels.Everything()
	}
	list := &v1.NamespaceList{}
	for _, item := range obj.(*v1.NamespaceList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested namespaces.
func (c *FakeNamespaces) Watch(opts api.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewRootWatchAction(namespacesResource, opts))
}

// Patch applies the patch and returns the patched namespace.
func (c *FakeNamespaces) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.Namespace, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootPatchSubresourceAction(namespacesResource, name, data, subresources...), &v1.Namespace{})
	if obj == nil {
		return nil, err
	}
	return obj.(*v1.Namespace), err
}


text:
#ifndef ROCKETCOREELEMENTUTILITIES_H
#define ROCKETCOREELEMENTUTILITIES_H

#include <Rocket/Core/Header.h>
#include <Rocket/Core/Box.h>
#include <Rocket/Core/WString.h>
#include <Rocket/Core/Types.h>

namespace Rocket {
namespace Core {

class Context;
class FontFaceHandle;
class RenderInterface;

/**
	Utility functions for dealing with elements.

	@author Lloyd Weehuizen
 */

class ROCKETCORE_API ElementUtilities
{
public:
	enum PositionAnchor
	{
		TOP = 1 << 0,
		BOTTOM = 1 << 1,
		LEFT = 1 << 2,
		RIGHT = 1 << 3,

		TOP_LEFT = TOP | LEFT,
		TOP_RIGHT = TOP | RIGHT,
		BOTTOM_LEFT = BOTTOM | LEFT,
		BOTTOM_RIGHT = BOTTOM | RIGHT
	};

	/// Get the element with the given id.
	/// @param[in] root_element First element to check.
	/// @param[in] id ID of the element to look for.
	static Element* GetElementById(Element* root_element, const String& id);
	/// Get all elements with the given tag.
	/// @param[out] elements Resulting elements.
	/// @param[in] root_element First element to check.
	/// @param[in] tag Tag to search for.
	static void GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag);

	/// Returns an element's font face.
	/// @param[in] element The element to determine the font face for.
	/// @return The element's font face. This will be NULL if no valid RCSS font styles have been set up for this element.
	static FontFaceHandle* GetFontFaceHandle(Element* element);
	/// Returns an element's font size, if it has a font defined.
	/// @param[in] element The element to determine the font size for.
	/// @return The font size as determined by the element's font, or 0 if it has no font specified.
	static int GetFontSize(Element* element);
	/// Returns an element's line height, if it has a font defined.
	/// @param[in] element The element to determine the line height for.
	/// @return The line height as specified by the element's font and line height styles.
	static int GetLineHeight(Element* element);
	/// Returns the width of a string rendered within the context of the given element.
	/// @param[in] element The element to measure the string from.
	/// @param[in] string The string to measure.
	/// @return The string width, in pixels.
	static int GetStringWidth(Element* element, const WString& string);

	/// Bind and instance all event attributes on the given element onto the element
	/// @param element Element to bind events on
	static void BindEventAttributes(Element* element);

	/// Generates the clipping region for an element.
	/// @param[out] clip_origin The origin, in context coordinates, of the origin of the element's clipping window.
	/// @param[out] clip_dimensions The size, in context coordinates, of the element's clipping window.
	/// @param[in] element The element to generate the clipping region for.
	/// @return True if a clipping region exists for the element and clip_origin and clip_window were set, false if not.
	static bool GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element);
	/// Sets the clipping region from an element and its ancestors.
	/// @param[in] element The element to generate the clipping region from.
	/// @param[in] context The context of the element; if this is not supplied, it will be derived from the element.
	/// @return The visibility of the given element within its clipping region.
	static bool SetClippingRegion(Element* element, Context* context = NULL);
	/// Pushes the cached clip state of a render interface back up to ensure the cache is up-to-date.
	/// @param[in] render_interface The render interface to update.
	static void PushClipCache(RenderInterface* render_interface);

	/// Formats the contents of an element. This does not need to be called for ordinary elements, but can be useful
	/// for non-DOM elements of custom elements.
	/// @param[in] element The element to lay out.
	/// @param[in] containing_block The size of the element's containing block.
	static bool FormatElement(Element* element, const Vector2f& containing_block);

	/// Generates the box for an element.
	/// @param[out] box The box to be built.
	/// @param[in] containing_block The dimensions of the content area of the block containing the element.
	/// @param[in] element The element to build the box for.
	/// @param[in] inline_element True if the element is placed in an inline context, false if not.
	static void BuildBox(Box& box, const Vector2f& containing_block, Element* element, bool inline_element = false);

	/// Sizes and positions an element within its parent. Any relative values will be evaluated against the size of the
	/// element parent's content area.
	/// @param element[in] The element to size and position.
	/// @param offset[in] The offset of the element inside its parent's content area.
	static bool PositionElement(Element* element, const Vector2f& offset);
	/// Sizes an element, and positions it within its parent offset from the borders of its content area. Any relative
	/// values will be evaluated against the size of the element parent's content area.
	/// @param element[in] The element to size and position.
	/// @param offset[in] The offset from the parent's borders.
	/// @param anchor[in] Defines which corner or edge the border is to be positioned relative to.
	static bool PositionElement(Element* element, const Vector2f& offset, PositionAnchor anchor);
};

}
}

#endif


text:
public class Names
{
    // ------------------------
    // main prints the list
    // ------------------------
    public static void main (String[] args)
    {
      System.out.println ();
      System.out.println ("\tName\t\tHometown\t\tMajor");
      System.out.println ("\t====\t\t========\t\t=====");
      System.out.println ("\tSally\t\tRoanoke\t\tComputer Science");
      System.out.println ("\tAlexander\t\tWashington\t\tMath");
      System.out.println ("\tJustin\t\tTucker\t\tComputer Science, Networking");
      System.out.println ("\tSamanyu\t\tHyderabad\t\tUnknown");
      System.out.println ("\tZach\t\tCumming\t\tUnknown");
      System.out.println ();
    }
}


text:
@class NSMutableArray;

@interface TNDRMomentViewerViewModel : NSObject
{
    id <TNDRMomentViewerViewModelDelegate> _delegate;
    NSMutableArray *_moments;
}

- (void).cxx_destruct;
- (void)_deleteMoment:(id)arg1 completion:(CDUnknownBlockType)arg2;
- (void)_image:(id)arg1 didFinishSavingWithError:(id)arg2 contextInfo:(void *)arg3;
- (float)_mostLikes;
@property(nonatomic) __weak id <TNDRMomentViewerViewModelDelegate> delegate; // @synthesize delegate=_delegate;
- (void)deleteMomentAtIndex:(id)arg1 completion:(CDUnknownBlockType)arg2;
- (float)expirationPercentForMomentAtIndexPath:(id)arg1;
- (id)expirationStringForMomentAtIndexPath:(id)arg1;
- (BOOL)hasLikesToShowAtIndexPath:(id)arg1;
- (id)initWithMoments:(id)arg1;
- (BOOL)isMyMomentForIndexPath:(id)arg1;
- (float)likePercentForMomentAtIndexPath:(id)arg1;
- (id)likesStringForMomentAtIndexPath:(id)arg1;
- (id)likesViewModelForIndexPath:(id)arg1;
- (id)momentForIndexPath:(id)arg1;
@property(retain, nonatomic) NSMutableArray *moments; // @synthesize moments=_moments;
- (unsigned int)numberOfMoments;
- (void)saveImage:(id)arg1 forIndexPath:(id)arg2;
- (id)timeLeftViewModelForIndexPath:(id)arg1;
- (id)urlForMomentAtIndex:(id)arg1;

@end


text:
<?php # -*- coding: utf-8 -*-

namespace Brain\Monkey\Hook;

/**
 * A simple stack data structure built around an array for hook names.
 * This allow to keep last hook being executed.
 *
 * It is used to `current_filter()`, `doing_action()`, and `doing_filter()`.
 *
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @package BrainMonkey
 * @license http://opensource.org/licenses/MIT MIT
 */
final class HookRunningStack
{

    /**
     * @var array
     */
    private $stack = [];

    /**
     * @param string $hook_name
     * @return static
     */
    public function push($hook_name)
    {
        $this->stack[] = $hook_name;

        return $this;
    }

    /**
     * @return string
     */
    public function last()
    {
        if ( ! $this->stack) {
            return '';
        }

        return end($this->stack);
    }

    /**
     * @param string $hook_name
     * @return bool
     */
    public function has($hook_name = null)
    {
        if ( ! $this->stack) {
            return false;
        }

        return $hook_name === null ? true : in_array($hook_name, $this->stack, true);
    }

    /**
     * @return static
     */
    public function reset()
    {
        $this->stack = [];

        return $this;
    }
}


text:
package org.schema.api.model.thing.creativeWork.article.socialMediaPosting;

import org.schema.api.model.thing.creativeWork.CreativeWork;
import org.schema.api.model.thing.creativeWork.article.Article;

public class SocialMediaPosting extends Article
{
	private CreativeWork sharedContent;

	public CreativeWork getSharedContent()
	{
		return sharedContent;
	}

	public void setSharedContent(CreativeWork sharedContent)
	{
		this.sharedContent = sharedContent;
	}
}


text:
package com.angkorteam.framework.wicket.extensions.markup.html.repeater.data.table.filter;

import com.angkorteam.framework.share.provider.TableProvider;
import com.angkorteam.framework.wicket.WicketBiFunction;
import com.angkorteam.framework.wicket.WicketTriConsumer;
import com.angkorteam.framework.wicket.WicketTriFunction;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterForm;
import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.IFilteredColumn;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;

import java.util.List;
import java.util.Map;

/**
 * Created by socheat on 12/7/16.
 */
public class ChoiceFilterColumn extends LambdaColumn
        implements IFilteredColumn<Map<String, Object>, String> {

    private final IModel<List<String>> filterChoices;

    private final String propertyExpression;

    public ChoiceFilterColumn(TableProvider provider,
                              ItemClass itemClass,
                              IModel<String> displayModel,
                              String column,
                              IModel<List<String>> filterChoices,
                              WicketBiFunction<String, Map<String, Object>, ?> function) {
        super(provider, itemClass, displayModel, column, function);
        this.filterChoices = filterChoices;
        this.propertyExpression = column;
    }

    public ChoiceFilterColumn(TableProvider provider,
                              ItemClass itemClass,
                              IModel<String> displayModel,
                              String column,
                              IModel<List<String>> filterChoices,
                              WicketBiFunction<String, Map<String, Object>, ?> function,
                              WicketBiFunction<String, Map<String, Object>, ItemType> itemType,
                              WicketBiFunction<String, Map<String, Object>, Boolean> clickable,
                              WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss,
                              WicketBiFunction<String, Map<String, Object>, Boolean> progressBarActive,
                              WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick) {
        super(provider, itemClass, displayModel, column, function, itemType, clickable, itemCss, progressBarActive, itemClick);
        this.filterChoices = filterChoices;
        this.propertyExpression = column;
    }

    public ChoiceFilterColumn(TableProvider provider,
                              ItemClass itemClass,
                              IModel<String> displayModel,
                              String identity,
                              String column,
                              String sortProperty,
                              String propertyExpression,
                              IModel<List<String>> filterChoices,
                              WicketBiFunction<String, Map<String, Object>, ?> function,
                              WicketBiFunction<String, Map<String, Object>, ItemType> itemType,
                              WicketBiFunction<String, Map<String, Object>, Boolean> clickable,
                              WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss,
                              WicketBiFunction<String, Map<String, Object>, Boolean> progressBarActive,
                              WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick,
                              WicketTriFunction<String, Map<String, Object>, String, ? extends Component> itemCustom) {
        super(provider, itemClass, displayModel, identity, column, sortProperty, function, itemType, clickable, itemCss, progressBarActive, itemClick, itemCustom);
        this.filterChoices = filterChoices;
        this.propertyExpression = propertyExpression;
    }

    @Override
    public Component getFilter(final String componentId, final FilterForm<?> form) {
        ChoiceFilter<String> filter = new ChoiceFilter<>(componentId, getFilterModel(form), form,
                getFilterChoices(), enableAutoSubmit());
        IChoiceRenderer<String> renderer = getChoiceRenderer();
        if (renderer != null) {
            filter.getChoice().setChoiceRenderer(renderer);
        }
        return filter;
    }

    protected IModel<String> getFilterModel(final FilterForm<?> form) {
        return new PropertyModel<>(form.getDefaultModel(), this.propertyExpression);
    }

    protected IChoiceRenderer<String> getChoiceRenderer() {
        return null;
    }

    protected final IModel<List<String>> getFilterChoices() {
        return filterChoices;
    }

    public void detach() {
        super.detach();
        if (filterChoices != null) {
            filterChoices.detach();
        }
    }

    protected boolean enableAutoSubmit() {
        return true;
    }

    public static class Builder {

        private TableProvider provider;

        private ItemClass itemClass;

        private IModel<String> displayModel;

        private String column;

        private IModel<List<String>> filterChoices;

        private WicketBiFunction<String, Map<String, Object>, ?> function;

        private WicketBiFunction<String, Map<String, Object>, ItemType> itemType;

        private WicketBiFunction<String, Map<String, Object>, Boolean> clickable;

        private WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss;

        private WicketBiFunction<String, Map<String, Object>, Boolean> progressBarActive;

        private WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick;

        private WicketTriFunction<String, Map<String, Object>, String, ? extends Component> itemCustom;

        public Builder(TableProvider provider, ItemClass itemClass, IModel<String> displayModel, String column, IModel<List<String>> filterChoices, WicketBiFunction<String, Map<String, Object>, ?> function) {
            this.provider = provider;
            this.itemClass = itemClass;
            this.filterChoices = filterChoices;
            this.displayModel = displayModel;
            this.column = column;
            this.function = function;
        }

        public Builder withItemType(WicketBiFunction<String, Map<String, Object>, ItemType> itemType) {
            this.itemType = itemType;
            return this;
        }

        public Builder withClickable(WicketBiFunction<String, Map<String, Object>, Boolean> clickable) {
            this.clickable = clickable;
            return this;
        }

        public Builder withItemCss(WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss) {
            this.itemCss = itemCss;
            return this;
        }

        public Builder withProgressBarActive(WicketBiFunction<String, Map<String, Object>, Boolean> progressBarActive) {
            this.progressBarActive = progressBarActive;
            return this;
        }

        public Builder withItemClick(WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick) {
            this.itemClick = itemClick;
            return this;
        }

        public Builder withItemCustom(WicketTriFunction<String, Map<String, Object>, String, ? extends Component> itemCustom) {
            this.itemCustom = itemCustom;
            return this;
        }

        public ChoiceFilterColumn build() {
            ChoiceFilterColumn column = new ChoiceFilterColumn(this.provider, this.itemClass, this.displayModel, this.column, this.filterChoices, this.function);
            column.itemCustom = this.itemCustom;
            column.itemClick = this.itemClick;
            column.itemType = this.itemType;
            column.clickable = this.clickable;
            column.itemCss = this.itemCss;
            column.progressBarActive = this.progressBarActive;
            return column;
        }
    }

}


text:
package net.bis5.mattermost.model.license;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

/**
 * Features.
 *
 * @author Takayuki Maruyama
 */
@Data
public class Features {

  @JsonProperty("users")
  private int users;
  @JsonProperty("ldap")
  private boolean ldap;
  @JsonProperty("mfa")
  private boolean mfa;
  @JsonProperty("google_oauth")
  private boolean googleOAuth;
  @JsonProperty("office365_oauth")
  private boolean office365OAuth;
  @JsonProperty("compliance")
  private boolean compliance;
  @JsonProperty("cluster")
  private boolean cluster;
  @JsonProperty("metrics")
  private boolean metrics;
  @JsonProperty("custom_brand")
  private boolean customBrand;
  @JsonProperty("mhpns")
  private boolean mhpns;
  @JsonProperty("saml")
  private boolean saml;
  @JsonProperty("password_requirements")
  private boolean passwordRequirements;
  // after we enabled more features for webrtc we'll need to control them with
  // this
  @JsonProperty("future_features")
  private boolean futureFeatures;

}


text:
title: Use PropTypes to Define the Props You Expect
localeTitle: استخدم PropTypes لتحديد الدعائم التي تتوقعها
---
## استخدم PropTypes لتحديد الدعائم التي تتوقعها

هذا التحدي قد قمت بتعيين `propTypes` لمكون `Items` .

 `const Items = (props) => {
  return
Current Quantity of Items in Cart: {props.quantity}

 };
`

لتعيين propTypes ، فإن الصيغة التي يجب اتباعها هي

 `itemName.propTypes = {
  props: PropTypes.dataType.isRequired
 };
`

بعد التركيب، يجب وضع التعليمات البرمجية التالية أدناه رمز نظرا ل `quantity` الدعائم من `Items` عنصر

 `Items.propTypes = {
  quantity: PropTypes.number.isRequired
 };
`


text:
package com.haskforce.psi;

import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import com.haskforce.HaskellLanguage;

public class HaskellTokenType extends IElementType {
    public HaskellTokenType(@NotNull @NonNls String debugName) {
        super(debugName, HaskellLanguage.INSTANCE);
    }

    @Override
    public String toString() {
        return "HaskellTokenType." + super.toString();
    }
}


text:
package hyn.com.lib;

import java.net.HttpURLConnection;

/**
 * Created by hanyanan on 2015/3/17.
 */
public class FourTuple<T1, T2, T3, T4> extends ThreeTuple {
    public final T4 fourthValue;
    public FourTuple(T1 value1, T2 value2, T3 value3, T4 value4) {
        super(value1, value2,value3);
        fourthValue = value4;
    }
}


text:
using namespace Storage::Disk;

D64::D64(const std::string &file_name) :
		file_(file_name) {
	// in D64, this is it for validation without imposing potential false-negative tests: check that
	// the file size appears to be correct. Stone-age stuff.
	if(file_.stats().st_size != 174848 && file_.stats().st_size != 196608)
		throw Error::InvalidFormat;

	number_of_tracks_ = (file_.stats().st_size == 174848) ? 35 : 40;

	// then, ostensibly, this is a valid file. Hmmm. Pick a disk ID as a function of the file_name,
	// being the most stable thing available
	disk_id_ = 0;
	for(const auto &character: file_name) {
		disk_id_ ^= character;
		disk_id_ = uint16_t((disk_id_ << 2) ^ (disk_id_ >> 13));
	}
}

HeadPosition D64::get_maximum_head_position() {
	return HeadPosition(number_of_tracks_);
}

std::shared_ptr<Track> D64::get_track_at_position(Track::Address address) {
	// figure out where this track starts on the disk
	int offset_to_track = 0;
	int tracks_to_traverse = address.position.as_int();

	int zone_sizes[] = {17, 7, 6, 10};
	int sectors_by_zone[] = {21, 19, 18, 17};
	int zone = 0;
	for(int current_zone = 0; current_zone < 4; current_zone++) {
		int tracks_in_this_zone = std::min(tracks_to_traverse, zone_sizes[current_zone]);
		offset_to_track += tracks_in_this_zone * sectors_by_zone[current_zone];
		tracks_to_traverse -= tracks_in_this_zone;
		if(tracks_in_this_zone == zone_sizes[current_zone]) zone++;
	}

	// seek to start of data
	file_.seek(offset_to_track * 256, SEEK_SET);

	// build up a PCM sampling of the GCR version of this track

	// format per sector:
	//
	// syncronisation: three $FFs directly in GCR
	// value $08 to announce a header
	// a checksum made of XORing the following four bytes
	// sector number (1 byte)
	// track number (1 byte)
	// disk ID (2 bytes)
	// five GCR bytes of value $55
	// = [6 bytes -> 7.5 GCR bytes] + ... = 21 GCR bytes
	//
	// syncronisation: three $FFs directly in GCR
	// value $07 to announce data
	// 256 data bytes
	// a checksum: the XOR of the previous 256 bytes
	// two bytes of vaue $00
	// = [260 bytes -> 325 GCR bytes] + 3 GCR bytes = 328 GCR bytes
	//
	// = 349 GCR bytes per sector

	std::size_t track_bytes = 349 * size_t(sectors_by_zone[zone]);
	std::vector<uint8_t> data(track_bytes);

	for(int sector = 0; sector < sectors_by_zone[zone]; sector++) {
		uint8_t *sector_data = &data[size_t(sector) * 349];
		sector_data[0] = sector_data[1] = sector_data[2] = 0xff;

		uint8_t sector_number = uint8_t(sector);						// sectors count from 0
		uint8_t track_number = uint8_t(address.position.as_int() + 1);	// tracks count from 1
		uint8_t checksum = uint8_t(sector_number ^ track_number ^ disk_id_ ^ (disk_id_ >> 8));
		uint8_t header_start[4] = {
			0x08, checksum, sector_number, track_number
		};
		Encodings::CommodoreGCR::encode_block(&sector_data[3], header_start);

		uint8_t header_end[4] = {
			uint8_t(disk_id_ & 0xff), uint8_t(disk_id_ >> 8), 0, 0
		};
		Encodings::CommodoreGCR::encode_block(&sector_data[8], header_end);

		// pad out post-header parts
		uint8_t zeros[4] = {0, 0, 0, 0};
		Encodings::CommodoreGCR::encode_block(&sector_data[13], zeros);
		sector_data[18] = 0x52;
		sector_data[19] = 0x94;
		sector_data[20] = 0xaf;

		// get the actual contents
		uint8_t source_data[256];
		file_.read(source_data, sizeof(source_data));

		// compute the latest checksum
		checksum = 0;
		for(int c = 0; c < 256; c++)
			checksum ^= source_data[c];

		// put in another sync
		sector_data[21] = sector_data[22] = sector_data[23] = 0xff;

		// now start writing in the actual data
		uint8_t start_of_data[4] = {
			0x07, source_data[0], source_data[1], source_data[2]
		};
		Encodings::CommodoreGCR::encode_block(&sector_data[24], start_of_data);
		int source_data_offset = 3;
		int target_data_offset = 29;
		while((source_data_offset+4) < 256) {
			Encodings::CommodoreGCR::encode_block(&sector_data[target_data_offset], &source_data[source_data_offset]);
			target_data_offset += 5;
			source_data_offset += 4;
		}
		uint8_t end_of_data[4] = {
			source_data[255], checksum, 0, 0
		};
		Encodings::CommodoreGCR::encode_block(&sector_data[target_data_offset], end_of_data);
	}

	return std::make_shared<PCMTrack>(PCMSegment(data));
}


text:
<!--
  ~ Copyright (c) 2016. Eli Connelly
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~    you may not use this file except in compliance with the License.
  ~    You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~    Unless required by applicable law or agreed to in writing, software
  ~    distributed under the License is distributed on an "AS IS" BASIS,
  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~    See the License for the specific language governing permissions and
  ~    limitations under the License.
  -->

<resources>
    <!--
    Layout alias to replace the single-pane version of the layout with a
    two-pane version on Large screens.

    For more on layout aliases, see:
    http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
    -->
    <!--<item type="layout" name="activity_postitem_list">@layout/activity_postitem_twopane</item>-->
    <!--<item type="layout" name="fragment_postitem_detail">@layout/fragment_postitem_detail_twopane</item>-->
</resources>


text:
import classNames from "classnames";
import { LocalizedString } from "common/types";
import React from "react";
import styled, * as styles from "renderer/styles";
import Icon from "renderer/basics/Icon";

const IconButtonDiv = styled.div`
  &:not(.disabled) {
    ${styles.clickable};
  }

  font-size: ${(props) => props.theme.fontSizes.baseText};
  display: flex;
  align-items: center;
  justify-content: center;

  flex-shrink: 0;

  width: 30px;
  height: 30px;

  &:hover {
    color: ${(props) => props.theme.secondaryTextHover};
  }

  &.disabled {
    opacity: 0.2;
    pointer: disabled;
  }

  &.emphasized {
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  &.big {
    font-size: ${(props) => props.theme.fontSizes.huge};
    width: 36px;
    height: 36px;
  }

  &.huge {
    font-size: ${(props) => props.theme.fontSizes.huger};
    width: 48px;
    height: 48px;
  }

  &.enormous {
    font-size: ${(props) => props.theme.fontSizes.enormous};
    width: 48px;
    height: 48px;
  }
`;

class IconButton extends React.PureComponent<Props> {
  render() {
    const {
      className,
      big,
      huge,
      enormous,
      emphasized,
      disabled,
      icon,
      hint,
      hintPosition = "top",
      ...restProps
    } = this.props;

    return (
      <IconButtonDiv
        className={classNames(className, {
          disabled,
          big,
          huge,
          enormous,
          emphasized,
        })}
        data-rh={hint ? JSON.stringify(hint) : null}
        data-rh-at={hintPosition}
        {...restProps}
      >
        {typeof icon === "string" ? <Icon icon={icon} /> : icon}
      </IconButtonDiv>
    );
  }
}

interface Props {
  icon: string | JSX.Element;
  disabled?: boolean;
  className?: string;
  id?: string;
  hint?: LocalizedString;
  hintPosition?: "top" | "left" | "right" | "bottom";

  onClick?: React.MouseEventHandler<HTMLElement>;
  onMouseDown?: React.MouseEventHandler<HTMLElement>;
  onContextMenu?: React.MouseEventHandler<HTMLElement>;
  big?: boolean;
  huge?: boolean;
  enormous?: boolean;
  emphasized?: boolean;
}

export default IconButton;


text:
/**
 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
 * needs of dygraphs.
 *
 * In particular, support for:
 * - grid overlays
 * - error bars
 * - dygraphs attribute system
 */

/**
 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
 * a canvas. It's based on PlotKit.CanvasRenderer.
 * @param {Object} element The canvas to attach to
 * @param {Object} elementContext The 2d context of the canvas (injected so it
 * can be mocked for testing.)
 * @param {Layout} layout The DygraphLayout object for this graph.
 * @constructor
 */

/*jshint globalstrict: true */
/*global Dygraph:false,RGBColor:false */
"use strict";

/**
 * @constructor
 *
 * This gets called when there are "new points" to chart. This is generally the
 * case when the underlying data being charted has changed. It is _not_ called
 * in the common case that the user has zoomed or is panning the view.
 *
 * The chart canvas has already been created by the Dygraph object. The
 * renderer simply gets a drawing context.
 *
 * @param {Dyraph} dygraph The chart to which this renderer belongs.
 * @param {Canvas} element The <canvas> DOM element on which to draw.
 * @param {CanvasRenderingContext2D} elementContext The drawing context.
 * @param {DygraphLayout} layout The chart's DygraphLayout object.
 *
 * TODO(danvk): remove the elementContext property.
 */
var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
  this.dygraph_ = dygraph;

  this.layout = layout;
  this.element = element;
  this.elementContext = elementContext;
  this.container = this.element.parentNode;

  this.height = this.element.height;
  this.width = this.element.width;

  // --- check whether everything is ok before we return
  if (!this.isIE && !(DygraphCanvasRenderer.isSupported(this.element)))
      throw "Canvas is not supported.";

  // internal state
  this.area = layout.getPlotArea();
  this.container.style.position = "relative";
  this.container.style.width = this.width + "px";

  // Set up a clipping area for the canvas (and the interaction canvas).
  // This ensures that we don't overdraw.
  if (this.dygraph_.isUsingExcanvas_) {
    this._createIEClipArea();
  } else {
    // on Android 3 and 4, setting a clipping area on a canvas prevents it from
    // displaying anything.
    if (!Dygraph.isAndroid()) {
      var ctx = this.dygraph_.canvas_ctx_;
      ctx.beginPath();
      ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
      ctx.clip();

      ctx = this.dygraph_.hidden_ctx_;
      ctx.beginPath();
      ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
      ctx.clip();
    }
  }
};

/**
 * This just forwards to dygraph.attr_.
 * TODO(danvk): remove this?
 * @private
 */
DygraphCanvasRenderer.prototype.attr_ = function(name, opt_seriesName) {
  return this.dygraph_.attr_(name, opt_seriesName);
};

/**
 * Clears out all chart content and DOM elements.
 * This is called immediately before render() on every frame, including
 * during zooms and pans.
 * @private
 */
DygraphCanvasRenderer.prototype.clear = function() {
  var context;
  if (this.isIE) {
    // VML takes a while to start up, so we just poll every this.IEDelay
    try {
      if (this.clearDelay) {
        this.clearDelay.cancel();
        this.clearDelay = null;
      }
      context = this.elementContext;
    }
    catch (e) {
      // TODO(danvk): this is broken, since MochiKit.Async is gone.
      // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
      // this.clearDelay.addCallback(bind(this.clear, this));
      return;
    }
  }

  context = this.elementContext;
  context.clearRect(0, 0, this.width, this.height);
};

/**
 * Checks whether the browser supports the <canvas> tag.
 * @private
 */
DygraphCanvasRenderer.isSupported = function(canvasName) {
  var canvas = null;
  try {
    if (typeof(canvasName) == 'undefined' || canvasName === null) {
      canvas = document.createElement("canvas");
    } else {
      canvas = canvasName;
    }
    canvas.getContext("2d");
  }
  catch (e) {
    var ie = navigator.appVersion.match(/MSIE (\d\.\d)/);
    var opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
    if ((!ie) || (ie[1] < 6) || (opera))
      return false;
    return true;
  }
  return true;
};

/**
 * This method is responsible for drawing everything on the chart, including
 * lines, error bars, fills and axes.
 * It is called immediately after clear() on every frame, including during pans
 * and zooms.
 * @private
 */
DygraphCanvasRenderer.prototype.render = function() {
  // attaches point.canvas{x,y}
  this._updatePoints();

  // actually draws the chart.
  this._renderLineChart();
};

DygraphCanvasRenderer.prototype._createIEClipArea = function() {
  var className = 'dygraph-clip-div';
  var graphDiv = this.dygraph_.graphDiv;

  // Remove old clip divs.
  for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
    if (graphDiv.childNodes[i].className == className) {
      graphDiv.removeChild(graphDiv.childNodes[i]);
    }
  }

  // Determine background color to give clip divs.
  var backgroundColor = document.bgColor;
  var element = this.dygraph_.graphDiv;
  while (element != document) {
    var bgcolor = element.currentStyle.backgroundColor;
    if (bgcolor && bgcolor != 'transparent') {
      backgroundColor = bgcolor;
      break;
    }
    element = element.parentNode;
  }

  function createClipDiv(area) {
    if (area.w === 0 || area.h === 0) {
      return;
    }
    var elem = document.createElement('div');
    elem.className = className;
    elem.style.backgroundColor = backgroundColor;
    elem.style.position = 'absolute';
    elem.style.left = area.x + 'px';
    elem.style.top = area.y + 'px';
    elem.style.width = area.w + 'px';
    elem.style.height = area.h + 'px';
    graphDiv.appendChild(elem);
  }

  var plotArea = this.area;
  // Left side
  createClipDiv({
    x:0, y:0,
    w:plotArea.x,
    h:this.height
  });

  // Top
  createClipDiv({
    x: plotArea.x, y: 0,
    w: this.width - plotArea.x,
    h: plotArea.y
  });

  // Right side
  createClipDiv({
    x: plotArea.x + plotArea.w, y: 0,
    w: this.width-plotArea.x - plotArea.w,
    h: this.height
  });

  // Bottom
  createClipDiv({
    x: plotArea.x,
    y: plotArea.y + plotArea.h,
    w: this.width - plotArea.x,
    h: this.height - plotArea.h - plotArea.y
  });
};

/**
 * Returns a predicate to be used with an iterator, which will
 * iterate over points appropriately, depending on whether
 * connectSeparatedPoints is true. When it's false, the predicate will
 * skip over points with missing yVals.
 */
DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
  return connectSeparatedPoints ?
      DygraphCanvasRenderer._predicateThatSkipsEmptyPoints :
      null;
};

DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
    function(array, idx) {
  return array[idx].yval !== null;
};

/**
 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawStyledLine = function(e,
    color, strokeWidth, strokePattern, drawPoints,
    drawPointCallback, pointSize) {
  var g = e.dygraph;
  // TODO(konigsberg): Compute attributes outside this method call.
  var stepPlot = g.getOption("stepPlot");  // TODO(danvk): per-series
  if (!Dygraph.isArrayLike(strokePattern)) {
    strokePattern = null;
  }

  var drawGapPoints = g.getOption('drawGapEdgePoints', e.setName);

  var points = e.points;
  var iter = Dygraph.createIterator(points, 0, points.length,
      DygraphCanvasRenderer._getIteratorPredicate(
          g.getOption("connectSeparatedPoints")));  // TODO(danvk): per-series?

  var stroking = strokePattern && (strokePattern.length >= 2);

  var ctx = e.drawingContext;
  ctx.save();
  if (stroking) {
    ctx.installPattern(strokePattern);
  }

  var pointsOnLine = DygraphCanvasRenderer._drawSeries(
      e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
  DygraphCanvasRenderer._drawPointsOnLine(
      e, pointsOnLine, drawPointCallback, color, pointSize);

  if (stroking) {
    ctx.uninstallPattern();
  }

  ctx.restore();
};

/**
 * This does the actual drawing of lines on the canvas, for just one series.
 * Returns a list of [canvasx, canvasy] pairs for points for which a
 * drawPointCallback should be fired.  These include isolated points, or all
 * points if drawPoints=true.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawSeries = function(e,
    iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) {

  var prevCanvasX = null;
  var prevCanvasY = null;
  var nextCanvasY = null;
  var isIsolated; // true if this point is isolated (no line segments)
  var point; // the point being processed in the while loop
  var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
  var first = true; // the first cycle through the while loop

  var ctx = e.drawingContext;
  ctx.beginPath();
  ctx.strokeStyle = color;
  ctx.lineWidth = strokeWidth;

  // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
  var arr = iter.array_;
  var limit = iter.end_;
  var predicate = iter.predicate_;

  for (var i = iter.start_; i < limit; i++) {
    point = arr[i];
    if (predicate) {
      while (i < limit && !predicate(arr, i)) {
        i++;
      }
      if (i == limit) break;
      point = arr[i];
    }

    if (point.canvasy === null || point.canvasy != point.canvasy) {
      if (stepPlot && prevCanvasX !== null) {
        // Draw a horizontal line to the start of the missing data
        ctx.moveTo(prevCanvasX, prevCanvasY);
        ctx.lineTo(point.canvasx, prevCanvasY);
      }
      prevCanvasX = prevCanvasY = null;
    } else {
      isIsolated = false;
      if (drawGapPoints || !prevCanvasX) {
        iter.nextIdx_ = i;
        var peek = iter.next();
        nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;

        var isNextCanvasYNullOrNaN = nextCanvasY === null ||
            nextCanvasY != nextCanvasY;
        isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
        if (drawGapPoints) {
          // Also consider a point to be "isolated" if it's adjacent to a
          // null point, excluding the graph edges.
          if ((!first && !prevCanvasX) ||
              (iter.hasNext && isNextCanvasYNullOrNaN)) {
            isIsolated = true;
          }
        }
      }

      if (prevCanvasX !== null) {
        if (strokeWidth) {
          if (stepPlot) {
            ctx.moveTo(prevCanvasX, prevCanvasY);
            ctx.lineTo(point.canvasx, prevCanvasY);
          }

          ctx.lineTo(point.canvasx, point.canvasy);
        }
      } else {
        ctx.moveTo(point.canvasx, point.canvasy);
      }
      if (drawPoints || isIsolated) {
        pointsOnLine.push([point.canvasx, point.canvasy]);
      }
      prevCanvasX = point.canvasx;
      prevCanvasY = point.canvasy;
    }
    first = false;
  }
  ctx.stroke();
  return pointsOnLine;
};

/**
 * This fires the drawPointCallback functions, which draw dots on the points by
 * default. This gets used when the "drawPoints" option is set, or when there
 * are isolated points.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawPointsOnLine = function(
    e, pointsOnLine, drawPointCallback, color, pointSize) {
  var ctx = e.drawingContext;
  for (var idx = 0; idx < pointsOnLine.length; idx++) {
    var cb = pointsOnLine[idx];
    ctx.save();
    drawPointCallback(
        e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize);
    ctx.restore();
  }
};

/**
 * Attaches canvas coordinates to the points array.
 * @private
 */
DygraphCanvasRenderer.prototype._updatePoints = function() {
  // Update Points
  // TODO(danvk): here
  //
  // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
  // transformations can be pushed into the canvas via linear transformation
  // matrices.
  // NOTE(danvk): this is trickier than it sounds at first. The transformation
  // needs to be done before the .moveTo() and .lineTo() calls, but must be
  // undone before the .stroke() call to ensure that the stroke width is
  // unaffected.  An alternative is to reduce the stroke width in the
  // transformed coordinate space, but you can't specify different values for
  // each dimension (as you can with .scale()). The speedup here is ~12%.
  var sets = this.layout.points;
  for (var i = sets.length; i--;) {
    var points = sets[i];
    for (var j = points.length; j--;) {
      var point = points[j];
      point.canvasx = this.area.w * point.x + this.area.x;
      point.canvasy = this.area.h * point.y + this.area.y;
    }
  }
};

/**
 * Add canvas Actually draw the lines chart, including error bars.
 * If opt_seriesName is specified, only that series will be drawn.
 * (This is used for expedited redrawing with highlightSeriesOpts)
 * Lines are typically drawn in the non-interactive dygraph canvas. If opt_ctx
 * is specified, they can be drawn elsewhere.
 *
 * This function can only be called if DygraphLayout's points array has been
 * updated with canvas{x,y} attributes, i.e. by
 * DygraphCanvasRenderer._updatePoints.
 * @private
 */
DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) {
  var ctx = opt_ctx || this.elementContext;
  var errorBars = this.attr_("errorBars") || this.attr_("customBars");
  var fillGraph = this.attr_("fillGraph");
  var i;

  var sets = this.layout.points;
  var setNames = this.layout.setNames;
  var setCount = setNames.length;
  var setName;

  this.colors = this.dygraph_.colorsMap_;

  // Determine which series have specialized plotters.
  var plotter_attr = this.attr_("plotter");
  var plotters = plotter_attr;
  if (!Dygraph.isArrayLike(plotters)) {
    plotters = [plotters];
  }

  var setPlotters = {};  // series name -> plotter fn.
  for (i = 0; i < setNames.length; i++) {
    setName = setNames[i];
    var setPlotter = this.attr_("plotter", setName);
    if (setPlotter == plotter_attr) continue;  // not specialized.

    setPlotters[setName] = setPlotter;
  }

  for (i = 0; i < plotters.length; i++) {
    var plotter = plotters[i];
    var is_last = (i == plotters.length - 1);

    for (var j = 0; j < sets.length; j++) {
      setName = setNames[j];
      if (opt_seriesName && setName != opt_seriesName) continue;

      var points = sets[j];

      // Only throw in the specialized plotters on the last iteration.
      var p = plotter;
      if (setName in setPlotters) {
        if (is_last) {
          p = setPlotters[setName];
        } else {
          // Don't use the standard plotters in this case.
          continue;
        }
      }

      var color = this.colors[setName];
      var strokeWidth = this.dygraph_.getOption("strokeWidth", setName);

      ctx.save();
      ctx.strokeStyle = color;
      ctx.lineWidth = strokeWidth;
      p({
        points: points,
        setName: setName,
        drawingContext: ctx,
        color: color,
        strokeWidth: strokeWidth,
        dygraph: this.dygraph_,
        axis: this.dygraph_.axisPropertiesForSeries(setName),
        plotArea: this.area,
        seriesIndex: j,
        seriesCount: sets.length,
        allSeriesPoints: sets
      });
      ctx.restore();
    }
  }
};

/**
 * Standard plotters. These may be used by clients via Dygraph.Plotters.
 * See comments there for more details.
 */
DygraphCanvasRenderer._Plotters = {
  linePlotter: function(e) {
    DygraphCanvasRenderer._linePlotter(e);
  },

  fillPlotter: function(e) {
    DygraphCanvasRenderer._fillPlotter(e);
  },

  errorPlotter: function(e) {
    DygraphCanvasRenderer._errorPlotter(e);
  }
};

/**
 * Plotter which draws the central lines for a series.
 * @private
 */
DygraphCanvasRenderer._linePlotter = function(e) {
  var g = e.dygraph;
  var setName = e.setName;
  var strokeWidth = e.strokeWidth;

  // TODO(danvk): Check if there's any performance impact of just calling
  // getOption() inside of _drawStyledLine. Passing in so many parameters makes
  // this code a bit nasty.
  var borderWidth = g.getOption("strokeBorderWidth", setName);
  var drawPointCallback = g.getOption("drawPointCallback", setName) ||
      Dygraph.Circles.DEFAULT;
  var strokePattern = g.getOption("strokePattern", setName);
  var drawPoints = g.getOption("drawPoints", setName);
  var pointSize = g.getOption("pointSize", setName);

  if (borderWidth && strokeWidth) {
    DygraphCanvasRenderer._drawStyledLine(e,
        g.getOption("strokeBorderColor", setName),
        strokeWidth + 2 * borderWidth,
        strokePattern,
        drawPoints,
        drawPointCallback,
        pointSize
        );
  }

  DygraphCanvasRenderer._drawStyledLine(e,
      e.color,
      strokeWidth,
      strokePattern,
      drawPoints,
      drawPointCallback,
      pointSize
  );
};

/**
 * Draws the shaded error bars/confidence intervals for each series.
 * This happens before the center lines are drawn, since the center lines
 * need to be drawn on top of the error bars for all series.
 * @private
 */
DygraphCanvasRenderer._errorPlotter = function(e) {
  var g = e.dygraph;
  var setName = e.setName;
  var errorBars = g.getOption("errorBars") || g.getOption("customBars");
  if (!errorBars) return;

  var fillGraph = g.getOption("fillGraph", setName);
  if (fillGraph) {
    g.warn("Can't use fillGraph option with error bars");
  }

  var ctx = e.drawingContext;
  var color = e.color;
  var fillAlpha = g.getOption('fillAlpha', setName);
  var stepPlot = g.getOption('stepPlot');  // TODO(danvk): per-series
  var axis = e.axis;
  var points = e.points;

  var iter = Dygraph.createIterator(points, 0, points.length,
      DygraphCanvasRenderer._getIteratorPredicate(
          g.getOption("connectSeparatedPoints")));

  var newYs;

  // setup graphics context
  var prevX = NaN;
  var prevY = NaN;
  var prevYs = [-1, -1];
  var yscale = axis.yscale;
  // should be same color as the lines but only 15% opaque.
  var rgb = new RGBColor(color);
  var err_color =
      'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
  ctx.fillStyle = err_color;
  ctx.beginPath();

  var isNullUndefinedOrNaN = function(x) {
    return (x === null ||
            x === undefined ||
            isNaN(x));
  };

  while (iter.hasNext) {
    var point = iter.next();
    if ((!stepPlot && isNullUndefinedOrNaN(point.y)) ||
        (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) {
      prevX = NaN;
      continue;
    }

    if (stepPlot) {
      newYs = [ point.y_bottom, point.y_top ];
      prevY = point.y;
    } else {
      newYs = [ point.y_bottom, point.y_top ];
    }
    newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y;
    newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y;
    if (!isNaN(prevX)) {
      if (stepPlot) {
        ctx.moveTo(prevX, prevYs[0]);
        ctx.lineTo(point.canvasx, prevYs[0]);
        ctx.lineTo(point.canvasx, prevYs[1]);
      } else {
        ctx.moveTo(prevX, prevYs[0]);
        ctx.lineTo(point.canvasx, newYs[0]);
        ctx.lineTo(point.canvasx, newYs[1]);
      }
      ctx.lineTo(prevX, prevYs[1]);
      ctx.closePath();
    }
    prevYs = newYs;
    prevX = point.canvasx;
  }
  ctx.fill();
};

/**
 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
 * error bars.
 *
 * For stacked charts, it's more convenient to handle all the series
 * simultaneously. So this plotter plots all the points on the first series
 * it's asked to draw, then ignores all the other series.
 *
 * @private
 */
DygraphCanvasRenderer._fillPlotter = function(e) {
  // We'll handle all the series at once, not one-by-one.
  if (e.seriesIndex !== 0) return;

  var g = e.dygraph;
  var setNames = g.getLabels().slice(1);  // remove x-axis

  // getLabels() includes names for invisible series, which are not included in
  // allSeriesPoints. We remove those to make the two match.
  // TODO(danvk): provide a simpler way to get this information.
  for (var i = setNames.length; i >= 0; i--) {
    if (!g.visibility()[i]) setNames.splice(i, 1);
  }

  var anySeriesFilled = (function() {
    for (var i = 0; i < setNames.length; i++) {
      if (g.getOption("fillGraph", setNames[i])) return true;
    }
    return false;
  })();

  if (!anySeriesFilled) return;

  var ctx = e.drawingContext;
  var area = e.plotArea;
  var sets = e.allSeriesPoints;
  var setCount = sets.length;

  var fillAlpha = g.getOption('fillAlpha');
  var stepPlot = g.getOption('stepPlot');
  var stackedGraph = g.getOption("stackedGraph");
  var colors = g.getColors();

  var baseline = {};  // for stacked graphs: baseline for filling
  var currBaseline;

  // process sets in reverse order (needed for stacked graphs)
  for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) {
    var setName = setNames[setIdx];
    if (!g.getOption('fillGraph', setName)) continue;

    var color = colors[setIdx];
    var axis = g.axisPropertiesForSeries(setName);
    var axisY = 1.0 + axis.minyval * axis.yscale;
    if (axisY < 0.0) axisY = 0.0;
    else if (axisY > 1.0) axisY = 1.0;
    axisY = area.h * axisY + area.y;

    var points = sets[setIdx];
    var iter = Dygraph.createIterator(points, 0, points.length,
        DygraphCanvasRenderer._getIteratorPredicate(
            g.getOption("connectSeparatedPoints")));

    // setup graphics context
    var prevX = NaN;
    var prevYs = [-1, -1];
    var newYs;
    var yscale = axis.yscale;
    // should be same color as the lines but only 15% opaque.
    var rgb = new RGBColor(color);
    var err_color =
        'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
    ctx.fillStyle = err_color;
    ctx.beginPath();
    while(iter.hasNext) {
      var point = iter.next();
      if (!Dygraph.isOK(point.y)) {
        prevX = NaN;
        continue;
      }
      if (stackedGraph) {
        currBaseline = baseline[point.canvasx];
        var lastY;
        if (currBaseline === undefined) {
          lastY = axisY;
        } else {
          if(stepPlot) {
            lastY = currBaseline[0];
          } else {
            lastY = currBaseline;
          }
        }
        newYs = [ point.canvasy, lastY ];

        if(stepPlot) {
          // Step plots must keep track of the top and bottom of
          // the baseline at each point.
          if(prevYs[0] === -1) {
            baseline[point.canvasx] = [ point.canvasy, axisY ];
          } else {
            baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
          }
        } else {
          baseline[point.canvasx] = point.canvasy;
        }

      } else {
        newYs = [ point.canvasy, axisY ];
      }
      if (!isNaN(prevX)) {
        ctx.moveTo(prevX, prevYs[0]);

        if (stepPlot) {
          ctx.lineTo(point.canvasx, prevYs[0]);
          if(currBaseline) {
            // Draw to the bottom of the baseline
            ctx.lineTo(point.canvasx, currBaseline[1]);
          } else {
            ctx.lineTo(point.canvasx, newYs[1]);
          }
        } else {
          ctx.lineTo(point.canvasx, newYs[0]);
          ctx.lineTo(point.canvasx, newYs[1]);
        }

        ctx.lineTo(prevX, prevYs[1]);
        ctx.closePath();
      }
      prevYs = newYs;
      prevX = point.canvasx;
    }
    ctx.fill();
  }
};


text:
{-# LANGUAGE
      GADTs
    , DeriveDataTypeable
    , DeriveGeneric
    , TemplateHaskell
    #-}

module Likelyhood where

import Evidence
import Data.List
import Data.Typeable
import GHC.Generics
import Data.Aeson.TH

-- Likelyhood isn't evidence! It can generate distributions of evidence or be derived from populations of Evidence
data Likelyhood name p =
    Likelyhood name (Probability p)
    deriving (Generic, Show, Typeable, Eq, Ord)

$(deriveJSON defaultOptions ''Likelyhood)

data Alternatives name r = Alternatives [Evidence name r]
    deriving (Generic, Show, Typeable, Eq, Ord)

$(deriveJSON defaultOptions ''Alternatives)

alternatively :: Evidence name r -> Alternatives name r -> Alternatives name r
alternatively alt (Alternatives alts) = Alternatives $ alt:alts

toggle_alternative :: (Eq r, Eq name) => Evidence name r -> Alternatives name r -> Alternatives name r
toggle_alternative alt (Alternatives alts) = if elem alt alts then Alternatives (delete alt alts) else Alternatives $ alt:alts

data Potential name p r =
      Likely [Likelyhood name p]
    | Alternatively (Alternatives name r)

likely :: Truthy a => name -> a -> Likelyhood name a
likely name p = Likelyhood name (P p)

-- fifty fifty, maximum entropy?
chaotic :: (Truthy a, Fractional a) => name -> Likelyhood name a
chaotic name = Likelyhood name (P (recip 2))

pick :: (Ord like, Eq name, Eq like, Eq r, Truthy r) => like -> Likelyhood name like -> Evidence name r
pick random (Likelyhood name (P like)) =
    Evidence name (P (if random <= like then yes else no))

-- Select from alternatives should yield mutually exclusive evidence
select :: (RealFrac random, Eq name, Eq r, Truthy r) => random -> Alternatives name r -> [Evidence name r]
select random (Alternatives alts) = map decide (zip alts [(0::Int)..])
    where
        index = truncate $ random * (fromRational (toRational (length alts)))
        decide (alt, idx) = if idx == index then alt else dual alt

all_combinations :: Truthy r => Alternatives name r -> [[Evidence name r]]
all_combinations (Alternatives alts) = map indicate [1..length alts]
    where
        indicate indicator = map (\(alt, index) -> if index == indicator then alt else dual alt) (zip alts [1..])


text:
describe("agendamento", function(){

	var pacienteJoao;
	var agenda;

	beforeEach(function(){
	 	pacienteJoao = new pacienteBuilder().constroi;
		agenda = new agendamento();
	});

	it ("deve agendar 20 dias depois", function(){
		var consultaJoao = new consulta(pacienteJoao, [], true, true, new Date(2014, 7, 1));
		var novaConsulta = new agenda.para(consultaJoao);

		expect(novaConsulta.getData()).toEqual(new Date(2014, 7, 21));
	});

	it ("deve pular fim de semanas", function(){
		var consultaJoao = new consulta(pacienteJoao, [], true, true, new Date(2014, 5, 30));
		var novaConsulta = new agenda.para(consultaJoao);

		expect(novaConsulta.getData()).toEqual(new Date(2014, 6, 21));
	});
});


text:
package com.pongasoft.kiwidoc.builder.serializer.tag;

import com.pongasoft.kiwidoc.builder.serializer.Serializer;
import com.pongasoft.kiwidoc.builder.serializer.SerializerException;
import com.pongasoft.kiwidoc.model.tag.InlineTextTag;

/**
 * @author yan@pongasoft.com
 */
public class InlineTextTagSerializer implements Serializer<InlineTextTag, Object>
{
  public Object serialize(InlineTextTag tag) throws SerializerException
  {
    return tag.getText();
  }

  public InlineTextTag deserialize(Object context, Object objectToDeserialize) throws SerializerException
  {
    return new InlineTextTag(String.valueOf(objectToDeserialize));
  }
}


text:
import React, { Component } from 'react';
import {
  Router
} from 'react-router';
import { Provider } from 'react-redux';
import store, { history } from '../store';
import routes from '../routes';

class Root extends Component {
  render() {
    return (
      <Provider store={store}>
        <Router history={history} routes={routes} />
      </Provider>
    );
  }
}

export default Root;


text:
<?php
namespace Console\Service\Exception;

class AddressAlreadyExsistException extends \Exception
{

}


text:
// Copyright (c) 2004  Dustin Sallings <dustin@spy.net>

package net.spy.db;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import net.spy.SpyObject;
import net.spy.concurrent.TrackingScheduledExecutor;
import net.spy.util.SpyConfig;

/**
 * Asynchronous Saver.
 */
public class TransactionPipeline extends SpyObject {

	// Thread pool name
	private static final String POOL_NAME="TransactionPipeline Worker";
	// Default size of the transaction pipeline pool
	private static final int DEFAULT_POOL_SIZE=1;

	// Minimum amount of time (in milliseconds) a transaction has to have been
	// in the pipeline before it will be considered for processing
	private static final int MIN_TRANS_AGE=500;

	// The thread pool.
	private ScheduledExecutorService pool;

	/**
	 * Get an instance of TransactionPipeline.
	 *
	 * @param tg the thread group under which threads will be created
	 * @param name an optional suffix to the names of the worker created
	 */
	public TransactionPipeline(ThreadGroup tg, String name) {
		super();
		final String n=POOL_NAME+(name==null?"": " " + name);
		pool=new TrackingScheduledExecutor(DEFAULT_POOL_SIZE, tg, n);
	}

	/**
	 * Get a transaction pipeline with no specific name.
	 */
	public TransactionPipeline() {
		this(null, null);
	}

	/**
	 * Shut down the pipeline.
	 */
	public synchronized void shutdown() {
		assert pool != null : "Trying to double-shutdown a pool.";
		pool.shutdown();
		pool = null;
	}

	/**
	 * Add a transaction to the pipeline.
	 *
	 * @param s the savable
	 * @param conf the configuration
	 * @param context a context for the save
	 */
	public ScheduledFuture<?> addTransaction(
			Savable s, SpyConfig conf, SaveContext ctx) {
		return pool.schedule(new PipelineTask(s, conf, ctx), MIN_TRANS_AGE,
				TimeUnit.MILLISECONDS);
	}

	/**
	 * Add a transaction to the pipeline without a context.
	 *
	 * @param s the savable
	 * @param conf the configuration
	 */
	public ScheduledFuture<?> addTransaction(Savable s, SpyConfig conf) {
		return addTransaction(s, conf, null);
	}

	static final class PipelineTask extends SpyObject
		implements Runnable {

		// Throwable filled in with the stack holding the context of where the
		// pipeline request was original requested
		private Throwable originalStack=null;

		private Savable toSave=null;
		private SpyConfig conf=null;
		private SaveContext context=null;

		PipelineTask(Savable s, SpyConfig cnf, SaveContext ctx) {
			super();
			this.originalStack=new Exception("Original request");
			originalStack.fillInStackTrace();

			this.toSave=s;
			conf=cnf;
			context=ctx;
		}

		/**
		 * Run the transaction.
		 */
		public void run() {
			try {
				new Saver(conf, context).save(toSave);
			} catch(Throwable t) {
				getLogger().error("Error saving asynchronous transaction", t);
				getLogger().error("Sent from", originalStack);
			}
		} // run()

	} // class PipelineTask

} // class TransactionPipeline


text:
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi" xmlns:mdattr="urn:oasis:names:tc:SAML:metadata:attribute" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:shibmd="urn:mace:shibboleth:metadata:1.0" xmlns:mdui="urn:oasis:names:tc:SAML:metadata:ui" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" entityID="https://katalog.svkos.cz/idp/shibboleth">
    <md:Extensions>
      <mdrpi:RegistrationInfo registrationAuthority="http://www.eduid.cz/" registrationInstant="2014-01-08T16:18:12Z">
        <mdrpi:RegistrationPolicy xml:lang="en">http://www.eduid.cz/wiki/_media/en/eduid/policy/policy_eduid_en-1_1.pdf</mdrpi:RegistrationPolicy>
        <mdrpi:RegistrationPolicy xml:lang="cs">http://www.eduid.cz/wiki/_media/eduid/policy/policy_eduid_cz-1_1-3.pdf</mdrpi:RegistrationPolicy>
      </mdrpi:RegistrationInfo>
      <mdattr:EntityAttributes>
        <saml:Attribute Name="http://macedir.org/entity-category" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
          <saml:AttributeValue>http://eduid.cz/uri/idp-group/library</saml:AttributeValue>
        </saml:Attribute>
      </mdattr:EntityAttributes>
    </md:Extensions>
    <md:IDPSSODescriptor protocolSupportEnumeration="urn:mace:shibboleth:1.0 urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:2.0:protocol">
      <md:Extensions>
        <eduidmd:RepublishRequest xmlns:eduidmd="http://eduid.cz/schema/metadata/1.0">
          <eduidmd:RepublishTarget>http://edugain.org/</eduidmd:RepublishTarget>
        </eduidmd:RepublishRequest>
        <shibmd:Scope regexp="false">svkos.cz</shibmd:Scope>
        <mdui:UIInfo>
          <mdui:DisplayName xml:lang="en">Moravian-Silesian Research Library in Ostrava</mdui:DisplayName>
          <mdui:DisplayName xml:lang="cs">Moravskoslezská vědecká knihovna v Ostravě</mdui:DisplayName>
          <mdui:Description xml:lang="en">Identity Provider for patrons and staff of Moravian-Silesian Research Library in Ostrava</mdui:Description>
          <mdui:Description xml:lang="cs">Identity Provider pro čtenáře a zaměstance Moravskoslezské vědecké knihovny v Ostravě</mdui:Description>
          <mdui:InformationURL xml:lang="en">http://www.svkos.cz/en/</mdui:InformationURL>
          <mdui:InformationURL xml:lang="cs">http://www.svkos.cz/</mdui:InformationURL>
          <mdui:Logo height="40" width="40">https://katalog.svkos.cz/logo/logo_40.png</mdui:Logo>
          <mdui:Logo height="90" width="91">https://katalog.svkos.cz/logo/logo_90.png</mdui:Logo>
        </mdui:UIInfo>
      </md:Extensions>
      <md:KeyDescriptor>
        <ds:KeyInfo>
          <ds:X509Data>
            <ds:X509Certificate>
MIIDKzCCAhOgAwIBAgIUMysVZyotzMFN08smrMEjxr7cBg4wDQYJKoZIhvcNAQEF
BQAwGzEZMBcGA1UEAxMQa2F0YWxvZy5zdmtvcy5jejAeFw0xMzExMTEyMDIxMjJa
Fw0zMzExMTEyMDIxMjJaMBsxGTAXBgNVBAMTEGthdGFsb2cuc3Zrb3MuY3owggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCMXDtGvbcdogNvhJbrKZmDxFqb
9VJ33XYnH+mBPdndP5kMDcE70SZqBpJQlP4JP+0GvETydNlHnK/t7TUE8SyRV+5y
dLMeuFnAvP4So2OGfJfcivVizSvNSKuiYWBO2c7z90E3e0qBET0/gBSZ/lMvNSu5
GS7Xe3+j35NGUiwGIzRglMKOAPxiA+szn0wIBsG7JhMdHuZMUASeVJewAxlPVv1p
C7BrtRYVPmHm8xfqoTFg9RJz8nWDfugKLOPeVfdB17UwQICMYLM6pCvCmDGZ3SFz
k83oy1GqWnfsXasaEWAL9VpQI5keYO34kgjRadlrSCjaMCSwPEgII6Z7J88HAgMB
AAGjZzBlMEQGA1UdEQQ9MDuCEGthdGFsb2cuc3Zrb3MuY3qGJ2h0dHBzOi8va2F0
YWxvZy5zdmtvcy5jei9pZHAvc2hpYmJvbGV0aDAdBgNVHQ4EFgQUS5NR0hEzdvRO
kCB+T+bV6A3WQG8wDQYJKoZIhvcNAQEFBQADggEBAHVlLp4Vdb1zrlGQVO0AZBoz
pPpRx2+MW9nasMPsd8ybYW/mbvAQU1c1MaUCK+rRk3Tu+Jj08A6YJOY5x/yLXxjh
Us6l6JqIDYn6M/44vMf0fH+DkA40zfnpI8fv07O5Oc8EV1MsBdQm6zBh19MmDxY8
diuVwTi1E9kR6Q3RIzhH1TERBDOpIfsUGVv5IHywYlUYsxYfOy6A0FjEtenMpfsI
4NMjUoYVfnC0z5aWU7Vdu5LJIfkNj4HCuxLZur7NBvX3UTEuegzZRewy5edw+/hp
K1WmgwfZhpsu54HYP1WZcpvCC4nCiZ9b1wiwdAixsl/orsvhTGeJVLtV1MbEaHY=

                    </ds:X509Certificate>
          </ds:X509Data>
        </ds:KeyInfo>
      </md:KeyDescriptor>
      <md:ArtifactResolutionService Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://katalog.svkos.cz:8443/idp/profile/SAML1/SOAP/ArtifactResolution" index="1"/>
      <md:ArtifactResolutionService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP" Location="https://katalog.svkos.cz:8443/idp/profile/SAML2/SOAP/ArtifactResolution" index="2"/>
      <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://katalog.svkos.cz/idp/profile/SAML2/Redirect/SLO"/>
      <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://katalog.svkos.cz/idp/profile/SAML2/POST/SLO"/>
      <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP" Location="https://katalog.svkos.cz:8443/idp/profile/SAML2/SOAP/SLO"/>
      <md:NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</md:NameIDFormat>
      <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>
      <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
      <md:SingleSignOnService Binding="urn:mace:shibboleth:1.0:profiles:AuthnRequest" Location="https://katalog.svkos.cz/idp/profile/Shibboleth/SSO"/>
      <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://katalog.svkos.cz/idp/profile/SAML2/POST/SSO"/>
      <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST-SimpleSign" Location="https://katalog.svkos.cz/idp/profile/SAML2/POST-SimpleSign/SSO"/>
      <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://katalog.svkos.cz/idp/profile/SAML2/Redirect/SSO"/>
    </md:IDPSSODescriptor>
    <md:AttributeAuthorityDescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:oasis:names:tc:SAML:2.0:protocol">
      <md:Extensions>
        <shibmd:Scope regexp="false">svkos.cz</shibmd:Scope>
      </md:Extensions>
      <md:KeyDescriptor>
        <ds:KeyInfo>
          <ds:X509Data>
            <ds:X509Certificate>
MIIDKzCCAhOgAwIBAgIUMysVZyotzMFN08smrMEjxr7cBg4wDQYJKoZIhvcNAQEF
BQAwGzEZMBcGA1UEAxMQa2F0YWxvZy5zdmtvcy5jejAeFw0xMzExMTEyMDIxMjJa
Fw0zMzExMTEyMDIxMjJaMBsxGTAXBgNVBAMTEGthdGFsb2cuc3Zrb3MuY3owggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCMXDtGvbcdogNvhJbrKZmDxFqb
9VJ33XYnH+mBPdndP5kMDcE70SZqBpJQlP4JP+0GvETydNlHnK/t7TUE8SyRV+5y
dLMeuFnAvP4So2OGfJfcivVizSvNSKuiYWBO2c7z90E3e0qBET0/gBSZ/lMvNSu5
GS7Xe3+j35NGUiwGIzRglMKOAPxiA+szn0wIBsG7JhMdHuZMUASeVJewAxlPVv1p
C7BrtRYVPmHm8xfqoTFg9RJz8nWDfugKLOPeVfdB17UwQICMYLM6pCvCmDGZ3SFz
k83oy1GqWnfsXasaEWAL9VpQI5keYO34kgjRadlrSCjaMCSwPEgII6Z7J88HAgMB
AAGjZzBlMEQGA1UdEQQ9MDuCEGthdGFsb2cuc3Zrb3MuY3qGJ2h0dHBzOi8va2F0
YWxvZy5zdmtvcy5jei9pZHAvc2hpYmJvbGV0aDAdBgNVHQ4EFgQUS5NR0hEzdvRO
kCB+T+bV6A3WQG8wDQYJKoZIhvcNAQEFBQADggEBAHVlLp4Vdb1zrlGQVO0AZBoz
pPpRx2+MW9nasMPsd8ybYW/mbvAQU1c1MaUCK+rRk3Tu+Jj08A6YJOY5x/yLXxjh
Us6l6JqIDYn6M/44vMf0fH+DkA40zfnpI8fv07O5Oc8EV1MsBdQm6zBh19MmDxY8
diuVwTi1E9kR6Q3RIzhH1TERBDOpIfsUGVv5IHywYlUYsxYfOy6A0FjEtenMpfsI
4NMjUoYVfnC0z5aWU7Vdu5LJIfkNj4HCuxLZur7NBvX3UTEuegzZRewy5edw+/hp
K1WmgwfZhpsu54HYP1WZcpvCC4nCiZ9b1wiwdAixsl/orsvhTGeJVLtV1MbEaHY=

                    </ds:X509Certificate>
          </ds:X509Data>
        </ds:KeyInfo>
      </md:KeyDescriptor>
      <md:AttributeService Binding="urn:oasis:names:tc:SAML:1.0:bindings:SOAP-binding" Location="https://katalog.svkos.cz:8443/idp/profile/SAML1/SOAP/AttributeQuery"/>
      <md:AttributeService Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP" Location="https://katalog.svkos.cz:8443/idp/profile/SAML2/SOAP/AttributeQuery"/>
      <md:NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</md:NameIDFormat>
      <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</md:NameIDFormat>
      <md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>
    </md:AttributeAuthorityDescriptor>
    <md:Organization>
      <md:OrganizationName xml:lang="cs">Moravskoslezská vědecká knihovna v Ostravě</md:OrganizationName>
      <md:OrganizationName xml:lang="en">Moravian-Silesian Research Library in Ostrava</md:OrganizationName>
      <md:OrganizationDisplayName xml:lang="cs">Moravskoslezská vědecká knihovna v Ostravě</md:OrganizationDisplayName>
      <md:OrganizationDisplayName xml:lang="en">Moravian-Silesian Research Library in Ostrava</md:OrganizationDisplayName>
      <md:OrganizationURL xml:lang="en">http://www.svkos.cz/en/</md:OrganizationURL>
      <md:OrganizationURL xml:lang="cs">http://www.svkos.cz/</md:OrganizationURL>
    </md:Organization>
    <md:ContactPerson contactType="technical">
      <md:GivenName>Magda</md:GivenName>
      <md:SurName>Zavilová</md:SurName>
      <md:EmailAddress>zavilova@svkos.cz</md:EmailAddress>
    </md:ContactPerson>
  </md:EntityDescriptor>


text:
define(['jquery','underscore', 'backbone','collections/releaseCollection','views/releaseListView'],
		function ($, _, Backbone, releaseCollection, releaseListView) {
	ReleaseView =  Backbone.View.extend({
		limit : 10,
		params : null,
		releaseCollection : null,
		currentIndex : 0,
		el:$('body'),
		singleReleaseTemplate : _.template($('#single-release-template').html()),
		editReleaseTemplate :  _.template($('#release-edit-template').html()),
		els:{
			table_data : '#releases',
			btnShowMore : 'a#show_more',
			sRelease : '#s-release',
			row : '.row',
			editContainer: ".edit-container",
			releaseName : "#releaseName",
		},
		events:{
			'click a#show_more' : 'showMore',
			'click .getRelease' : 'getRelease',
			'click .deleteRelease' : 'deleteRelease',
			'click .editRelease' : 'editRelease',
			'click .btnCancel' : 'cancelEdit',
			'click .saveEditedRelease' : 'saveEditedRelease',
			'click #release' : 'reloadRecord',
			'click .cancelEdit' : 'cancelEdit'

		},
        initialize: function () {
        	this.params = {};
        	this.collection = new releaseCollection();
        	this.fetchRecord();
        },
        fetchRecord : function(e) {
        	self = this;
        	this.collection.fetch({
        		async : false,
        		data : self.params,
    		      success: function(){
    		    	  self.render();
    		      }
        	});
        	this.params = {};
        },
        reloadRecord : function (){
        	this.fetchRecord();
        },
        render : function(){
        	this.$el.find(this.els.row).remove();
        	releases = this.collection.models;
        	_.each(releases.slice(this.currentIndex,(this.currentIndex + this.limit)), function(data) {
        		data = data.toJSON();
    			this.$el.find(this.els.table_data).append(new releaseListView({
    				id : 'release_' + data.releaseId,
    				model : data
    			}).render().el);
    		}, this);
    		return this;
        },
        getRelease : function (e){
        	releaseId = e.target.id.split('_')[1];
        	this.params.id = releaseId;
        	this.fetchRecord();
        },
        showMore : function(){
        	this.currentIndex = this.currentIndex + this.limit;
        	if(this.currentIndex >= this.collection.models[0].length){
        		this.$el.find(this.els.btnShowMore).hide();
        	}
        	this.render();
        },
        deleteRelease : function(e){
        	releaseId = e.target.id.split('_')[1];
        	release = {'releaseId' : Number(releaseId)};
        	var deletedRelease = this.collection.where(release)[0];
             var flag = confirm('Are you sure you want to delete Genre details?');
             if(flag){
                 this.collection.remove(deletedRelease);
                 this.destroyRelease(deletedRelease);
             }
        },
        destroyRelease: function (target) {
        	self = this;
            if(target.get('releaseId')!=0){
            	target.set('id',target.get('releaseId'));
            }
            target.destroy({
            	success: function (status, data) {
            		self.render();
                },
                error: function(model, xhr, options){
                },
            	wait : true
            });
        },
        editRelease:function(e){
        	release = {};
        	releaseId = Number(e.target.id.split('_')[1]);
        	release.releaseId = releaseId;
        	release.releaseName = this.collection.where({'releaseId' : release.releaseId})[0].get("releaseName");
        	release.upc = this.collection.where({'releaseId' : release.releaseId})[0].get("upc");
        	release.genreId = this.collection.where({'releaseId' : release.releaseId})[0].get("genreId");
        	this.$el.find("#release_"+releaseId).attr("class", "edit-container").html(this.editReleaseTemplate(release));
        },
        saveEditedRelease: function (e) {
            e.preventDefault();
            var edited = this.collection.where({'releaseId' : Number(this.$el.find(this.els.editContainer).attr('id').split('_')[1])})[0];
            releaseName = $(this.els.releaseName).val(),
            newupc = $(this.els.editupc).val(),
            newrelease_id = this.$el.find(this.els.editContainer).attr('id').split('_')[1];
            edited.set({id: this.$el.find(this.els.editContainer).attr('id').split('_')[1], releaseName: $.trim(releaseName), upc: newupc, releaseId : newrelease_id});
            this.saveRelease(edited);
            this.cancelEdit();
        },
        saveRelease : function(release){
        	var that=this;
        	release.save(release,{
                success: function(model, response, options){
                	if(response!=1){
                		release.set("releaseId", String(response));
                	}
                	that.render();
                },
                error: function(model, xhr, options){
                    xhr.fault = {"networkError": 'We\'re sorry, a network error occured when trying to save this genre.'};
                },
                wait: true
            });
        },
        cancelEdit: function () {
            this.$el.find(this.els.editContainer).remove();
            this.render();
        },
        add_release_event : function(e){
        	e.preventDefault();
        	newReleaseName = $(this.els.releasename_add).val();
        	newUpc = $(this.els.upc_add).val();
        	 var addedrelease = new Release_model({
                 release_name : $.trim(newReleaseName),
                 upc : $.trim(newUpc)
             });
        	 this.collection.add(addedrelease);
        	 this.save_release(addedrelease);
        }
    });
	return ReleaseView;
});