text:
"""Change keystone_id for external_id in Project model

Revision ID: 256da65e0c5f
Revises: 795737bb3c3
Create Date: 2014-12-22 03:55:29.072375

"""

# revision identifiers, used by Alembic.
revision = '256da65e0c5f'
down_revision = '795737bb3c3'

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.alter_column('projects', 'keystone_id',
                    type_=sa.String(36),
                    new_column_name='external_id')

def downgrade():
    op.alter_column('projects', 'external_id',
                    type_=sa.String(36),
                    new_column_name='keystone_id')

redpajama_set_name: RedPajamaGithub


text:
#ifndef NX_PHYSICS_NXPRISMATICJOINTDESC
#define NX_PHYSICS_NXPRISMATICJOINTDESC
/*----------------------------------------------------------------------------*\
|
|						Public Interface to Ageia PhysX Technology
|
|							     www.ageia.com
|
\*----------------------------------------------------------------------------*/
/** \addtogroup physics
  @{
*/

#include "Nxp.h"
#include "NxJointDesc.h"
/**
\brief Desc class for #NxPrismaticJoint.

<b>Platform:</b>
\li PC SW: Yes
\li PPU  : Yes
\li PS3  : Yes
\li XB360: Yes

@see NxJointDesc NxPrismaticJoint NxScene.createJoint
*/
class NxPrismaticJointDesc : public NxJointDesc
	{
	public:
	/**
	\brief Constructor sets to default.
	*/
	NX_INLINE NxPrismaticJointDesc();

	/**
	\brief (re)sets the structure to the default.
	*/
	NX_INLINE void setToDefault();

	/**
	\brief Returns true if the descriptor is valid.
	\return true if the current settings are valid
	*/
	NX_INLINE bool isValid() const;

	};

NX_INLINE NxPrismaticJointDesc::NxPrismaticJointDesc() : NxJointDesc(NX_JOINT_PRISMATIC)	//constructor sets to default
	{
	setToDefault();
	}

NX_INLINE void NxPrismaticJointDesc::setToDefault()
	{
	NxJointDesc::setToDefault();
	}

NX_INLINE bool NxPrismaticJointDesc::isValid() const
	{
	return NxJointDesc::isValid();
	}

/** @} */
#endif
//AGCOPYRIGHTBEGIN
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2005 AGEIA Technologies.
// All rights reserved. www.ageia.com
///////////////////////////////////////////////////////////////////////////
//AGCOPYRIGHTEND


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Magazin Ges. naturf. Freunde, Berlin 8: 28 (1816)

#### Original name
Uredo rhinanthearum Link, 1816

### Remarks
null


text:
suite('google birthday events', function() {

  var icsData;
  var stringified;

  testSupport.defineSample('google_birthday.ics', function(data) {
    icsData = data;
  });

  test('expanding malformatted recurring event', function(done) {
    // just verify it can parse forced types
    var parser = new ICAL.ComponentParser();
    var primary;
    var exceptions = [];

    var expectedDates = [
      new Date(2012, 11, 10),
      new Date(2013, 11, 10),
      new Date(2014, 11, 10)
    ];

    parser.onevent = function(event) {
      if (event.isRecurrenceException()) {
        exceptions.push(event);
      } else {
        primary = event;
      }
    }

    parser.oncomplete = function() {
      exceptions.forEach(function(item) {
        primary.relateException(item);
      });

      var iter = primary.iterator();
      var next;
      var dates = [];
      while ((next = iter.next())) {
        dates.push(next.toJSDate());
      }

      assert.deepEqual(
        dates,
        expectedDates
      );

      done();
    }

    parser.process(icsData);
  });
});


text:
/*
Package otto is a JavaScript parser and interpreter written natively in Go.

http://godoc.org/github.com/robertkrimen/otto

    import (
        "github.com/robertkrimen/otto"
    )

Run something in the VM

    vm := otto.New()
    vm.Run(`
        abc = 2 + 2;
    	console.log("The value of abc is " + abc); // 4
    `)

Get a value out of the VM

    value, err := vm.Get("abc")
    	value, _ := value.ToInteger()
    }

Set a number

    vm.Set("def", 11)
    vm.Run(`
    	console.log("The value of def is " + def);
    	// The value of def is 11
    `)

Set a string

    vm.Set("xyzzy", "Nothing happens.")
    vm.Run(`
    	console.log(xyzzy.length); // 16
    `)

Get the value of an expression

    value, _ = vm.Run("xyzzy.length")
    {
    	// value is an int64 with a value of 16
    	value, _ := value.ToInteger()
    }

An error happens

    value, err = vm.Run("abcdefghijlmnopqrstuvwxyz.length")
    if err != nil {
    	// err = ReferenceError: abcdefghijlmnopqrstuvwxyz is not defined
    	// If there is an error, then value.IsUndefined() is true
    	...
    }

Set a Go function

    vm.Set("sayHello", func(call otto.FunctionCall) otto.Value {
        fmt.Printf("Hello, %s.\n", call.Argument(0).String())
        return otto.Value{}
    })

Set a Go function that returns something useful

    vm.Set("twoPlus", func(call otto.FunctionCall) otto.Value {
        right, _ := call.Argument(0).ToInteger()
        result, _ := vm.ToValue(2 + right)
        return result
    })

Use the functions in JavaScript

    result, _ = vm.Run(`
        sayHello("Xyzzy");      // Hello, Xyzzy.
        sayHello();             // Hello, undefined

        result = twoPlus(2.0); // 4
    `)

Parser

A separate parser is available in the parser package if you're just interested in building an AST.

http://godoc.org/github.com/robertkrimen/otto/parser

Parse and return an AST

    filename := "" // A filename is optional
    src := `
        // Sample xyzzy example
        (function(){
            if (3.14159 > 0) {
                console.log("Hello, World.");
                return;
            }

            var xyzzy = NaN;
            console.log("Nothing happens.");
            return xyzzy;
        })();
    `

    // Parse some JavaScript, yielding a *ast.Program and/or an ErrorList
    program, err := parser.ParseFile(nil, filename, src, 0)

otto

You can run (Go) JavaScript from the commandline with: http://github.com/robertkrimen/otto/tree/master/otto

	$ go get -v github.com/robertkrimen/otto/otto

Run JavaScript by entering some source on stdin or by giving otto a filename:

	$ otto example.js

underscore

Optionally include the JavaScript utility-belt library, underscore, with this import:

	import (
		"github.com/robertkrimen/otto"
		_ "github.com/robertkrimen/otto/underscore"
	)

	// Now every otto runtime will come loaded with underscore

For more information: http://github.com/robertkrimen/otto/tree/master/underscore

Caveat Emptor

The following are some limitations with otto:

    * "use strict" will parse, but does nothing.
    * The regular expression engine (re2/regexp) is not fully compatible with the ECMA5 specification.
    * Otto targets ES5. ES6 features (eg: Typed Arrays) are not supported.

Regular Expression Incompatibility

Go translates JavaScript-style regular expressions into something that is "regexp" compatible via `parser.TransformRegExp`.
Unfortunately, RegExp requires backtracking for some patterns, and backtracking is not supported by the standard Go engine: https://code.google.com/p/re2/wiki/Syntax

Therefore, the following syntax is incompatible:

    (?=)  // Lookahead (positive), currently a parsing error
    (?!)  // Lookahead (backhead), currently a parsing error
    \1    // Backreference (\1, \2, \3, ...), currently a parsing error

A brief discussion of these limitations: "Regexp (?!re)" https://groups.google.com/forum/?fromgroups=#%21topic/golang-nuts/7qgSDWPIh_E

More information about re2: https://code.google.com/p/re2/

In addition to the above, re2 (Go) has a different definition for \s: [\t\n\f\r ].
The JavaScript definition, on the other hand, also includes \v, Unicode "Separator, Space", etc.

Halting Problem

If you want to stop long running executions (like third-party code), you can use the interrupt channel to do this:

    package main

    import (
        "errors"
        "fmt"
        "os"
        "time"

        "github.com/robertkrimen/otto"
    )

    var halt = errors.New("Stahp")

    func main() {
        runUnsafe(`var abc = [];`)
        runUnsafe(`
        while (true) {
            // Loop forever
        }`)
    }

    func runUnsafe(unsafe string) {
        start := time.Now()
        defer func() {
            duration := time.Since(start)
            if caught := recover(); caught != nil {
                if caught == halt {
                    fmt.Fprintf(os.Stderr, "Some code took to long! Stopping after: %v\n", duration)
                    return
                }
                panic(caught) // Something else happened, repanic!
            }
            fmt.Fprintf(os.Stderr, "Ran code successfully: %v\n", duration)
        }()

        vm := otto.New()
        vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking

        go func() {
            time.Sleep(2 * time.Second) // Stop after two seconds
            vm.Interrupt <- func() {
                panic(halt)
            }
        }()

        vm.Run(unsafe) // Here be dragons (risky code)
    }

Where is setTimeout/setInterval?

These timing functions are not actually part of the ECMA-262 specification. Typically, they belong to the `windows` object (in the browser).
It would not be difficult to provide something like these via Go, but you probably want to wrap otto in an event loop in that case.

For an example of how this could be done in Go with otto, see natto:

http://github.com/robertkrimen/natto

Here is some more discussion of the issue:

* http://book.mixu.net/node/ch2.html

* http://en.wikipedia.org/wiki/Reentrancy_%28computing%29

* http://aaroncrane.co.uk/2009/02/perl_safe_signals/

*/
package otto

import (
	"fmt"
	"strings"

	"github.com/robertkrimen/otto/file"
	"github.com/robertkrimen/otto/registry"
)

// Otto is the representation of the JavaScript runtime. Each instance of Otto has a self-contained namespace.
type Otto struct {
	// Interrupt is a channel for interrupting the runtime. You can use this to halt a long running execution, for example.
	// See "Halting Problem" for more information.
	Interrupt chan func()
	runtime   *_runtime
}

// New will allocate a new JavaScript runtime
func New() *Otto {
	self := &Otto{
		runtime: newContext(),
	}
	self.runtime.otto = self
	self.runtime.traceLimit = 10
	self.Set("console", self.runtime.newConsole())

	registry.Apply(func(entry registry.Entry) {
		self.Run(entry.Source())
	})

	return self
}

func (otto *Otto) clone() *Otto {
	self := &Otto{
		runtime: otto.runtime.clone(),
	}
	self.runtime.otto = self
	return self
}

// Run will allocate a new JavaScript runtime, run the given source
// on the allocated runtime, and return the runtime, resulting value, and
// error (if any).
//
// src may be a string, a byte slice, a bytes.Buffer, or an io.Reader, but it MUST always be in UTF-8.
//
// src may also be a Script.
//
// src may also be a Program, but if the AST has been modified, then runtime behavior is undefined.
//
func Run(src interface{}) (*Otto, Value, error) {
	otto := New()
	value, err := otto.Run(src) // This already does safety checking
	return otto, value, err
}

// Run will run the given source (parsing it first if necessary), returning the resulting value and error (if any)
//
// src may be a string, a byte slice, a bytes.Buffer, or an io.Reader, but it MUST always be in UTF-8.
//
// If the runtime is unable to parse source, then this function will return undefined and the parse error (nothing
// will be evaluated in this case).
//
// src may also be a Script.
//
// src may also be a Program, but if the AST has been modified, then runtime behavior is undefined.
//
func (self Otto) Run(src interface{}) (Value, error) {
	value, err := self.runtime.cmpl_run(src, nil)
	if !value.safe() {
		value = Value{}
	}
	return value, err
}

// Eval will do the same thing as Run, except without leaving the current scope.
//
// By staying in the same scope, the code evaluated has access to everything
// already defined in the current stack frame. This is most useful in, for
// example, a debugger call.
func (self Otto) Eval(src interface{}) (Value, error) {
	if self.runtime.scope == nil {
		self.runtime.enterGlobalScope()
		defer self.runtime.leaveScope()
	}

	value, err := self.runtime.cmpl_eval(src, nil)
	if !value.safe() {
		value = Value{}
	}
	return value, err
}

// Get the value of the top-level binding of the given name.
//
// If there is an error (like the binding does not exist), then the value
// will be undefined.
func (self Otto) Get(name string) (Value, error) {
	value := Value{}
	err := catchPanic(func() {
		value = self.getValue(name)
	})
	if !value.safe() {
		value = Value{}
	}
	return value, err
}

func (self Otto) getValue(name string) Value {
	return self.runtime.globalStash.getBinding(name, false)
}

// Set the top-level binding of the given name to the given value.
//
// Set will automatically apply ToValue to the given value in order
// to convert it to a JavaScript value (type Value).
//
// If there is an error (like the binding is read-only, or the ToValue conversion
// fails), then an error is returned.
//
// If the top-level binding does not exist, it will be created.
func (self Otto) Set(name string, value interface{}) error {
	{
		value, err := self.ToValue(value)
		if err != nil {
			return err
		}
		err = catchPanic(func() {
			self.setValue(name, value)
		})
		return err
	}
}

func (self Otto) setValue(name string, value Value) {
	self.runtime.globalStash.setValue(name, value, false)
}

func (self Otto) SetDebuggerHandler(fn func(vm *Otto)) {
	self.runtime.debugger = fn
}

func (self Otto) SetRandomSource(fn func() float64) {
	self.runtime.random = fn
}

// SetStackDepthLimit sets an upper limit to the depth of the JavaScript
// stack. In simpler terms, this limits the number of "nested" function calls
// you can make in a particular interpreter instance.
//
// Note that this doesn't take into account the Go stack depth. If your
// JavaScript makes a call to a Go function, otto won't keep track of what
// happens outside the interpreter. So if your Go function is infinitely
// recursive, you're still in trouble.
func (self Otto) SetStackDepthLimit(limit int) {
	self.runtime.stackLimit = limit
}

// SetStackTraceLimit sets an upper limit to the number of stack frames that
// otto will use when formatting an error's stack trace. By default, the limit
// is 10. This is consistent with V8 and SpiderMonkey.
//
// TODO: expose via `Error.stackTraceLimit`
func (self Otto) SetStackTraceLimit(limit int) {
	self.runtime.traceLimit = limit
}

// MakeCustomError creates a new Error object with the given name and message,
// returning it as a Value.
func (self Otto) MakeCustomError(name, message string) Value {
	return self.runtime.toValue(self.runtime.newError(name, self.runtime.toValue(message), 0))
}

// MakeRangeError creates a new RangeError object with the given message,
// returning it as a Value.
func (self Otto) MakeRangeError(message string) Value {
	return self.runtime.toValue(self.runtime.newRangeError(self.runtime.toValue(message)))
}

// MakeSyntaxError creates a new SyntaxError object with the given message,
// returning it as a Value.
func (self Otto) MakeSyntaxError(message string) Value {
	return self.runtime.toValue(self.runtime.newSyntaxError(self.runtime.toValue(message)))
}

// MakeTypeError creates a new TypeError object with the given message,
// returning it as a Value.
func (self Otto) MakeTypeError(message string) Value {
	return self.runtime.toValue(self.runtime.newTypeError(self.runtime.toValue(message)))
}

// Context is a structure that contains information about the current execution
// context.
type Context struct {
	Filename   string
	Line       int
	Column     int
	Callee     string
	Symbols    map[string]Value
	This       Value
	Stacktrace []string
}

// Context returns the current execution context of the vm, traversing up to
// ten stack frames, and skipping any innermost native function stack frames.
func (self Otto) Context() Context {
	return self.ContextSkip(10, true)
}

// ContextLimit returns the current execution context of the vm, with a
// specific limit on the number of stack frames to traverse, skipping any
// innermost native function stack frames.
func (self Otto) ContextLimit(limit int) Context {
	return self.ContextSkip(limit, true)
}

// ContextSkip returns the current execution context of the vm, with a
// specific limit on the number of stack frames to traverse, optionally
// skipping any innermost native function stack frames.
func (self Otto) ContextSkip(limit int, skipNative bool) (ctx Context) {
	// Ensure we are operating in a scope
	if self.runtime.scope == nil {
		self.runtime.enterGlobalScope()
		defer self.runtime.leaveScope()
	}

	scope := self.runtime.scope
	frame := scope.frame

	for skipNative && frame.native && scope.outer != nil {
		scope = scope.outer
		frame = scope.frame
	}

	// Get location information
	ctx.Filename = "<unknown>"
	ctx.Callee = frame.callee

	switch {
	case frame.native:
		ctx.Filename = frame.nativeFile
		ctx.Line = frame.nativeLine
		ctx.Column = 0
	case frame.file != nil:
		ctx.Filename = "<anonymous>"

		if p := frame.file.Position(file.Idx(frame.offset)); p != nil {
			ctx.Line = p.Line
			ctx.Column = p.Column

			if p.Filename != "" {
				ctx.Filename = p.Filename
			}
		}
	}

	// Get the current scope this Value
	ctx.This = toValue_object(scope.this)

	// Build stacktrace (up to 10 levels deep)
	ctx.Symbols = make(map[string]Value)
	ctx.Stacktrace = append(ctx.Stacktrace, frame.location())
	for limit != 0 {
		// Get variables
		stash := scope.lexical
		for {
			for _, name := range getStashProperties(stash) {
				if _, ok := ctx.Symbols[name]; !ok {
					ctx.Symbols[name] = stash.getBinding(name, true)
				}
			}
			stash = stash.outer()
			if stash == nil || stash.outer() == nil {
				break
			}
		}

		scope = scope.outer
		if scope == nil {
			break
		}
		if scope.frame.offset >= 0 {
			ctx.Stacktrace = append(ctx.Stacktrace, scope.frame.location())
		}
		limit--
	}

	return
}

// Call the given JavaScript with a given this and arguments.
//
// If this is nil, then some special handling takes place to determine the proper
// this value, falling back to a "standard" invocation if necessary (where this is
// undefined).
//
// If source begins with "new " (A lowercase new followed by a space), then
// Call will invoke the function constructor rather than performing a function call.
// In this case, the this argument has no effect.
//
//      // value is a String object
//      value, _ := vm.Call("Object", nil, "Hello, World.")
//
//      // Likewise...
//      value, _ := vm.Call("new Object", nil, "Hello, World.")
//
//      // This will perform a concat on the given array and return the result
//      // value is [ 1, 2, 3, undefined, 4, 5, 6, 7, "abc" ]
//      value, _ := vm.Call(`[ 1, 2, 3, undefined, 4 ].concat`, nil, 5, 6, 7, "abc")
//
func (self Otto) Call(source string, this interface{}, argumentList ...interface{}) (Value, error) {

	thisValue := Value{}

	construct := false
	if strings.HasPrefix(source, "new ") {
		source = source[4:]
		construct = true
	}

	// FIXME enterGlobalScope
	self.runtime.enterGlobalScope()
	defer func() {
		self.runtime.leaveScope()
	}()

	if !construct && this == nil {
		program, err := self.runtime.cmpl_parse("", source+"()", nil)
		if err == nil {
			if node, ok := program.body[0].(*_nodeExpressionStatement); ok {
				if node, ok := node.expression.(*_nodeCallExpression); ok {
					var value Value
					err := catchPanic(func() {
						value = self.runtime.cmpl_evaluate_nodeCallExpression(node, argumentList)
					})
					if err != nil {
						return Value{}, err
					}
					return value, nil
				}
			}
		}
	} else {
		value, err := self.ToValue(this)
		if err != nil {
			return Value{}, err
		}
		thisValue = value
	}

	{
		this := thisValue

		fn, err := self.Run(source)
		if err != nil {
			return Value{}, err
		}

		if construct {
			result, err := fn.constructSafe(self.runtime, this, argumentList...)
			if err != nil {
				return Value{}, err
			}
			return result, nil
		}

		result, err := fn.Call(this, argumentList...)
		if err != nil {
			return Value{}, err
		}
		return result, nil
	}
}

// Object will run the given source and return the result as an object.
//
// For example, accessing an existing object:
//
//		object, _ := vm.Object(`Number`)
//
// Or, creating a new object:
//
//		object, _ := vm.Object(`({ xyzzy: "Nothing happens." })`)
//
// Or, creating and assigning an object:
//
//		object, _ := vm.Object(`xyzzy = {}`)
//		object.Set("volume", 11)
//
// If there is an error (like the source does not result in an object), then
// nil and an error is returned.
func (self Otto) Object(source string) (*Object, error) {
	value, err := self.runtime.cmpl_run(source, nil)
	if err != nil {
		return nil, err
	}
	if value.IsObject() {
		return value.Object(), nil
	}
	return nil, fmt.Errorf("value is not an object")
}

// ToValue will convert an interface{} value to a value digestible by otto/JavaScript.
func (self Otto) ToValue(value interface{}) (Value, error) {
	return self.runtime.safeToValue(value)
}

// Copy will create a copy/clone of the runtime.
//
// Copy is useful for saving some time when creating many similar runtimes.
//
// This method works by walking the original runtime and cloning each object, scope, stash,
// etc. into a new runtime.
//
// Be on the lookout for memory leaks or inadvertent sharing of resources.
func (in *Otto) Copy() *Otto {
	out := &Otto{
		runtime: in.runtime.clone(),
	}
	out.runtime.otto = out
	return out
}

// Object{}

// Object is the representation of a JavaScript object.
type Object struct {
	object *_object
	value  Value
}

func _newObject(object *_object, value Value) *Object {
	// value MUST contain object!
	return &Object{
		object: object,
		value:  value,
	}
}

// Call a method on the object.
//
// It is essentially equivalent to:
//
//		var method, _ := object.Get(name)
//		method.Call(object, argumentList...)
//
// An undefined value and an error will result if:
//
//		1. There is an error during conversion of the argument list
//		2. The property is not actually a function
//		3. An (uncaught) exception is thrown
//
func (self Object) Call(name string, argumentList ...interface{}) (Value, error) {
	// TODO: Insert an example using JavaScript below...
	// e.g., Object("JSON").Call("stringify", ...)

	function, err := self.Get(name)
	if err != nil {
		return Value{}, err
	}
	return function.Call(self.Value(), argumentList...)
}

// Value will return self as a value.
func (self Object) Value() Value {
	return self.value
}

// Get the value of the property with the given name.
func (self Object) Get(name string) (Value, error) {
	value := Value{}
	err := catchPanic(func() {
		value = self.object.get(name)
	})
	if !value.safe() {
		value = Value{}
	}
	return value, err
}

// Set the property of the given name to the given value.
//
// An error will result if the setting the property triggers an exception (i.e. read-only),
// or there is an error during conversion of the given value.
func (self Object) Set(name string, value interface{}) error {
	{
		value, err := self.object.runtime.safeToValue(value)
		if err != nil {
			return err
		}
		err = catchPanic(func() {
			self.object.put(name, value, true)
		})
		return err
	}
}

// Keys gets the keys for the given object.
//
// Equivalent to calling Object.keys on the object.
func (self Object) Keys() []string {
	var keys []string
	self.object.enumerate(false, func(name string) bool {
		keys = append(keys, name)
		return true
	})
	return keys
}

// KeysByParent gets the keys (and those of the parents) for the given object,
// in order of "closest" to "furthest".
func (self Object) KeysByParent() [][]string {
	var a [][]string

	for o := self.object; o != nil; o = o.prototype {
		var l []string

		o.enumerate(false, func(name string) bool {
			l = append(l, name)
			return true
		})

		a = append(a, l)
	}

	return a
}

// Class will return the class string of the object.
//
// The return value will (generally) be one of:
//
//		Object
//		Function
//		Array
//		String
//		Number
//		Boolean
//		Date
//		RegExp
//
func (self Object) Class() string {
	return self.object.class
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>volkov</groupId>
	<artifactId>ServletExample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ServletExample Maven Webapp</name>
	<url>https://github.com/ArtyomVolkov/ServletExample</url>

	<developers>
		<developer>
			<id>avolkov</id>
			<name>Artem Volkov</name>
			<email>artyom.volkow@gmail.com</email>
			<roles>
				<role>developer</role>
			</roles>
		</developer>
	</developers>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.1</version>
		</dependency>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.7.3</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.9.5</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.16</version>
				<configuration>
					<includes>
						<include>**/*TESTS.java</include>
					</includes>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.4.1</version>
				<configuration>
					<preparationGoals>clean verify</preparationGoals>
					<goals>package</goals>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<description> Web application is a servlet to manage the data from the database Mongodb</description>
	<inceptionYear>2013</inceptionYear>
</project>


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/activity_load_qna"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="zero.zd.zikyu.QnaLoadActivity">

    <TextView
        android:id="@+id/text_msg_choose"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".05"
        android:text="@string/msg_choose_file"/>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="10dp"
        android:layout_weight=".95"/>
</LinearLayout>


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */

package org.modeshape.web.jcr.rest.handler;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import org.modeshape.web.jcr.rest.RestHelper;
import org.modeshape.web.jcr.rest.model.RestWorkspaces;

/**
 * An extension of the {@link RepositoryHandler} which returns POJO-based rest model instances.
 *
 * @author Horia Chiorean (hchiorea@redhat.com)
 */
public final class RestRepositoryHandler extends AbstractHandler {

    /**
     * Returns the list of workspaces available to this user within the named repository.
     *
     * @param request the servlet request; may not be null
     * @param repositoryName the name of the repository; may not be null
     * @return the list of workspaces available to this user within the named repository, as a {@link RestWorkspaces} object
     *
     * @throws RepositoryException if there is any other error accessing the list of available workspaces for the repository
     */
    public RestWorkspaces getWorkspaces( HttpServletRequest request,
                                         String repositoryName ) throws RepositoryException {
        assert request != null;
        assert repositoryName != null;

        RestWorkspaces workspaces = new RestWorkspaces();
        Session session = getSession(request, repositoryName, null);
        for (String workspaceName : session.getWorkspace().getAccessibleWorkspaceNames()) {
            String repositoryUrl = RestHelper.urlFrom(request);
            workspaces.addWorkspace(workspaceName, repositoryUrl);
        }
        return workspaces;
    }
}


text:
using System;
using System.Net;

namespace EnjoyDialogs.SCIM.Infrastructure
{
    public class ScimException : ApplicationException
    {

        public ScimException (HttpStatusCode statusCode, string message)
            : base(message)
        {
            this.StatusCode = statusCode;
        }

        public HttpStatusCode StatusCode { get; set; }
    }
}


text:
<component name="libraryTable">
  <library name="support-vector-drawable-25.1.1">
    <CLASSES>
      <root url="jar://D:/ProgramFile/AndroidPhonModel/.android/build-cache/cc635197ce3cf02ddaacb2b895d700bcacebf6ce/output/jars/classes.jar!/" />
      <root url="file://D:/ProgramFile/AndroidPhonModel/.android/build-cache/cc635197ce3cf02ddaacb2b895d700bcacebf6ce/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://F:/SDKTools/sdk/extras/android/m2repository/com/android/support/support-vector-drawable/25.1.1/support-vector-drawable-25.1.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
- Fixes "Modified names for (class) is empty" error. [zinc#292][zinc292] / [zinc#484][zinc484] by [@jvican][@jvican]
- Fixes tab completion in `console` while running in batch mode as `sbt console`. [#3841][3841]/[#3876][3876] by [@eed3si9n][@eed3si9n]
- Fixes file timestamp retrieval of missing files on Windows. [#3871][3871] / [io#120][io120] by [@cunei][@cunei]
- Aligns the errors thrown by file timestamp implementations. Fixes [#3894][3894] / [io#121][io121] by [@j-keck][@j-keck]
- Adds file timestamps native support for FreeBSD. [#3894][3894] / [io#124][io124] by [@cunei][@cunei]
- Fixes JDK 10 version string parsing. [launcher#209][launcher209] by [@2m][@2m]

### Improvements

- Deprecates `Extracted#append` in favour of `appendWithSession` or `appendWithoutSession`.  [#3865][3865] by [@dwijnand][@dwijnand]
- Adds a new global `Boolean` setting called `autoStartServer`. See below.
- Upgrades Scala versions used for sbt cross building `^^`. [#3923][3923] by [@dwijnand][@dwijnand]
- Many documentation maintenance changes by [@xuwei-k][@xuwei-k]

### autoStartServer setting

sbt 1.1.1 adds a new global `Boolean` setting called `autoStartServer`, which is set to `true` by default.
When set to `true`, sbt shell will automatically start sbt server. Otherwise, it will not start the server until `startServer` command is issued. This could be used to opt out of server for security reasons.

[#3922][3922] by [@swaldman][@swaldman]

  [@eed3si9n]: https://github.com/eed3si9n
  [@dwijnand]: https://github.com/dwijnand
  [@cunei]: https://github.com/cunei
  [@jvican]: https://github.com/jvican
  [@Duhemm]: https://github.com/Duhemm
  [@j-keck]: https://github.com/j-keck
  [@swaldman]: https://github.com/swaldman
  [@xuwei-k]: https://github.com/xuwei-k
  [@2m]: https://github.com/2m
  [3871]: https://github.com/sbt/sbt/issues/3871
  [io120]: https://github.com/sbt/io/pull/120
  [3894]: https://github.com/sbt/sbt/issues/3894
  [io121]: https://github.com/sbt/io/pull/121
  [io124]: https://github.com/sbt/io/pull/124
  [zinc292]: https://github.com/sbt/zinc/issues/292
  [zinc484]: https://github.com/sbt/zinc/pull/484
  [3865]: https://github.com/sbt/sbt/pull/3865
  [3841]: https://github.com/sbt/sbt/issues/3841
  [3876]: https://github.com/sbt/sbt/pull/3876
  [3923]: https://github.com/sbt/sbt/pull/3923
  [3922]: https://github.com/sbt/sbt/pull/3922
  [launcher209]: https://github.com/sbt/sbt-launcher-package/pull/209


text:
from tempest.lib.services.compute import hosts_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services import base

class TestHostsClient(base.BaseServiceTest):
    FAKE_HOST_DATA = {
        "host": {
            "resource": {
                "cpu": 1,
                "disk_gb": 1028,
                "host": "c1a7de0ac9d94e4baceae031d05caae3",
                "memory_mb": 8192,
                "project": "(total)"
                }
        },
        "hosts": {
            "host_name": "c1a7de0ac9d94e4baceae031d05caae3",
            "service": "conductor",
            "zone": "internal"
        },
        "enable_hosts": {
            "host": "65c5d5b7e3bd44308e67fc50f362aee6",
            "maintenance_mode": "off_maintenance",
            "status": "enabled"
        }
        }

    FAKE_CONTROL_DATA = {
        "shutdown": {
            "host": "c1a7de0ac9d94e4baceae031d05caae3",
            "power_action": "shutdown"
        },
        "startup": {
            "host": "c1a7de0ac9d94e4baceae031d05caae3",
            "power_action": "startup"
        },
        "reboot": {
            "host": "c1a7de0ac9d94e4baceae031d05caae3",
            "power_action": "reboot"
        }}

    HOST_DATA = {'host': [FAKE_HOST_DATA['host']]}
    HOSTS_DATA = {'hosts': [FAKE_HOST_DATA['hosts']]}
    ENABLE_HOST_DATA = FAKE_HOST_DATA['enable_hosts']
    HOST_ID = "c1a7de0ac9d94e4baceae031d05caae3"
    TEST_HOST_DATA = {
        "status": "enable",
        "maintenance_mode": "disable"
    }

    def setUp(self):
        super(TestHostsClient, self).setUp()
        fake_auth = fake_auth_provider.FakeAuthProvider()
        self.client = hosts_client.HostsClient(fake_auth, 'compute',
                                               'regionOne')
        self.params = {'hostname': self.HOST_ID}
        self.func2mock = {
            'get': 'tempest.lib.common.rest_client.RestClient.get',
            'put': 'tempest.lib.common.rest_client.RestClient.put'}

    def _test_host_data(self, test_type='list', bytes_body=False):
        expected_resp = self.HOST_DATA
        if test_type != 'list':
            function_call = self.client.show_host
        else:
            expected_resp = self.HOSTS_DATA
            function_call = self.client.list_hosts
            self.params = {'host_name': self.HOST_ID}

        self.check_service_client_function(
            function_call, self.func2mock['get'],
            expected_resp, bytes_body,
            200, **self.params)

    def _test_update_hosts(self, bytes_body=False):
        expected_resp = self.ENABLE_HOST_DATA
        self.check_service_client_function(
            self.client.update_host, self.func2mock['put'],
            expected_resp, bytes_body,
            200, **self.params)

    def _test_control_host(self, control_op='reboot', bytes_body=False):
        if control_op == 'start':
            expected_resp = self.FAKE_CONTROL_DATA['startup']
            function_call = self.client.startup_host
        elif control_op == 'stop':
            expected_resp = self.FAKE_CONTROL_DATA['shutdown']
            function_call = self.client.shutdown_host
        else:
            expected_resp = self.FAKE_CONTROL_DATA['reboot']
            function_call = self.client.reboot_host

        self.check_service_client_function(
            function_call, self.func2mock['get'],
            expected_resp, bytes_body,
            200, **self.params)

    def test_show_host_with_str_body(self):
        self._test_host_data('show')

    def test_show_host_with_bytes_body(self):
        self._test_host_data('show', True)

    def test_list_host_with_str_body(self):
        self._test_host_data()

    def test_list_host_with_bytes_body(self):
        self._test_host_data(bytes_body=True)

    def test_start_host_with_str_body(self):
        self._test_control_host('start')

    def test_start_host_with_bytes_body(self):
        self._test_control_host('start', True)

    def test_stop_host_with_str_body(self):
        self._test_control_host('stop')

    def test_stop_host_with_bytes_body(self):
        self._test_control_host('stop', True)

    def test_reboot_host_with_str_body(self):
        self._test_control_host('reboot')

    def test_reboot_host_with_bytes_body(self):
        self._test_control_host('reboot', True)

    def test_update_host_with_str_body(self):
        self._test_update_hosts()

    def test_update_host_with_bytes_body(self):
        self._test_update_hosts(True)


text:
// Fig. 9.9: circletest.cpp
// Testing class Circle.
#include <iostream>

using std::cout;
using std::endl;
using std::fixed;

#include <iomanip>

using std::setprecision;

#include "circle.h"  // Circle class definition

int main()
{
   Circle circle( 37, 43, 2.5 );  // instantiate Circle object

   // display point coordinates
   cout << "X coordinate is " << circle.getX()
        << "\nY coordinate is " << circle.getY()
        << "\nRadius is " << circle.getRadius();

   circle.setX( 2 );          // set new x-coordinate
   circle.setY( 2 );          // set new y-coordinate
   circle.setRadius( 4.25 );  // set new radius

   // display new point value
   cout << "\n\nThe new location and radius of circle are\n";
   circle.print();

   // display floating-point values with 2 digits of precision
   cout << fixed << setprecision( 2 );

   // display Circle's diameter
   cout << "\nDiameter is " << circle.getDiameter();

   // display Circle's circumference
   cout << "\nCircumference is " << circle.getCircumference();

   // display Circle's area
   cout << "\nArea is " << circle.getArea();

   cout << endl;

   return 0;  // indicates successful termination

} // end main


text:
require 'cutorch'
require 'nn'

local TemporalKMaxPooling, parent =
    torch.class('nn.TemporalKMaxPooling', 'nn.Module')

function TemporalKMaxPooling:__init(k, k_dynamic)
    parent.__init(self)

    self.k = k
    if k_dynamic then
        assert(k_dynamic <= 1 and k_dynamic >=0,
        'k_dynamic must be between 0 and 1')
    end
    self.k_dynamic = k_dynamic or -1

    -- k_dynamic is an optional scalar parameter between 0 and 1
    -- that makes k a fraction of the input sequence size.

    -- To follow Kalchbrenner et al's architecture on Dynamic k-Max Pooling:
    -- Use (k = k_top, kDynamic = (L - l)/L), with
    -- L : total number of conv layers,
    -- l : current convolutional layer to which the pooling is applied,
    -- k_top : fixed pooling parameter for the topmost convolutional layer.

    self.output = torch.CudaTensor()
    self.gradInput = torch.CudaTensor()
    self.indices = torch.CudaTensor()
end

function TemporalKMaxPooling:updateOutput(input)
    input = input:contiguous()
    input.nn.TemporalKMaxPooling_updateOutput(self, input)
    return self.output
end

function TemporalKMaxPooling:updateGradInput(input, gradOutput)
    input = input:contiguous()
    gradOutput = gradOutput:contiguous()

    input.nn.TemporalKMaxPooling_updateGradInput(self, input, gradOutput)
    return self.gradInput
end


text:
using async_task_t = std::function<void()>;
using task_owner = void*;
#define null_owner nullptr

//·ÇḬ̈߳²È«

class task_queue
{
public:
	task_queue(bool persistence, bool nolock);
	virtual ~task_queue();

	void			add(const async_task_t& task, const task_owner& owner = null_owner);
	void			del(const task_owner& owner = null_owner);
	void			execute();
	bool			is_empty();
	void			clear();

private:
	struct task_item
	{
		task_item(const async_task_t& task_ = nullptr, const task_owner& owner_ = null_owner)
		{
			task = task_;
			owner = owner_;
		}
		async_task_t	task;
		task_owner		owner;
	};
	bool								_persistence;//ÊÇ·ñ³Ö¾Ã
	bool								_nolock;

	uint64_t							_seq;
	std::map<uint64_t, task_item>		_task_list;
	std::map<task_owner, std::map<uint64_t, uint64_t>>	_owner_list;
	std::recursive_mutex				_mutex;
};


text:
layout:     gallerypost
title:      "Milfs and Maidens"
date:       2009-01-14 14:36:55
categories: writing
permalink:  ash/:title
author:     Martin
meta:
tags:       []
images:
    klausi-tattoo/bild006.jpg:           600x400
---

{% include gallery.html %}


text:
package storage

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"

	"k8s.io/kubernetes/pkg/client/unversioned/cache"
	"k8s.io/kubernetes/pkg/conversion"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/pkg/watch"

	"github.com/golang/glog"
)

// CacherConfig contains the configuration for a given Cache.
type CacherConfig struct {
	// Maximum size of the history cached in memory.
	CacheCapacity int

	// An underlying storage.Interface.
	Storage Interface

	// An underlying storage.Versioner.
	Versioner Versioner

	// The Cache will be caching objects of a given Type and assumes that they
	// are all stored under ResourcePrefix directory in the underlying database.
	Type           interface{}
	ResourcePrefix string

	// KeyFunc is used to get a key in the underyling storage for a given object.
	KeyFunc func(runtime.Object) (string, error)

	// NewList is a function that creates new empty object storing a list of
	// objects of type Type.
	NewListFunc func() runtime.Object

	// Cacher will be stopped when the StopChannel will be closed.
	StopChannel <-chan struct{}
}

// Cacher is responsible for serving WATCH and LIST requests for a given
// resource from its internal cache and updating its cache in the background
// based on the underlying storage contents.
type Cacher struct {
	sync.RWMutex

	// Whether Cacher is initialized.
	initialized sync.WaitGroup
	initOnce    sync.Once

	// "sliding window" of recent changes of objects and the current state.
	watchCache *cache.WatchCache
	reflector  *cache.Reflector

	// Registered watchers.
	watcherIdx int
	watchers   map[int]*cacheWatcher

	// Versioner is used to handle resource versions.
	versioner Versioner

	// keyFunc is used to get a key in the underyling storage for a given object.
	keyFunc func(runtime.Object) (string, error)
}

// Create a new Cacher responsible from service WATCH and LIST requests from its
// internal cache and updating its cache in the background based on the given
// configuration.
func NewCacher(config CacherConfig) *Cacher {
	watchCache := cache.NewWatchCache(config.CacheCapacity)
	listerWatcher := newCacherListerWatcher(config.Storage, config.ResourcePrefix, config.NewListFunc)

	cacher := &Cacher{
		initialized: sync.WaitGroup{},
		watchCache:  watchCache,
		reflector:   cache.NewReflector(listerWatcher, config.Type, watchCache, 0),
		watcherIdx:  0,
		watchers:    make(map[int]*cacheWatcher),
		versioner:   config.Versioner,
		keyFunc:     config.KeyFunc,
	}
	cacher.initialized.Add(1)
	// See startCaching method for why explanation on it.
	watchCache.SetOnReplace(func() {
		cacher.initOnce.Do(func() { cacher.initialized.Done() })
		cacher.Unlock()
	})
	watchCache.SetOnEvent(cacher.processEvent)

	stopCh := config.StopChannel
	go util.Until(func() { cacher.startCaching(stopCh) }, 0, stopCh)
	cacher.initialized.Wait()
	return cacher
}

func (c *Cacher) startCaching(stopChannel <-chan struct{}) {
	c.Lock()
	c.terminateAllWatchers()
	// We explicitly do NOT Unlock() in this method.
	// This is because we do not want to allow any WATCH/LIST methods before
	// the cache is initialized. Once the underlying cache is propagated,
	// onReplace handler will be called, which will do the Unlock() as
	// configured in NewCacher().
	// Note: the same bahavior is also triggered every time we fall out of
	// backen storage (e.g. etcd's) watch event window.
	// Note that since onReplace may be not called due to errors, we explicitly
	// need to retry it on errors under lock.
	for {
		err := c.reflector.ListAndWatch(stopChannel)
		if err == nil {
			break
		}
	}
}

// Implements Watch (signature from storage.Interface).
func (c *Cacher) Watch(key string, resourceVersion uint64, filter FilterFunc) (watch.Interface, error) {
	// We explicitly use thread unsafe version and do locking ourself to ensure that
	// no new events will be processed in the meantime. The watchCache will be unlocked
	// on return from this function.
	// Note that we cannot do it under Cacher lock, to avoid a deadlock, since the
	// underlying watchCache is calling processEvent under its lock.
	c.watchCache.RLock()
	defer c.watchCache.RUnlock()
	initEvents, err := c.watchCache.GetAllEventsSinceThreadUnsafe(resourceVersion)
	if err != nil {
		return nil, err
	}

	c.Lock()
	defer c.Unlock()
	watcher := newCacheWatcher(initEvents, filterFunction(key, c.keyFunc, filter), forgetWatcher(c, c.watcherIdx))
	c.watchers[c.watcherIdx] = watcher
	c.watcherIdx++
	return watcher, nil
}

// Implements WatchList (signature from storage.Interface).
func (c *Cacher) WatchList(key string, resourceVersion uint64, filter FilterFunc) (watch.Interface, error) {
	return c.Watch(key, resourceVersion, filter)
}

// Implements List (signature from storage.Interface).
func (c *Cacher) List(key string, listObj runtime.Object) error {
	listPtr, err := runtime.GetItemsPtr(listObj)
	if err != nil {
		return err
	}
	listVal, err := conversion.EnforcePtr(listPtr)
	if err != nil || listVal.Kind() != reflect.Slice {
		return fmt.Errorf("need a pointer to slice, got %v", listVal.Kind())
	}
	filter := filterFunction(key, c.keyFunc, Everything)

	objs, resourceVersion := c.watchCache.ListWithVersion()
	for _, obj := range objs {
		object, ok := obj.(runtime.Object)
		if !ok {
			return fmt.Errorf("non runtime.Object returned from storage: %v", obj)
		}
		if filter(object) {
			listVal.Set(reflect.Append(listVal, reflect.ValueOf(object).Elem()))
		}
	}
	if c.versioner != nil {
		if err := c.versioner.UpdateList(listObj, resourceVersion); err != nil {
			return err
		}
	}
	return nil
}

func (c *Cacher) processEvent(event cache.WatchCacheEvent) {
	c.Lock()
	defer c.Unlock()
	for _, watcher := range c.watchers {
		watcher.add(event)
	}
}

func (c *Cacher) terminateAllWatchers() {
	for key, watcher := range c.watchers {
		delete(c.watchers, key)
		watcher.stop()
	}
}

func forgetWatcher(c *Cacher, index int) func() {
	return func() {
		c.Lock()
		defer c.Unlock()
		// It's possible that the watcher is already not in the map (e.g. in case of
		// simulaneous Stop() and terminateAllWatchers(), but it doesn't break anything.
		delete(c.watchers, index)
	}
}

func filterFunction(key string, keyFunc func(runtime.Object) (string, error), filter FilterFunc) FilterFunc {
	return func(obj runtime.Object) bool {
		objKey, err := keyFunc(obj)
		if err != nil {
			glog.Errorf("Invalid object for filter: %v", obj)
			return false
		}
		if !strings.HasPrefix(objKey, key) {
			return false
		}
		return filter(obj)
	}
}

// Returns resource version to which the underlying cache is synced.
func (c *Cacher) LastSyncResourceVersion() (uint64, error) {
	c.RLock()
	defer c.RUnlock()

	resourceVersion := c.reflector.LastSyncResourceVersion()
	if resourceVersion == "" {
		return 0, nil
	}
	return strconv.ParseUint(resourceVersion, 10, 64)
}

// cacherListerWatcher opaques storage.Interface to expose cache.ListerWatcher.
type cacherListerWatcher struct {
	storage        Interface
	resourcePrefix string
	newListFunc    func() runtime.Object
}

func newCacherListerWatcher(storage Interface, resourcePrefix string, newListFunc func() runtime.Object) cache.ListerWatcher {
	return &cacherListerWatcher{
		storage:        storage,
		resourcePrefix: resourcePrefix,
		newListFunc:    newListFunc,
	}
}

// Implements cache.ListerWatcher interface.
func (lw *cacherListerWatcher) List() (runtime.Object, error) {
	list := lw.newListFunc()
	if err := lw.storage.List(lw.resourcePrefix, list); err != nil {
		return nil, err
	}
	return list, nil
}

// Implements cache.ListerWatcher interface.
func (lw *cacherListerWatcher) Watch(resourceVersion string) (watch.Interface, error) {
	version, err := ParseWatchResourceVersion(resourceVersion, lw.resourcePrefix)
	if err != nil {
		return nil, err
	}
	return lw.storage.WatchList(lw.resourcePrefix, version, Everything)
}

// cacherWatch implements watch.Interface
type cacheWatcher struct {
	sync.Mutex
	input   chan cache.WatchCacheEvent
	result  chan watch.Event
	filter  FilterFunc
	stopped bool
	forget  func()
}

func newCacheWatcher(initEvents []cache.WatchCacheEvent, filter FilterFunc, forget func()) *cacheWatcher {
	watcher := &cacheWatcher{
		input:   make(chan cache.WatchCacheEvent, 10),
		result:  make(chan watch.Event, 10),
		filter:  filter,
		stopped: false,
		forget:  forget,
	}
	go watcher.process(initEvents)
	return watcher
}

// Implements watch.Interface.
func (c *cacheWatcher) ResultChan() <-chan watch.Event {
	return c.result
}

// Implements watch.Interface.
func (c *cacheWatcher) Stop() {
	c.forget()
	c.stop()
}

func (c *cacheWatcher) stop() {
	c.Lock()
	defer c.Unlock()
	if !c.stopped {
		c.stopped = true
		close(c.input)
	}
}

func (c *cacheWatcher) add(event cache.WatchCacheEvent) {
	c.input <- event
}

func (c *cacheWatcher) sendWatchCacheEvent(event cache.WatchCacheEvent) {
	curObjPasses := event.Type != watch.Deleted && c.filter(event.Object)
	oldObjPasses := false
	if event.PrevObject != nil {
		oldObjPasses = c.filter(event.PrevObject)
	}
	switch {
	case curObjPasses && !oldObjPasses:
		c.result <- watch.Event{Type: watch.Added, Object: event.Object}
	case curObjPasses && oldObjPasses:
		c.result <- watch.Event{Type: watch.Modified, Object: event.Object}
	case !curObjPasses && oldObjPasses:
		c.result <- watch.Event{Type: watch.Deleted, Object: event.Object}
	}
}

func (c *cacheWatcher) process(initEvents []cache.WatchCacheEvent) {
	for _, event := range initEvents {
		c.sendWatchCacheEvent(event)
	}
	defer close(c.result)
	defer c.Stop()
	for {
		event, ok := <-c.input
		if !ok {
			return
		}
		c.sendWatchCacheEvent(event)
	}
}


text:
namespace FakeItEasy.Core
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    internal class EventHandlerArgumentProviderMap
    {
        private readonly ConcurrentDictionary<Delegate, IEventRaiserArgumentProvider> map
            = new ConcurrentDictionary<Delegate, IEventRaiserArgumentProvider>(new EventRaiserDelegateComparer());

        public void AddArgumentProvider(Delegate eventHandler, IEventRaiserArgumentProvider argumentProvider)
        {
            this.map[eventHandler] = argumentProvider;
        }

        public bool TryTakeArgumentProviderFor(Delegate eventHandler, [NotNullWhen(true)] out IEventRaiserArgumentProvider? argumentProvider)
        {
            return this.map.TryRemove(eventHandler, out argumentProvider);
        }

        public bool HasArgumentProvider(Delegate eventHandler) => this.map.ContainsKey(eventHandler);

        /// <summary>
        /// Allows a more lenient comparison of delegates, chiefly so <see cref="EventHandler"/>s and
        /// <see cref="EventHandler{TEventArgs}"/>s that refer to the same method on the same instance
        /// will compare as equal. It relies on the fact that every time an event is raised,
        /// <see cref="Raise"/> creates a new instance, and the delegate registered in the map
        /// targets that instance.
        /// </summary>
        private class EventRaiserDelegateComparer : IEqualityComparer<Delegate>
        {
            public bool Equals(Delegate? leftDelegate, Delegate? rightDelegate)
            {
                return ReferenceEquals(leftDelegate, rightDelegate) ||
                       (leftDelegate is not null &&
                        rightDelegate is not null &&
                        ReferenceEquals(leftDelegate.Target, rightDelegate.Target));
            }

            public int GetHashCode(Delegate theDelegate)
            {
                return theDelegate is null || theDelegate.Target is null
                    ? 17
                    : theDelegate.Target.GetHashCode();
            }
        }
    }
}


text:
android-fn-all
==============

Add New Functionalities at one place in an application


text:
__author__ = 'evgeny'

from features import logfbank
from collections import defaultdict
import scipy.io.wavfile as wav
import os
import numpy as np

sph2pipe = "/Users/evgeny/kaldi3/tools/sph2pipe_v2.5/sph2pipe"

window = 0.025
step = 0.01
nfilt = 40
fftsize = 512

left_context = 6
right_context = 2

def getAudio(path):
    os.system(sph2pipe + " -f wav " + path + " tmp.wav")
    (rate, sig) = wav.read("tmp.wav")
    os.remove("tmp.wav")
    return (rate, sig)

def extractLogFBank(rate, sig):
    feats = logfbank(sig, rate, window, step, nfilt, fftsize, 0, None, 0)
    return feats

keywords = ["she", "had"]

src = "/Users/evgeny/timit/TIMIT"
dst = "/Users/evgeny/data"

count = {"TEST": 10000, "TRAIN": 100000}

for type in ["TEST", "TRAIN"]:
    dstt = dst + "/" + type
    srct = src + "/" + type
    if not os.path.exists(dstt):
        os.mkdir(dstt)

    mx = count[type]
    item_id = 0

    used = set()

    wordCount = defaultdict(int)

    for root, dirs, filenames in os.walk(srct):
        for f in filenames:
            if f.endswith(".WRD"):
                id = f[:-4]
                rate, sig = getAudio(root + "/" + id + ".WAV")
                fbanks = extractLogFBank(rate, sig)
                segments = []
                file = open(root + "/" + f)
                for line in file:
                    [start, end, word] = line.split()
                    start = int(start)
                    end = int(end) + 1

                    firstFrame = int(1.0 * start / rate / step)
                    lastFrame = int(1.0 * end / rate / step)

                    class_id = keywords.index(word) if word in keywords else len(keywords)

                    segments.append([firstFrame, lastFrame, class_id])

                    #sig_seg = sig[start:end]
                    #print root, id, start, end
                    #fbanks = extractLogFBank(rate, sig_seg)
                    #class_id = keywords.index(word) if word in keywords else len(keywords)
                    wordCount[class_id] += 1
                    #item_id += 1

                np.save(dst + "/" + type + "/" + str(item_id), [fbanks, segments])
                item_id += 1
                file.close()

    print item_id
    for w in sorted(wordCount, key=wordCount.get, reverse=True):
        print w, wordCount[w]


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 324508 $ -->

<refentry xml:id="appenditerator.getinneriterator" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>AppendIterator::getInnerIterator</refname>
  <refpurpose>Gets the inner iterator</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>Iterator</type><methodname>AppendIterator::getInnerIterator</methodname>
   <void />
  </methodsynopsis>
  <para>
   This method returns the current inner iterator.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  &no.function.parameters;
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   The current inner iterator, or &null; if there is not one.
  </para>
 </refsect1>

 <refsect1 role="examples"><!-- {{{ -->
  &reftitle.examples;
  <para>
   <example xml:id="appenditerator.getinneriterator.examples.basic"><!-- {{{ -->
    <title><methodname>AppendIterator::getInnerIterator</methodname> example</title>
    <programlisting role="php">
<![CDATA[
<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new RegexIterator($array_a, '/^[ac]/');

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    $inner = $iterator->getInnerIterator();
    if ($inner instanceOf RegexIterator) {
        echo 'Filtered: ';
    } else {
        echo 'Original: ';
    }
    echo $current . PHP_EOL;
}
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
Original: aardwolf
Original: bear
Original: capybara
Filtered: aardwolf
Filtered: capybara
]]>
    </screen>
   </example><!-- }}} -->
  </para>
 </refsect1><!-- }}} -->

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><methodname>AppendIterator::getIteratorIndex</methodname></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package org.bouncycastle.operator;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

/**
 * The base interface for a provider of DigestCalculator implementations.
 */
public interface DigestCalculatorProvider
{
    DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier)
        throws OperatorCreationException;
}


text:
package nl.rostykerei.cci.ch01.q09;

/**
 * Question 1.9 - String Rotation.
 *
 * @author Rosty Kerei
 */
public interface StringRotation {

    /**
     * Checks if the String s2 is a rotation of s1.
     *
     * @param s1 base string
     * @param s2 rotation string
     * @return true if s2 is a rotation of s1
     */
    boolean isStringRotation(String s1, String s2);
}


text: export { default } from "./BannerPresenter";


text:
<?php

namespace GrahamCampbell\Exceptions\Displayers;

use Exception;
use GrahamCampbell\Exceptions\ExceptionInfo;
use Symfony\Component\HttpFoundation\Response;

/**
 * This is the html displayer class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class HtmlDisplayer implements DisplayerInterface
{
    /**
     * The exception info instance.
     *
     * @var \GrahamCampbell\Exceptions\ExceptionInfo
     */
    protected $info;

    /**
     * The asset generator function.
     *
     * @var callable
     */
    protected $assets;

    /**
     * The html template path.
     *
     * @var string
     */
    protected $path;

    /**
     * Create a new html displayer instance.
     *
     * @param \GrahamCampbell\Exceptions\ExceptionInfo $info
     * @param callable                                 $assets
     * @param string                                   $path
     *
     * @return void
     */
    public function __construct(ExceptionInfo $info, callable $assets, $path)
    {
        $this->info = $info;
        $this->assets = $assets;
        $this->path = $path;
    }

    /**
     * Get the error response associated with the given exception.
     *
     * @param \Exception $exception
     * @param string     $id
     * @param int        $code
     * @param string[]   $headers
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function display(Exception $exception, $id, $code, array $headers)
    {
        $info = $this->info->generate($exception, $id, $code);

        return new Response($this->render($info), $code, array_merge($headers, ['Content-Type' => $this->contentType()]));
    }

    /**
     * Render the page with given info.
     *
     * @param array $info
     *
     * @return string
     */
    protected function render(array $info)
    {
        $content = file_get_contents($this->path);

        $generator = $this->assets;
        $info['home_url'] = $generator('/');
        $info['favicon_url'] = $generator('favicon.ico');

        foreach ($info as $key => $val) {
            $content = str_replace("{{ $$key }}", $val, $content);
        }

        return $content;
    }

    /**
     * Get the supported content type.
     *
     * @return string
     */
    public function contentType()
    {
        return 'text/html';
    }

    /**
     * Can we display the exception?
     *
     * @param \Exception $original
     * @param \Exception $transformed
     * @param int        $code
     *
     * @return bool
     */
    public function canDisplay(Exception $original, Exception $transformed, $code)
    {
        return true;
    }

    /**
     * Do we provide verbose information about the exception?
     *
     * @return bool
     */
    public function isVerbose()
    {
        return false;
    }
}


text:
"""Base Class for the Delta and Chunk minimizers."""

import unittest

class BaseMinimizerTester(unittest.TestCase):
  """Base class for chunk and delta minimizer tests."""

  def setUp(self):
    raise NotImplementedError

  def _mock_test_function(self, data_file):
    """Mock test function to reduce time minimizer takes and simplify tests."""
    data = open(data_file, 'rb').read()
    if b'error' in data:
      return False
    return True

  def test_minimizer_still_contains_error(self):
    """Tests a simple minimization. Should remove the first and last lines."""
    testcase = b'x = 2 \n error \n return x'
    minimized = self.line_minimizer.minimize(testcase)
    self.assertEqual(minimized, b' error ')

  def test_minimizer_accepts_empty_data(self):
    """Tests that the minimizer does not break on empty string."""
    testcase = b''
    minimized = self.line_minimizer.minimize(testcase)
    self.assertEqual(minimized, b'')

  def test_minimizer_does_not_minimize_non_errored_code(self):
    """"Test that the minimizer does not break when there is nothing to min."""
    testcase = b'This \n Code \n Has \n No \n Error'
    minimized = self.line_minimizer.minimize(testcase)
    self.assertEqual(minimized, testcase)


text:
require 'rspec/core'
require 'rspec-api/matchers/attributes/have_attributes'
require 'rspec-api/matchers/collection/be_a_collection'
require 'rspec-api/matchers/content_type/have_content_type'
require 'rspec-api/matchers/filter/be_filtered'
require 'rspec-api/matchers/json/be_valid_json'
require 'rspec-api/matchers/jsonp/be_wrapped_in_callback'
require 'rspec-api/matchers/page_links/have_page_links'
require 'rspec-api/matchers/response/be_a_valid_response'
require 'rspec-api/matchers/sort/be_sorted'
require 'rspec-api/matchers/status/have_status'

module RSpecApi
  # Provides RSpec Matchers for RESTful web APIs.
  #
  # To have these matchers available inside of an RSpec `describe` block,
  # tag that block with the `:rspec_api` metadata, or explicitly include the
  # RSpecApi::Matchers module inside the example group
  #
  # @example Tag a `describe` block as `:rspec_api`:
  #   describe "Artists", rspec_api: true do
  #      ... # here you can write `expect(response).to have_status :ok`, etc.
  #   end
  #
  # @example Explicitly include the RSpecApi::Matchers module
  #   describe "Artists" do
  #      include RSpecApi::Matchers
  #      ... # here you can write `expect(response).to have_status :ok`, etc.
  #   end
  module Matchers
    include Attributes
    include Collection
    include ContentType
    include Filter
    include Json
    include Jsonp
    include PageLinks
    include Response
    include Sort
    include Status
  end
end

RSpec.configuration.include RSpecApi::Matchers, rspec_api: true


text:
<?php

/**
 * @file
 * Contains \Drupal\views\Tests\Plugin\DisplayPageTest.
 */

namespace Drupal\views\Tests\Plugin;

use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\views\EventSubscriber\RouteSubscriber;
use Drupal\views\Tests\ViewUnitTestBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\RouteCollection;

/**
 * Tests the page display plugin.
 *
 * @see Drupal\views\Plugin\display\Page
 */
class DisplayPageTest extends ViewUnitTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array('test_page_display', 'test_page_display_route');

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('system', 'user');

  /**
   * The router dumper to get all routes.
   *
   * @var \Drupal\Core\Routing\MatcherDumper
   */
  protected $routerDumper;

  public static function getInfo() {
    return array(
      'name' => 'Display: Page plugin',
      'description' => 'Tests the page display plugin.',
      'group' => 'Views Plugins',
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Setup the needed tables in order to make the drupal router working.
    $this->installSchema('system', 'router');
    $this->installSchema('system', 'url_alias');
    $this->installSchema('system', 'menu_router');
  }

  /**
   * Checks the behavior of the page for access denied/not found behaviours.
   */
  public function testPageResponses() {
    // @todo Importing a route should fire a container rebuild.
    $this->container->get('router.builder')->rebuild();

    $subrequest = Request::create('/test_page_display_403', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEqual($response->getStatusCode(), 403);

    $subrequest = Request::create('/test_page_display_404', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEqual($response->getStatusCode(), 404);

    $subrequest = Request::create('/test_page_display_200', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEqual($response->getStatusCode(), 200);

    // Test accessing a disabled page for a view.
    $view = views_get_view('test_page_display');
    // Disable the view, rebuild menu, and request the page again.
    $view->storage->disable()->save();
    $subrequest = Request::create('/test_page_display_200', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEqual($response->getStatusCode(), 404);
  }

  /**
   * Checks that the router items are properly registered
   */
  public function testPageRouterItems() {
    $subscriber = new RouteSubscriber();
    $collection = new RouteCollection();
    $subscriber->dynamicRoutes(new RouteBuildEvent($collection, 'dynamic_routes'));

    // Check the controller defaults.
    foreach ($collection as $id => $route) {
      if (strpos($id, 'test_page_display_route') === 0) {
        $this->assertEqual($route->getDefault('_controller'), 'Drupal\views\Routing\ViewPageController::handle');
        $this->assertEqual($route->getDefault('view_id'), 'test_page_display_route');
        $this->assertEqual($route->getDefault('display_id'), str_replace('test_page_display_route.', '', $id));
      }
    }

    // Check the generated patterns and default values.
    $route = $collection->get('view.test_page_display_route.page_1');
    $this->assertEqual($route->getPath(), '/test_route_without_arguments');

    $route = $collection->get('view.test_page_display_route.page_2');
    $this->assertEqual($route->getPath(), '/test_route_with_argument/{arg_id}');
    $this->assertTrue($route->hasDefault('arg_id'), 'A default value is set for the optional argument id.');

    $route = $collection->get('view.test_page_display_route.page_3');
    $this->assertEqual($route->getPath(), '/test_route_with_argument/{arg_id}/suffix');
    $this->assertFalse($route->hasDefault('arg_id'), 'No default value is set for the required argument id.');

    $route = $collection->get('view.test_page_display_route.page_4');
    $this->assertEqual($route->getPath(), '/test_route_with_argument/{arg_id}/suffix/{arg_id_2}');
    $this->assertFalse($route->hasDefault('arg_id'), 'No default value is set for the required argument id.');
    $this->assertTrue($route->hasDefault('arg_id_2'), 'A default value is set for the optional argument id_2.');

    $route = $collection->get('view.test_page_display_route.page_5');
    $this->assertEqual($route->getPath(), '/test_route_with_argument/{arg_id}/{arg_id_2}');
    $this->assertTrue($route->hasDefault('arg_id'), 'A default value is set for the optional argument id.');
    $this->assertTrue($route->hasDefault('arg_id_2'), 'A default value is set for the optional argument id_2.');

    $route = $collection->get('view.test_page_display_route.page_6');
    $this->assertEqual($route->getPath(), '/test_route_with_argument/{arg_id}/{arg_id_2}');
    $this->assertFalse($route->hasDefault('arg_id'), 'No default value is set for the required argument id.');
    $this->assertFalse($route->hasDefault('arg_id_2'), 'No default value is set for the required argument id_2.');
  }

}


text:
[Back to overview](./README.md)

# Writing PHPUnit tests (TODO)


text:
class ChangeNameOfDirectorMovies < ActiveRecord::Migration
  def change
    rename_table :director_movies, :movie_directors
  end
end


text:
layout: doc
title: "TabPage.onClosed"
position: 101
---

Устанавливает [обработчик события](../../../../Core/Script/) о том, что страница была закрыта.

# Description

Вызов метода [`close()`](../TabPage.close/) предпринимает попытку закрытия страницы панели. Закрытие
страницы означает, что она будет удалена из панели. Метод [`close()`](../TabPage.close/) предпринимает
попытку закрытия страницы, если метод [`getCanClose()`](../TabPage.getCanClose/) вернул `true`. Если
при этом нет ни одного обработчика, подписанного на событие [`onClosing`](../TabPage.onClosing/), либо
если все обработчики этого события вернули значение, отличное от `false`, страница будет закрыта. Иначе
вызов метода [`close()`](../TabPage.close/) ни к чему не приведет. Наконец, если все попытки закончились
успехом и страница была закрыта, будет вызвано событие [`onClosed`](../TabPage.onClosed/), в обработчике
которого можно обработать факт закрытия страницы.

# Syntax

```js
tabPage.onClosed(callback)
```

## Parameters

|Name|Type|Description|
|----|----|-----------|
|callback|[`Script`](../../../../Core/Script/)|Обработчик события о том, что страница была закрыта|

## Returns

Метод ничего не возвращает

# Examples

```js
tabPage.onClosed(
  function(context, args) { alert('Page is closed!'); }
);
```

# See Also

* [`close()`](../TabPage.close/)
* [`getCanClose()`](../TabPage.getCanClose/)
* [`setCanClose()`](../TabPage.setCanClose/)
* [`onClosing`](../TabPage.onClosing/)


text:
ether-contract
==============

Smart Contract Editor and Simulator for Ethereum: http://ether.fund/tool/contract

![ScreenShot](http://s3.amazonaws.com/m.saltado.com/sites/ether/tool/contract/7.png)


text:
<!doctype html>

    <title>Code coverage report for ol/interaction/snapinteraction.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / ol/interaction/ snapinteraction.js

        56.16%
        Statements
        123/219

        31.03%
        Branches
        18/58

        33.33%
        Functions
        8/24

        56.16%
        Lines
        123/219

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620	1×
1×

1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×

1×

2×

2×

2×

2×

2×

2×

2×

2×

2×

2×

2×

2×

2×

2×

1×

1×
1×
1×
1×
1×
1×
1×

1×

1×
1×

1×

1×
1×

1×

1×
1×
1×
1×

1×
1×

1×

1×

1×

1×

1×

1×
1×
1×
1×

1×

1×

1×
1×
1×

1×

1×

1×

1×

1×

1×

1×
1×
1×
1×
1×
1×
1×
1×
1×
1×

1×
1×

1×
1×
1×
1×
1×
1×
1×
1×
1×

1×
1×

1×

1×

1×

1×

1×

1×

1×

1×
1×
1×

1×

1×

1×

1×

1×
1×
1×
1×
1×

1×

1×

1×

goog.provide('ol.interaction.Snap');
goog.provide('ol.interaction.SnapProperty');

goog.require('goog.asserts');
goog.require('ol');
goog.require('ol.Collection');
goog.require('ol.CollectionEvent');
goog.require('ol.CollectionEventType');
goog.require('ol.Extent');
goog.require('ol.Feature');
goog.require('ol.Object');
goog.require('ol.Observable');
goog.require('ol.coordinate');
goog.require('ol.events');
goog.require('ol.events.EventType');
goog.require('ol.extent');
goog.require('ol.geom.Geometry');
goog.require('ol.interaction.Pointer');
goog.require('ol.object');
goog.require('ol.source.Vector');
goog.require('ol.source.VectorEvent');
goog.require('ol.source.VectorEventType');
goog.require('ol.structs.RBush');

/**
 * @classdesc
 * Handles snapping of vector features while modifying or drawing them.  The
 * features can come from a {@link ol.source.Vector} or {@link ol.Collection}
 * Any interaction object that allows the user to interact
 * with the features using the mouse can benefit from the snapping, as long
 * as it is added before.
 *
 * The snap interaction modifies map browser event `coordinate` and `pixel`
 * properties to force the snap to occur to any interaction that them.
 *
 * Example:
 *
 *     var snap = new ol.interaction.Snap({
 *       source: source
 *     });
 *
 * @constructor
 * @extends {ol.interaction.Pointer}
 * @param {olx.interaction.SnapOptions=} opt_options Options.
 * @api
 */
ol.interaction.Snap = function(opt_options) {

  goog.base(this, {
    handleEvent: ol.interaction.Snap.handleEvent_,
    handleDownEvent: goog.functions.TRUE,
    handleUpEvent: ol.interaction.Snap.handleUpEvent_
  });

  var options = opt_options ? opt_options : {};

  /**
   * @type {ol.source.Vector}
   * @private
   */
  this.source_ = options.source ? options.source : null;

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.features_ = options.features ? options.features : null;

  /**
   * @type {Array.<ol.events.Key>}
   * @private
   */
  this.featuresListenerKeys_ = [];

  /**
   * @type {Object.<number, ol.events.Key>}
   * @private
   */
  this.geometryChangeListenerKeys_ = {};

  /**
   * @type {Object.<number, ol.events.Key>}
   * @private
   */
  this.geometryModifyListenerKeys_ = {};

  /**
   * Extents are preserved so indexed segment can be quickly removed
   * when its feature geometry changes
   * @type {Object.<number, ol.Extent>}
   * @private
   */
  this.indexedFeaturesExtents_ = {};

  /**
   * If a feature geometry changes while a pointer drag|move event occurs, the
   * feature doesn't get updated right away.  It will be at the next 'pointerup'
   * event fired.
   * @type {Object.<number, ol.Feature>}
   * @private
   */
  this.pendingFeatures_ = {};

  /**
   * Used for distance sorting in sortByDistance_
   * @type {ol.Coordinate}
   * @private
   */
  this.pixelCoordinate_ = null;

  /**
   * @type {number}
   * @private
   */
  this.pixelTolerance_ = options.pixelTolerance !== undefined ?
      options.pixelTolerance : 10;

  /**
   * @type {function(ol.interaction.Snap.SegmentDataType, ol.interaction.Snap.SegmentDataType): number}
   * @private
   */
  this.sortByDistance_ = ol.interaction.Snap.sortByDistance.bind(this);

  /**
  * Segment RTree for each layer
  * @type {ol.structs.RBush.<ol.interaction.Snap.SegmentDataType>}
  * @private
  */
  this.rBush_ = new ol.structs.RBush();

  /**
  * @const
  * @private
  * @type {Object.<string, function(ol.Feature, ol.geom.Geometry)>}
  */
  this.SEGMENT_WRITERS_ = {
    'Point': this.writePointGeometry_,
    'LineString': this.writeLineStringGeometry_,
    'LinearRing': this.writeLineStringGeometry_,
    'Polygon': this.writePolygonGeometry_,
    'MultiPoint': this.writeMultiPointGeometry_,
    'MultiLineString': this.writeMultiLineStringGeometry_,
    'MultiPolygon': this.writeMultiPolygonGeometry_,
    'GeometryCollection': this.writeGeometryCollectionGeometry_
  };
};
goog.inherits(ol.interaction.Snap, ol.interaction.Pointer);

/**
 * Add a feature to the collection of features that we may snap to.
 * @param {ol.Feature} feature Feature.
 * @param {boolean=} opt_listen Whether to listen to the geometry change or not
 *     Defaults to `true`.
 * @api
 */
ol.interaction.Snap.prototype.addFeature = function(feature, opt_listen) {
  var listen = opt_listen !== undefined ? opt_listen : true;
  var geometry = feature.getGeometry();
  var segmentWriter = this.SEGMENT_WRITERS_[geometry.getType()];
  Eif (segmentWriter) {
    var feature_uid = goog.getUid(feature);
    this.indexedFeaturesExtents_[feature_uid] = geometry.getExtent(
        ol.extent.createEmpty());
    segmentWriter.call(this, feature, geometry);

    Eif (listen) {
      this.geometryModifyListenerKeys_[feature_uid] = ol.events.listen(
          geometry,
          ol.events.EventType.CHANGE,
          this.handleGeometryModify_.bind(this, feature),
          this);
      this.geometryChangeListenerKeys_[feature_uid] = ol.events.listen(
          feature,
          ol.Object.getChangeEventType(feature.getGeometryName()),
          this.handleGeometryChange_, this);
    }
  }
};

/**
 * @param {ol.Feature} feature Feature.
 * @private
 */
ol.interaction.Snap.prototype.forEachFeatureAdd_ = function(feature) {
  this.addFeature(feature);
};

/**
 * @param {ol.Feature} feature Feature.
 * @private
 */
ol.interaction.Snap.prototype.forEachFeatureRemove_ = function(feature) {
  this.removeFeature(feature);
};

/**
 * @return {ol.Collection.<ol.Feature>|Array.<ol.Feature>} Features.
 * @private
 */
ol.interaction.Snap.prototype.getFeatures_ = function() {
  var features;
  Eif (this.features_) {
    features = this.features_;
  } else if (this.source_) {
    features = this.source_.getFeatures();
  }
  goog.asserts.assert(features !== undefined, 'features should be defined');
  return features;
};

/**
 * @param {ol.source.VectorEvent|ol.CollectionEvent} evt Event.
 * @private
 */
ol.interaction.Snap.prototype.handleFeatureAdd_ = function(evt) {
  var feature;
  if (evt instanceof ol.source.VectorEvent) {
    feature = evt.feature;
  } else if (evt instanceof ol.CollectionEvent) {
    feature = evt.element;
  }
  goog.asserts.assertInstanceof(feature, ol.Feature,
      'feature should be an ol.Feature');
  this.addFeature(feature);
};

/**
 * @param {ol.source.VectorEvent|ol.CollectionEvent} evt Event.
 * @private
 */
ol.interaction.Snap.prototype.handleFeatureRemove_ = function(evt) {
  var feature;
  if (evt instanceof ol.source.VectorEvent) {
    feature = evt.feature;
  } else if (evt instanceof ol.CollectionEvent) {
    feature = evt.element;
  }
  goog.asserts.assertInstanceof(feature, ol.Feature,
      'feature should be an ol.Feature');
  this.removeFeature(feature);
};

/**
 * @param {ol.events.Event} evt Event.
 * @private
 */
ol.interaction.Snap.prototype.handleGeometryChange_ = function(evt) {
  var feature = evt.target;
  goog.asserts.assertInstanceof(feature, ol.Feature);
  this.removeFeature(feature, true);
  this.addFeature(feature, true);
};

/**
 * @param {ol.Feature} feature Feature which geometry was modified.
 * @param {ol.events.Event} evt Event.
 * @private
 */
ol.interaction.Snap.prototype.handleGeometryModify_ = function(feature, evt) {
  if (this.handlingDownUpSequence) {
    var uid = goog.getUid(feature);
    if (!(uid in this.pendingFeatures_)) {
      this.pendingFeatures_[uid] = feature;
    }
  } else {
    this.updateFeature_(feature);
  }
};

/**
 * Remove a feature from the collection of features that we may snap to.
 * @param {ol.Feature} feature Feature
 * @param {boolean=} opt_unlisten Whether to unlisten to the geometry change
 *     or not. Defaults to `true`.
 * @api
 */
ol.interaction.Snap.prototype.removeFeature = function(feature, opt_unlisten) {
  var unlisten = opt_unlisten !== undefined ? opt_unlisten : true;
  var feature_uid = goog.getUid(feature);
  var extent = this.indexedFeaturesExtents_[feature_uid];
  if (extent) {
    var rBush = this.rBush_;
    var i, nodesToRemove = [];
    rBush.forEachInExtent(extent, function(node) {
      if (feature === node.feature) {
        nodesToRemove.push(node);
      }
    });
    for (i = nodesToRemove.length - 1; i >= 0; --i) {
      rBush.remove(nodesToRemove[i]);
    }
    if (unlisten) {
      ol.Observable.unByKey(this.geometryModifyListenerKeys_[feature_uid]);
      delete this.geometryModifyListenerKeys_[feature_uid];

      ol.Observable.unByKey(this.geometryChangeListenerKeys_[feature_uid]);
      delete this.geometryChangeListenerKeys_[feature_uid];
    }
  }
};

/**
 * @inheritDoc
 */
ol.interaction.Snap.prototype.setMap = function(map) {
  var currentMap = this.getMap();
  var keys = this.featuresListenerKeys_;
  var features = this.getFeatures_();

  Iif (currentMap) {
    keys.forEach(ol.Observable.unByKey);
    keys.length = 0;
    features.forEach(this.forEachFeatureRemove_, this);
  }

  goog.base(this, 'setMap', map);

  Eif (map) {
    Eif (this.features_) {
      keys.push(
        ol.events.listen(this.features_, ol.CollectionEventType.ADD,
            this.handleFeatureAdd_, this),
        ol.events.listen(this.features_, ol.CollectionEventType.REMOVE,
            this.handleFeatureRemove_, this)
      );
    } else if (this.source_) {
      keys.push(
        ol.events.listen(this.source_, ol.source.VectorEventType.ADDFEATURE,
            this.handleFeatureAdd_, this),
        ol.events.listen(this.source_, ol.source.VectorEventType.REMOVEFEATURE,
            this.handleFeatureRemove_, this)
      );
    }
    features.forEach(this.forEachFeatureAdd_, this);
  }
};

/**
 * @inheritDoc
 */
ol.interaction.Snap.prototype.shouldStopEvent = goog.functions.FALSE;

/**
 * @param {ol.Pixel} pixel Pixel
 * @param {ol.Coordinate} pixelCoordinate Coordinate
 * @param {ol.Map} map Map.
 * @return {ol.interaction.Snap.ResultType} Snap result
 */
ol.interaction.Snap.prototype.snapTo = function(pixel, pixelCoordinate, map) {

  var lowerLeft = map.getCoordinateFromPixel(
      [pixel[0] - this.pixelTolerance_, pixel[1] + this.pixelTolerance_]);
  var upperRight = map.getCoordinateFromPixel(
      [pixel[0] + this.pixelTolerance_, pixel[1] - this.pixelTolerance_]);
  var box = ol.extent.boundingExtent([lowerLeft, upperRight]);

  var segments = this.rBush_.getInExtent(box);
  var snappedToVertex = false;
  var snapped = false;
  var vertex = null;
  var vertexPixel = null;
  Eif (segments.length > 0) {
    this.pixelCoordinate_ = pixelCoordinate;
    segments.sort(this.sortByDistance_);
    var closestSegment = segments[0].segment;
    vertex = (ol.coordinate.closestOnSegment(pixelCoordinate,
        closestSegment));
    vertexPixel = map.getPixelFromCoordinate(vertex);
    Eif (Math.sqrt(ol.coordinate.squaredDistance(pixel, vertexPixel)) <=
        this.pixelTolerance_) {
      snapped = true;
      var pixel1 = map.getPixelFromCoordinate(closestSegment[0]);
      var pixel2 = map.getPixelFromCoordinate(closestSegment[1]);
      var squaredDist1 = ol.coordinate.squaredDistance(vertexPixel, pixel1);
      var squaredDist2 = ol.coordinate.squaredDistance(vertexPixel, pixel2);
      var dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));
      snappedToVertex = dist <= this.pixelTolerance_;
      Eif (snappedToVertex) {
        vertex = squaredDist1 > squaredDist2 ?
            closestSegment[1] : closestSegment[0];
        vertexPixel = map.getPixelFromCoordinate(vertex);
        vertexPixel = [Math.round(vertexPixel[0]), Math.round(vertexPixel[1])];
      }
    }
  }
  return /** @type {ol.interaction.Snap.ResultType} */ ({
    snapped: snapped,
    vertex: vertex,
    vertexPixel: vertexPixel
  });
};

/**
 * @param {ol.Feature} feature Feature
 * @private
 */
ol.interaction.Snap.prototype.updateFeature_ = function(feature) {
  this.removeFeature(feature, false);
  this.addFeature(feature, false);
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.GeometryCollection} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writeGeometryCollectionGeometry_ = function(feature, geometry) {
  var i, geometries = geometry.getGeometriesArray();
  for (i = 0; i < geometries.length; ++i) {
    this.SEGMENT_WRITERS_[geometries[i].getType()].call(
        this, feature, geometries[i]);
  }
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.LineString} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writeLineStringGeometry_ = function(feature, geometry) {
  var coordinates = geometry.getCoordinates();
  var i, ii, segment, segmentData;
  for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
    segment = coordinates.slice(i, i + 2);
    segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
      feature: feature,
      segment: segment
    });
    this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
  }
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.MultiLineString} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writeMultiLineStringGeometry_ = function(feature, geometry) {
  var lines = geometry.getCoordinates();
  var coordinates, i, ii, j, jj, segment, segmentData;
  for (j = 0, jj = lines.length; j < jj; ++j) {
    coordinates = lines[j];
    for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
      segment = coordinates.slice(i, i + 2);
      segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
        feature: feature,
        segment: segment
      });
      this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
    }
  }
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.MultiPoint} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writeMultiPointGeometry_ = function(feature, geometry) {
  var points = geometry.getCoordinates();
  var coordinates, i, ii, segmentData;
  for (i = 0, ii = points.length; i < ii; ++i) {
    coordinates = points[i];
    segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
      feature: feature,
      segment: [coordinates, coordinates]
    });
    this.rBush_.insert(geometry.getExtent(), segmentData);
  }
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.MultiPolygon} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writeMultiPolygonGeometry_ = function(feature, geometry) {
  var polygons = geometry.getCoordinates();
  var coordinates, i, ii, j, jj, k, kk, rings, segment, segmentData;
  for (k = 0, kk = polygons.length; k < kk; ++k) {
    rings = polygons[k];
    for (j = 0, jj = rings.length; j < jj; ++j) {
      coordinates = rings[j];
      for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
        segment = coordinates.slice(i, i + 2);
        segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
          feature: feature,
          segment: segment
        });
        this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
      }
    }
  }
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.Point} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writePointGeometry_ = function(feature, geometry) {
  var coordinates = geometry.getCoordinates();
  var segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
    feature: feature,
    segment: [coordinates, coordinates]
  });
  this.rBush_.insert(geometry.getExtent(), segmentData);
};

/**
 * @param {ol.Feature} feature Feature
 * @param {ol.geom.Polygon} geometry Geometry.
 * @private
 */
ol.interaction.Snap.prototype.writePolygonGeometry_ = function(feature, geometry) {
  var rings = geometry.getCoordinates();
  var coordinates, i, ii, j, jj, segment, segmentData;
  for (j = 0, jj = rings.length; j < jj; ++j) {
    coordinates = rings[j];
    for (i = 0, ii = coordinates.length - 1; i < ii; ++i) {
      segment = coordinates.slice(i, i + 2);
      segmentData = /** @type {ol.interaction.Snap.SegmentDataType} */ ({
        feature: feature,
        segment: segment
      });
      this.rBush_.insert(ol.extent.boundingExtent(segment), segmentData);
    }
  }
};

/**
 * @typedef {{
 *     snapped: {boolean},
 *     vertex: (ol.Coordinate|null),
 *     vertexPixel: (ol.Pixel|null)
 * }}
 */
ol.interaction.Snap.ResultType;

/**
 * @typedef {{
 *     feature: ol.Feature,
 *     segment: Array.<ol.Coordinate>
 * }}
 */
ol.interaction.Snap.SegmentDataType;

/**
 * Handle all pointer events events.
 * @param {ol.MapBrowserEvent} evt A move event.
 * @return {boolean} Pass the event to other interactions.
 * @this {ol.interaction.Snap}
 * @private
 */
ol.interaction.Snap.handleEvent_ = function(evt) {
  var result = this.snapTo(evt.pixel, evt.coordinate, evt.map);
  Eif (result.snapped) {
    evt.coordinate = result.vertex.slice(0, 2);
    evt.pixel = result.vertexPixel;
  }
  return ol.interaction.Pointer.handleEvent.call(this, evt);
};

/**
 * @param {ol.MapBrowserPointerEvent} evt Event.
 * @return {boolean} Stop drag sequence?
 * @this {ol.interaction.Snap}
 * @private
 */
ol.interaction.Snap.handleUpEvent_ = function(evt) {
  var featuresToUpdate = ol.object.getValues(this.pendingFeatures_);
  if (featuresToUpdate.length) {
    featuresToUpdate.forEach(this.updateFeature_, this);
    this.pendingFeatures_ = {};
  }
  return false;
};

/**
 * Sort segments by distance, helper function
 * @param {ol.interaction.Snap.SegmentDataType} a The first segment data.
 * @param {ol.interaction.Snap.SegmentDataType} b The second segment data.
 * @return {number} The difference in distance.
 * @this {ol.interaction.Snap}
 */
ol.interaction.Snap.sortByDistance = function(a, b) {
  return ol.coordinate.squaredDistanceToSegment(
      this.pixelCoordinate_, a.segment) -
      ol.coordinate.squaredDistanceToSegment(
      this.pixelCoordinate_, b.segment);
};

  Code coverage
  generated by istanbul at Fri Mar 11 2016 13:34:39 GMT+0100 (CET)


text:
using System;

using UIKit;

using FFImageLoading;
using FFImageLoading.Work;
using FFImageLoading.Transformations;

namespace Simple.iOS.Sample
{
    public partial class ImageDetailsViewController : UIViewController
    {
        public const string SegueImageDetails = "ImageDetails-segue";

        public string imageURL = string.Empty;

        public ImageDetailsViewController(IntPtr handle)
            : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            transformation = 0;
            LoadImage();
        }

        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);
            imageURL = string.Empty;
        }

        int transformation = 0;

        protected void LoadImage()
        {
            imageView.Image = null;

            var taskImage = ImageService.Instance.LoadUrl(imageURL)
                                        .ErrorPlaceholder("error.png", ImageSource.ApplicationBundle)
                                        .LoadingPlaceholder("placeholder", ImageSource.CompiledResource);
            if(transformation==0)
            {
                taskImage.Into(imageView);
                transformation++;
            }
            else if(transformation==1)
            {
                taskImage.Transform(new CircleTransformation())
                         .Into(imageView);
                transformation++;
            }
            else if(transformation==2)
            {
                taskImage.Transform(new RoundedTransformation(10))
                         .Into(imageView);
                transformation = 0;
            }
        }

        partial void TapTransformation (Foundation.NSObject sender)
        {
            LoadImage();
        }

    }
}


text:
package apps.tree;

import structures.tree.Heap;

import java.io.*;

/**
 * This is a driver for the Heap class.
 *
 * @author Sesh Venugopal
 *
 */
public class HeapDriver {

	/**
	 * All the actions that can be issued to the driver.
	 *
	 */
	public enum Action { add, remove, display, size, clear, quit }

	/**
	 * Reader to read actions from terminal.
	 */
	static final BufferedReader stdbr = new BufferedReader(
			new InputStreamReader(System.in));

	/**
	 * Heap that is populated with HeapItem<String> instances
	 */
	static Heap<HeapItem<String>> myHeap = new Heap<HeapItem<String>>();

	/**
	 * Gets the next action issued at the terminal.
	 *
	 * @return Action issued at terminal. If three incorrect attempts are made,
	 * returns quit.
	 * @throws IOException If there is an error in reading the action.
	 */
	static Action getAction()
	throws IOException {

		int tries=3;
		while (tries > 0) {
			System.out.println();
			System.out.print("Choose one of the following actions:  ");
			for (Action act : Action.values()) {
				System.out.print(act+ "   ");
			}
			System.out.print("\n\tEnter action => ");
			System.out.flush();

			String choice = stdbr.readLine();
			for (Action act : Action.values()) {
				if (choice.trim().equals(act.name())) {
					return act;
				}
			}
			System.out.println("  Incorrect input, try again");
			tries--;
		}
		return Action.quit;
	}

	/**
	 * Adds an item to the heap.
	 *
	 * @throws IOException If there is an error reading from terminal.
	 */
	static void addItem()
	throws IOException {
		System.out.print("Item Name? => ");
		System.out.flush();
		String item = stdbr.readLine();

		System.out.print("Item Priority? => ");
		System.out.flush();
		int sid = Integer.parseInt(stdbr.readLine());

		myHeap.add(new HeapItem<String>(item,sid));
	}

	/**
	 * Removed the item at the top of the heap.
	 *
	 * @throws IOException If there is an error reading from terminal.
	 */
	static void removeItem()
	throws IOException {
		HeapItem<String> delItem = myHeap.deleteMax();
		System.out.println("Deleted " + delItem);
	}

	/**
	 * Displays all items in the heap.
	 *
	 * @throws IOException If there is an error reading from terminal.
	 */
	static void displayAllItems() {
		System.out.println();
		HeapItem<String> obj = myHeap.first();
		while (obj != null) {
			System.out.println(obj);
			obj = myHeap.next();
		}
		System.out.println();
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args)
	throws IOException {
		Action act;
		while ((act = getAction()) != Action.quit) {
			switch(act) {
			case add: addItem(); break;
			case remove: removeItem(); break;
			case display: displayAllItems(); break;
			case size: System.out.println("Size = " + myHeap.size()); break;
			case clear: myHeap.clear(); break;
			default: break;
			}
		}
	}
}


text:
namespace SampleMvcApplication1.Models
{
    public class UserModel
    {
        public int UserId { get; set; }

        public string UserName { get; set; }

        public string Email { get; set; }

        public string Description { get; set; }
    }
}


text:
/*global chrome */
chrome.app.runtime.onLaunched.addListener(function () {
    'use strict';
    chrome.app.window.create('index.html', {
        'id': 'fakeIdForSingleton',
        'innerBounds': {
            'width': 320,
            'height': 480,
            'minWidth': 320,
            'minHeight': 480
        },
        resizable: false
    });
});