text:
/*
 * MaybeValue.java
 * Created: Dec 9, 2005
 * By: Bo Ilic
 */

package org.openquark.cal.foreignsupport.module.Prelude;

/**
 * Class for supporting the instances of Inputable and Outputable for the Prelude.Maybe type.
 *
 * @author Bo Ilic
 */
public abstract class MaybeValue<T> {

    /** to ensure no subclasses other than Nothing and Just */
    private MaybeValue() {}

    /**
     * @return makes a Nothing value.
     */
    @SuppressWarnings("unchecked")
    public static <T> MaybeValue<T> makeNothing() {
        return (MaybeValue<T>)Nothing.NOTHING;
    }

    /**
     * @param value
     * @return makes a Just value.
     */
    public static <T> MaybeValue<T> makeJust(T value) {
        return new Just<T>(value);
    }

    /**
     * @param value
     * @return a Nothing value if value is null, otherwise a Just value holding the value argument.
     */
    public static <T> MaybeValue<T> makeMaybe(T value) {
        if (value == null) {
            return makeNothing();
        } else {
            return makeJust(value);
        }
    }

    /**
     * @return true for a Prelude.Nothing value, false for a Prelude.Just value.
     */
    public abstract boolean isNothing();

    /**
     * @return true for a Prelude.Just value, false for a Prelude.Nothing value.
     */
    public abstract boolean isJust();

    /**
     * @return null for a Nothing value and the held value for a Maybe value. Note that a Maybe value might hold a null so
     *   we can't use this method to distinguish between Nothing and Maybe null. Call isNothing or isJust to tell this.
     */
    public abstract T getValueField();

    /**
     * {@inheritDoc}
     * @return representation of the Maybe value suitable for use for debugging.
     */
    @Override
    public abstract String toString();

    /**
     * Supports the Inputable and Outputable instances of the Prelude.Maybe type in
     * their handling of the Prelude.Nothing data constructor.
     *
     * @author Bo Ilic
     */
    private static final class Nothing<T> extends MaybeValue<T> {

        /** singleton instance of Nothing */
        private static final Nothing<Object> NOTHING = new Nothing<Object>();

        private Nothing () {
        }

        /** {@inheritDoc} */
        @Override
        public boolean isNothing() {
            return true;
        }

        /** {@inheritDoc} */
        @Override
        public boolean isJust() {
            return false;
        }

        /** {@inheritDoc} */
        @Override
        public T getValueField() {
            return null;
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "Cal.Core.Prelude.Nothing";
        }
    }

    /**
     * Supports the Inputable and Outputable instances of the Prelude.Maybe type in
     * their handling of the Prelude.Just data constructor.
     *
     * @author Bo Ilic
     */
    private static final class Just<T> extends MaybeValue<T> {

        private final T value;

        private Just(T value) {
            this.value = value;
        }

        /** {@inheritDoc} */
        @Override
        public boolean isNothing() {
            return false;
        }

        /** {@inheritDoc} */
        @Override
        public boolean isJust() {
            return true;
        }

        /** {@inheritDoc} */
        @Override
        public T getValueField() {
            return value;
        }

        /** {@inheritDoc} */
        @Override
        public String toString() {
            return "(Cal.Core.Prelude.Just " + value + ')';
        }
    }

}


text:
var nodeunit = require('nodeunit'),
    utils = require('./utils'),
    task = require('../../lib/resources/task');

/* Test constructor fns */
var constructors = {
    "task.Task": {
        fn: task.Task,
        args: [
            {
                kind: 'task',
                id: 54322,
                storyId: 32452542424,
                position: 110,
                description: 'publish the module to npm',
                complete: true,
                createdAt: new Date(0),
                updatedAt: new Date(7000)
            }
        ]
    },
    "task.Service": {
        fn: task.Service,
        args: []
    }
};
for (var key in constructors) {
    if (constructors.hasOwnProperty(key)) {
    	module.exports['test_'+key] = new utils.ConstructorTest(key,constructors[key]);
    }
}

/* Test primitive property setters & getters */
var testData = [
	{
		propertyName: 'kind',
		happyTestValue: 'task'
	},
	{
		propertyName: 'id',
		happyTestValue: 62234234
	},
	{
		propertyName: 'storyId',
		happyTestValue: 62234234
	},
	{
		propertyName: 'description',
		happyTestValue: 'wheeeeee!'
	}
];
for (var i=0;i<testData.length;i++) {
	module.exports['test_'+testData[i].propertyName] =
		utils.standardPropertyTestFunction(task.Task,testData[i].propertyName,testData[i].happyTestValue);
}

/* Testing Date inputs */
var dateTestProperties = [
	'createdAt',
	'updatedAt',
];
var dateObj = new Date();
var dateStr = '2000-01-01 00:00';
for (var i=0; i < dateTestProperties.length; i++) {

	module.exports['test_'+dateTestProperties[i]] =
		utils.standardDatePropertyTestFunction(task.Task,dateTestProperties[i],dateObj);

	module.exports['test_'+dateTestProperties[i]] =
		utils.standardDatePropertyTestFunction(task.Task,dateTestProperties[i],dateStr);
}

redpajama_set_name: RedPajamaGithub


text:
using MuksanDemo.Areas.Security.Models;
using MuksanDemo.Dal;
using Mydudungcharing.dal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MuksanDemo.Areas.Security.Controllers
{
    public class UsersController : Controller
    {
        private IList<UserViewModel> Users
        {
            get
            {
                if (Session["data"] == null)
                {
                    Session["data"] = new List<UserViewModel>(){
                        new UserViewModel {
                             //Id = Guid.NewGuid(),
                             FirstName = "Lance",
                             Gender = "Male",
                             LastName = "Selot",
                             Age = 21
                        },
                        new UserViewModel {
                             //Id = Guid.NewGuid(),
                             FirstName = "Lance",
                             Gender = "Female",
                             LastName = "Oscar",
                             Age = 59
                        }
                    };
                }
                return Session["data"] as List<UserViewModel>;
            }
        }
        // GET: Security/Users
        public ActionResult Index()
        {
            using(var db = new DatabaseContext())
            {
                var users = (from user in db.Users
                             select new UserViewModel
                             {
                                 Id = user.Id,
                                 FirstName = user.Firstname,
                                 LastName = user.Lastname,
                                 Gender = user.Gender,
                                 Age = user.Age
                             }).ToList();
                return View(users);

            }

        }

        // GET: Security/Users/Details/5
        public ActionResult Details(int id)
        {
            using (var db = new DatabaseContext())
            {
                var users = (from user in db.Users
                             where user.Id == id
                             select new UserViewModel
            {
                Id = user.Id,
                FirstName = user.Firstname,
                Gender = user.Gender,
                LastName = user.Lastname,
                Age = user.Age
            }).FirstOrDefault();
                return View(users);
            }
        }

        // GET: Security/Users/Create
        public ActionResult Create()
        {
            ViewBag.Gender = new List<SelectListItem>{
            {
                new SelectListItem
                {
                    Value ="Male",
                    Text = "Male"
                }
            },
            new SelectListItem
                {
                    Value = "Female",
                    Text = "Female"
                }

            };
             return View();
        }

        // POST: Security/Users/Create
        [HttpPost]
        public ActionResult Create(UserViewModel viewModel)
        {
            try
            {
                if (ModelState.IsValid == false)
                    return View();
                using (var db = new DatabaseContext())
                {
                    db.Users.Add(new User
                    {
                        //ID = Guid.NewGuid(),
                        Firstname = viewModel.FirstName,
                        Gender = viewModel.Gender,
                        Lastname = viewModel.LastName,
                        Age = viewModel.Age
                    });
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();

            }
        }

        // GET: Security/Users/Edit/5
        public ActionResult Edit(int id)
        {
            using (var db = new DatabaseContext())
            {
                var users = (from user in db.Users
                             where user.Id == id
                             select new UserViewModel
                             {
                                 Id = user.Id,
                                 FirstName = user.Firstname,
                                 Gender = user.Gender,
                                 LastName = user.Lastname,
                                 Age = user.Age
                             }).FirstOrDefault();
                return View(users);
            }
        }

        // POST: Security/Users/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, UserViewModel viewModel)
        {
            try
            {
                // TODO: Add update logic here
             if (ModelState.IsValid == false)
                    return View();
                using (var db = new DatabaseContext())
                {
                    var users = (from user in db.Users
                                 where user.Id == id
                                 select user).FirstOrDefault();

                       //ID = Guid.NewGuid(),
                        users.Firstname = viewModel.FirstName;
                        users.Gender = viewModel.Gender;
                        users.Lastname = viewModel.LastName;
                        users.Age = viewModel.Age;

                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Security/Users/Delete/5
        public ActionResult Delete(int id)
        {
            using (var db = new DatabaseContext())
            {
                var users = (from user in db.Users where user.Id == id
                                 select new UserViewModel
                {
                    Id = user.Id,
                    FirstName = user.Firstname,
                    Gender = user.Gender,
                    LastName = user.Lastname,
                    Age = user.Age
                }).FirstOrDefault();
                return View(users);
            }

        }

        // POST: Security/Users/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            //try
            //{
                // TODO: Add delete logic here

                using (var db = new DatabaseContext())
                {
                    var users = (from user in db.Users
                                 where user.Id == id
                                 select user).FirstOrDefault();
                    db.Users.Remove(users);
                    db.SaveChanges();
                }
                return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}
        }

    }
}


text:
go-higgsml
==========

`go-higgsml` is a simple starting-kit for the HiggsML challenge:
  http://higgsml.lal.in2p3.fr/

(this `go-higgsml` kit is a transcription of the `python` one from
[here](http://higgsml.lal.in2p3.fr/software/simplest-python-kit/))

## Installation

```sh
$ go get github.com/sbinet/go-higgsml
```

## Example

Once you've downloaded the `test.csv` and `training.csv` files from
[Kaggle](https://www.kaggle.com/c/connectomics/data):

```sh
$ go-higgsml -train training.csv trained.dat
::: read training file [training.csv]
::: loop on training dataset and compute the score
::: loop again to determine the AMS, using threshold=-22
::: AMS computed from training file=1.5289067550142865 (sig=457.2791382866634, bkg=89291.91212537605)
::: timing: 8.482504175s
::: bye.

$ go-higgsml test.csv trained.dat scores_test.csv
::: compute the score for the test file entries [test.csv]
::: loop again on test file to load BDT score pairs
::: sort on the score
::: build a map key=id, value=rank
::: you can now submit [scores_test.csv] to Kaggle website
::: timing: 22.022769973s
::: bye.
```


text: Bank account analitics


text:
if(!dojo._hasResource["dojox.gfx.shape"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.gfx.shape"] = true;
dojo.provide("dojox.gfx.shape");

dojo.require("dojox.gfx._base");

dojo.declare("dojox.gfx.Shape", null, {
	// summary: a Shape object, which knows how to apply
	// graphical attributes and transformations

	constructor: function(){
		// rawNode: Node: underlying node
		this.rawNode = null;

		// shape: Object: an abstract shape object
		//	(see dojox.gfx.defaultPath,
		//	dojox.gfx.defaultPolyline,
		//	dojox.gfx.defaultRect,
		//	dojox.gfx.defaultEllipse,
		//	dojox.gfx.defaultCircle,
		//	dojox.gfx.defaultLine,
		//	or dojox.gfx.defaultImage)
		this.shape = null;

		// matrix: dojox.gfx.Matrix2D: a transformation matrix
		this.matrix = null;

		// fillStyle: Object: a fill object
		//	(see dojox.gfx.defaultLinearGradient,
		//	dojox.gfx.defaultRadialGradient,
		//	dojox.gfx.defaultPattern,
		//	or dojo.Color)
		this.fillStyle = null;

		// strokeStyle: Object: a stroke object
		//	(see dojox.gfx.defaultStroke)
		this.strokeStyle = null;

		// bbox: dojox.gfx.Rectangle: a bounding box of this shape
		//	(see dojox.gfx.defaultRect)
		this.bbox = null;

		// virtual group structure

		// parent: Object: a parent or null
		//	(see dojox.gfx.Surface,
		//	dojox.gfx.shape.VirtualGroup,
		//	or dojox.gfx.Group)
		this.parent = null;

		// parentMatrix: dojox.gfx.Matrix2D
		//	a transformation matrix inherited from the parent
		this.parentMatrix = null;
	},

	// trivial getters

	getNode: function(){
		// summary: returns the current DOM Node or null
		return this.rawNode; // Node
	},
	getShape: function(){
		// summary: returns the current shape object or null
		//	(see dojox.gfx.defaultPath,
		//	dojox.gfx.defaultPolyline,
		//	dojox.gfx.defaultRect,
		//	dojox.gfx.defaultEllipse,
		//	dojox.gfx.defaultCircle,
		//	dojox.gfx.defaultLine,
		//	or dojox.gfx.defaultImage)
		return this.shape; // Object
	},
	getTransform: function(){
		// summary: returns the current transformation matrix or null
		return this.matrix;	// dojox.gfx.Matrix2D
	},
	getFill: function(){
		// summary: returns the current fill object or null
		//	(see dojox.gfx.defaultLinearGradient,
		//	dojox.gfx.defaultRadialGradient,
		//	dojox.gfx.defaultPattern,
		//	or dojo.Color)
		return this.fillStyle;	// Object
	},
	getStroke: function(){
		// summary: returns the current stroke object or null
		//	(see dojox.gfx.defaultStroke)
		return this.strokeStyle;	// Object
	},
	getParent: function(){
		// summary: returns the parent or null
		//	(see dojox.gfx.Surface,
		//	dojox.gfx.shape.VirtualGroup,
		//	or dojox.gfx.Group)
		return this.parent;	// Object
	},
	getBoundingBox: function(){
		// summary: returns the bounding box or null
		//	(see dojox.gfx.defaultRect)
		return this.bbox;	// dojox.gfx.Rectangle
	},
	getTransformedBoundingBox: function(){
		// summary: returns an array of four points or null
		//	four points represent four corners of the untransformed bounding box
		var b = this.getBoundingBox();
		if(!b){
			return null;	// null
		}
		var m = this._getRealMatrix();
		var r = [];
		var g = dojox.gfx.matrix;
		r.push(g.multiplyPoint(m, b.x, b.y));
		r.push(g.multiplyPoint(m, b.x + b.width, b.y));
		r.push(g.multiplyPoint(m, b.x + b.width, b.y + b.height));
		r.push(g.multiplyPoint(m, b.x, b.y + b.height));
		return r;	// Array
	},
	getEventSource: function(){
		// summary: returns a Node, which is used as
		//	a source of events for this shape

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		return this.rawNode;	// Node
	},

	// empty settings

	setShape: function(shape){
		// summary: sets a shape object
		//	(the default implementation simply ignores it)
		// shape: Object: a shape object
		//	(see dojox.gfx.defaultPath,
		//	dojox.gfx.defaultPolyline,
		//	dojox.gfx.defaultRect,
		//	dojox.gfx.defaultEllipse,
		//	dojox.gfx.defaultCircle,
		//	dojox.gfx.defaultLine,
		//	or dojox.gfx.defaultImage)

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		this.shape = dojox.gfx.makeParameters(this.shape, shape);
		this.bbox = null;
		return this;	// self
	},
	setFill: function(fill){
		// summary: sets a fill object
		//	(the default implementation simply ignores it)
		// fill: Object: a fill object
		//	(see dojox.gfx.defaultLinearGradient,
		//	dojox.gfx.defaultRadialGradient,
		//	dojox.gfx.defaultPattern,
		//	or dojo.Color)

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		if(!fill){
			// don't fill
			this.fillStyle = null;
			return this;	// self
		}
		var f = null;
		if(typeof(fill) == "object" && "type" in fill){
			// gradient or pattern
			switch(fill.type){
				case "linear":
					f = dojox.gfx.makeParameters(dojox.gfx.defaultLinearGradient, fill);
					break;
				case "radial":
					f = dojox.gfx.makeParameters(dojox.gfx.defaultRadialGradient, fill);
					break;
				case "pattern":
					f = dojox.gfx.makeParameters(dojox.gfx.defaultPattern, fill);
					break;
			}
		}else{
			// color object
			f = dojox.gfx.normalizeColor(fill);
		}
		this.fillStyle = f;
		return this;	// self
	},
	setStroke: function(stroke){
		// summary: sets a stroke object
		//	(the default implementation simply ignores it)
		// stroke: Object: a stroke object
		//	(see dojox.gfx.defaultStroke)

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		if(!stroke){
			// don't stroke
			this.strokeStyle = null;
			return this;	// self
		}
		// normalize the stroke
		if(typeof stroke == "string"){
			stroke = {color: stroke};
		}
		var s = this.strokeStyle = dojox.gfx.makeParameters(dojox.gfx.defaultStroke, stroke);
		s.color = dojox.gfx.normalizeColor(s.color);
		return this;	// self
	},
	setTransform: function(matrix){
		// summary: sets a transformation matrix
		// matrix: dojox.gfx.Matrix2D: a matrix or a matrix-like object
		//	(see an argument of dojox.gfx.Matrix2D
		//	constructor for a list of acceptable arguments)

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		this.matrix = dojox.gfx.matrix.clone(matrix ? dojox.gfx.matrix.normalize(matrix) : dojox.gfx.matrix.identity);
		return this._applyTransform();	// self
	},

	_applyTransform: function(){
		// summary: physically sets a matrix

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		return this;	// self
	},

	// z-index

	moveToFront: function(){
		// summary: moves a shape to front of its parent's list of shapes
		var p = this.getParent();
		if(p){
			p._moveChildToFront(this);
			this._moveToFront();	// execute renderer-specific action
		}
		return this;	// self
	},
	moveToBack: function(){
		// summary: moves a shape to back of its parent's list of shapes
		var p = this.getParent();
		if(p){
			p._moveChildToBack(this);
			this._moveToBack();	// execute renderer-specific action
		}
		return this;
	},
	_moveToFront: function(){
		// summary: renderer-specific hook, see dojox.gfx.shape.Shape.moveToFront()

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!
	},
	_moveToBack: function(){
		// summary: renderer-specific hook, see dojox.gfx.shape.Shape.moveToFront()

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!
	},

	// apply left & right transformation

	applyRightTransform: function(matrix){
		// summary: multiplies the existing matrix with an argument on right side
		//	(this.matrix * matrix)
		// matrix: dojox.gfx.Matrix2D: a matrix or a matrix-like object
		//	(see an argument of dojox.gfx.Matrix2D
		//	constructor for a list of acceptable arguments)
		return matrix ? this.setTransform([this.matrix, matrix]) : this;	// self
	},
	applyLeftTransform: function(matrix){
		// summary: multiplies the existing matrix with an argument on left side
		//	(matrix * this.matrix)
		// matrix: dojox.gfx.Matrix2D: a matrix or a matrix-like object
		//	(see an argument of dojox.gfx.Matrix2D
		//	constructor for a list of acceptable arguments)
		return matrix ? this.setTransform([matrix, this.matrix]) : this;	// self
	},
	applyTransform: function(matrix){
		// summary: a shortcut for dojox.gfx.Shape.applyRightTransform
		// matrix: dojox.gfx.Matrix2D: a matrix or a matrix-like object
		//	(see an argument of dojox.gfx.Matrix2D
		//	constructor for a list of acceptable arguments)
		return matrix ? this.setTransform([this.matrix, matrix]) : this;	// self
	},

	// virtual group methods

	removeShape: function(silently){
		// summary: removes the shape from its parent's list of shapes
		// silently: Boolean?: if true, do not redraw a picture yet
		if(this.parent){
			this.parent.remove(this, silently);
		}
		return this;	// self
	},
	_setParent: function(parent, matrix){
		// summary: sets a parent
		// parent: Object: a parent or null
		//	(see dojox.gfx.Surface,
		//	dojox.gfx.shape.VirtualGroup,
		//	or dojox.gfx.Group)
		// matrix: dojox.gfx.Matrix2D:
		//	a 2D matrix or a matrix-like object
		this.parent = parent;
		return this._updateParentMatrix(matrix);	// self
	},
	_updateParentMatrix: function(matrix){
		// summary: updates the parent matrix with new matrix
		// matrix: dojox.gfx.Matrix2D:
		//	a 2D matrix or a matrix-like object
		this.parentMatrix = matrix ? dojox.gfx.matrix.clone(matrix) : null;
		return this._applyTransform();	// self
	},
	_getRealMatrix: function(){
		// summary: returns the cumulative ("real") transformation matrix
		//	by combining the shape's matrix with its parent's matrix
		var m = this.matrix;
		var p = this.parent;
		while(p){
			if(p.matrix){
				m = dojox.gfx.matrix.multiply(p.matrix, m);
			}
			p = p.parent;
		}
		return m;	// dojox.gfx.Matrix2D
	}
});

dojox.gfx.shape._eventsProcessing = {
	connect: function(name, object, method){
		// summary: connects a handler to an event on this shape

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		return arguments.length > 2 ?	// Object
			dojo.connect(this.getEventSource(), name, object, method) :
			dojo.connect(this.getEventSource(), name, object);
	},
	disconnect: function(token){
		// summary: connects a handler by token from an event on this shape

		// COULD BE RE-IMPLEMENTED BY THE RENDERER!

		dojo.disconnect(token);
	}
};

dojo.extend(dojox.gfx.Shape, dojox.gfx.shape._eventsProcessing);

dojox.gfx.shape.Container = {
	// summary: a container of shapes, which can be used
	//	as a foundation for renderer-specific groups, or as a way
	//	to logically group shapes (e.g, to propagate matricies)

	_init: function() {
		// children: Array: a list of children
		this.children = [];
	},

	// group management

	add: function(shape){
		// summary: adds a shape to the list
		// shape: dojox.gfx.Shape: a shape
		var oldParent = shape.getParent();
		if(oldParent){
			oldParent.remove(shape, true);
		}
		this.children.push(shape);
		return shape._setParent(this, this._getRealMatrix());	// self
	},
	remove: function(shape, silently){
		// summary: removes a shape from the list
		// silently: Boolean?: if true, do not redraw a picture yet
		for(var i = 0; i < this.children.length; ++i){
			if(this.children[i] == shape){
				if(silently){
					// skip for now
				}else{
					shape._setParent(null, null);
				}
				this.children.splice(i, 1);
				break;
			}
		}
		return this;	// self
	},
	clear: function(){
		// summary: removes all shapes from a group/surface
		this.children = [];
		return this;	// self
	},

	// moving child nodes

	_moveChildToFront: function(shape){
		// summary: moves a shape to front of the list of shapes
		for(var i = 0; i < this.children.length; ++i){
			if(this.children[i] == shape){
				this.children.splice(i, 1);
				this.children.push(shape);
				break;
			}
		}
		return this;	// self
	},
	_moveChildToBack: function(shape){
		// summary: moves a shape to back of the list of shapes
		for(var i = 0; i < this.children.length; ++i){
			if(this.children[i] == shape){
				this.children.splice(i, 1);
				this.children.unshift(shape);
				break;
			}
		}
		return this;	// self
	}
};

dojo.declare("dojox.gfx.shape.Surface", null, {
	// summary: a surface object to be used for drawings
	constructor: function(){
		// underlying node
		this.rawNode = null;
	},
	getEventSource: function(){
		// summary: returns a node, which can be used to attach event listeners
		return this.rawNode; // Node
	},
	_getRealMatrix: function(){
		// summary: always returns the identity matrix
		return null;	// dojox.gfx.Matrix2D
	}
});

dojo.extend(dojox.gfx.shape.Surface, dojox.gfx.shape._eventsProcessing);

dojo.declare("dojox.gfx.Point", null, {
	// summary: a hypothetical 2D point to be used for drawings - {x, y}
	// description: This object is defined for documentation purposes.
	//	You should use the naked object instead: {x: 1, y: 2}.
});

dojo.declare("dojox.gfx.Rectangle", null, {
	// summary: a hypothetical rectangle - {x, y, width, height}
	// description: This object is defined for documentation purposes.
	//	You should use the naked object instead: {x: 1, y: 2, width: 100, height: 200}.
});

dojo.declare("dojox.gfx.shape.Rect", dojox.gfx.Shape, {
	// summary: a generic rectangle
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultRect);
		this.rawNode = rawNode;
	},
	getBoundingBox: function(){
		// summary: returns the bounding box (its shape in this case)
		return this.shape;	// dojox.gfx.Rectangle
	}
});

dojo.declare("dojox.gfx.shape.Ellipse", dojox.gfx.Shape, {
	// summary: a generic ellipse
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultEllipse);
		this.rawNode = rawNode;
	},
	getBoundingBox: function(){
		// summary: returns the bounding box
		if(!this.bbox){
			var shape = this.shape;
			this.bbox = {x: shape.cx - shape.rx, y: shape.cy - shape.ry,
				width: 2 * shape.rx, height: 2 * shape.ry};
		}
		return this.bbox;	// dojox.gfx.Rectangle
	}
});

dojo.declare("dojox.gfx.shape.Circle", dojox.gfx.Shape, {
	// summary: a generic circle
	//	(this is a helper object, which is defined for convenience)
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultCircle);
		this.rawNode = rawNode;
	},
	getBoundingBox: function(){
		// summary: returns the bounding box
		if(!this.bbox){
			var shape = this.shape;
			this.bbox = {x: shape.cx - shape.r, y: shape.cy - shape.r,
				width: 2 * shape.r, height: 2 * shape.r};
		}
		return this.bbox;	// dojox.gfx.Rectangle
	}
});

dojo.declare("dojox.gfx.shape.Line", dojox.gfx.Shape, {
	// summary: a generic line
	//	(this is a helper object, which is defined for convenience)
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultLine);
		this.rawNode = rawNode;
	},
	getBoundingBox: function(){
		// summary: returns the bounding box
		if(!this.bbox){
			var shape = this.shape;
			this.bbox = {
				x:		Math.min(shape.x1, shape.x2),
				y:		Math.min(shape.y1, shape.y2),
				width:	Math.abs(shape.x2 - shape.x1),
				height:	Math.abs(shape.y2 - shape.y1)
			};
		}
		return this.bbox;	// dojox.gfx.Rectangle
	}
});

dojo.declare("dojox.gfx.shape.Polyline", dojox.gfx.Shape, {
	// summary: a generic polyline/polygon
	//	(this is a helper object, which is defined for convenience)
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultPolyline);
		this.rawNode = rawNode;
	},
	setShape: function(points, closed){
		// summary: sets a polyline/polygon shape object
		// points: Object: a polyline/polygon shape object
		// closed: Boolean: close the polyline to make a polygon
		if(points && points instanceof Array){
			// points: Array: an array of points
			dojox.gfx.Shape.prototype.setShape.call(this, {points: points});
			if(closed && this.shape.points.length){
				this.shape.points.push(this.shape.points[0]);
			}
		}else{
			dojox.gfx.Shape.prototype.setShape.call(this, points);
		}
		return this;	// self
	},
	getBoundingBox: function(){
		// summary: returns the bounding box
		if(!this.bbox && this.shape.points.length){
			var p = this.shape.points;
			var l = p.length;
			var t = p[0];
			var bbox = {l: t.x, t: t.y, r: t.x, b: t.y};
			for(var i = 1; i < l; ++i){
				t = p[i];
				if(bbox.l > t.x) bbox.l = t.x;
				if(bbox.r < t.x) bbox.r = t.x;
				if(bbox.t > t.y) bbox.t = t.y;
				if(bbox.b < t.y) bbox.b = t.y;
			}
			this.bbox = {
				x:		bbox.l,
				y:		bbox.t,
				width:	bbox.r - bbox.l,
				height:	bbox.b - bbox.t
			};
		}
		return this.bbox;	// dojox.gfx.Rectangle
	}
});

dojo.declare("dojox.gfx.shape.Image", dojox.gfx.Shape, {
	// summary: a generic image
	//	(this is a helper object, which is defined for convenience)
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.shape = dojo.clone(dojox.gfx.defaultImage);
		this.rawNode = rawNode;
	},
	getBoundingBox: function(){
		// summary: returns the bounding box (its shape in this case)
		return this.shape;	// dojox.gfx.Rectangle
	},
	setStroke: function(){
		// summary: ignore setting a stroke style
		return this;	// self
	},
	setFill: function(){
		// summary: ignore setting a fill style
		return this;	// self
	}
});

dojo.declare("dojox.gfx.shape.Text", dojox.gfx.Shape, {
	// summary: a generic text
	constructor: function(rawNode) {
		// rawNode: Node: a DOM Node
		this.fontStyle = null;
		this.shape = dojo.clone(dojox.gfx.defaultText);
		this.rawNode = rawNode;
	},
	getFont: function(){
		// summary: returns the current font object or null
		return this.fontStyle;	// Object
	},
	setFont: function(newFont){
		// summary: sets a font for text
		// newFont: Object: a font object (see dojox.gfx.defaultFont) or a font string
		this.fontStyle = typeof newFont == "string" ? dojox.gfx.splitFontString(newFont) :
			dojox.gfx.makeParameters(dojox.gfx.defaultFont, newFont);
		this._setFont();
		return this;	// self
	}
});

dojox.gfx.shape.Creator = {
	// summary: shape creators
	createShape: function(shape){
		// summary: creates a shape object based on its type; it is meant to be used
		//	by group-like objects
		// shape: Object: a shape descriptor object
		switch(shape.type){
			case dojox.gfx.defaultPath.type:		return this.createPath(shape);
			case dojox.gfx.defaultRect.type:		return this.createRect(shape);
			case dojox.gfx.defaultCircle.type:		return this.createCircle(shape);
			case dojox.gfx.defaultEllipse.type:		return this.createEllipse(shape);
			case dojox.gfx.defaultLine.type:		return this.createLine(shape);
			case dojox.gfx.defaultPolyline.type:	return this.createPolyline(shape);
			case dojox.gfx.defaultImage.type:		return this.createImage(shape);
			case dojox.gfx.defaultText.type:		return this.createText(shape);
			case dojox.gfx.defaultTextPath.type:	return this.createTextPath(shape);
		}
		return null;
	},
	createGroup: function(){
		// summary: creates an SVG group shape
		return this.createObject(dojox.gfx.Group);	// dojox.gfx.Group
	},
	createRect: function(rect){
		// summary: creates an SVG rectangle shape
		// rect: Object: a path object (see dojox.gfx.defaultRect)
		return this.createObject(dojox.gfx.Rect, rect);	// dojox.gfx.Rect
	},
	createEllipse: function(ellipse){
		// summary: creates an SVG ellipse shape
		// ellipse: Object: an ellipse object (see dojox.gfx.defaultEllipse)
		return this.createObject(dojox.gfx.Ellipse, ellipse);	// dojox.gfx.Ellipse
	},
	createCircle: function(circle){
		// summary: creates an SVG circle shape
		// circle: Object: a circle object (see dojox.gfx.defaultCircle)
		return this.createObject(dojox.gfx.Circle, circle);	// dojox.gfx.Circle
	},
	createLine: function(line){
		// summary: creates an SVG line shape
		// line: Object: a line object (see dojox.gfx.defaultLine)
		return this.createObject(dojox.gfx.Line, line);	// dojox.gfx.Line
	},
	createPolyline: function(points){
		// summary: creates an SVG polyline/polygon shape
		// points: Object: a points object (see dojox.gfx.defaultPolyline)
		//	or an Array of points
		return this.createObject(dojox.gfx.Polyline, points);	// dojox.gfx.Polyline
	},
	createImage: function(image){
		// summary: creates an SVG image shape
		// image: Object: an image object (see dojox.gfx.defaultImage)
		return this.createObject(dojox.gfx.Image, image);	// dojox.gfx.Image
	},
	createText: function(text){
		// summary: creates an SVG text shape
		// text: Object: a text object (see dojox.gfx.defaultText)
		return this.createObject(dojox.gfx.Text, text);	// dojox.gfx.Text
	},
	createPath: function(path){
		// summary: creates an SVG path shape
		// path: Object: a path object (see dojox.gfx.defaultPath)
		return this.createObject(dojox.gfx.Path, path);	// dojox.gfx.Path
	},
	createTextPath: function(text){
		// summary: creates an SVG text shape
		// text: Object: a textpath object (see dojox.gfx.defaultTextPath)
		return this.createObject(dojox.gfx.TextPath, {}).setText(text);	// dojox.gfx.TextPath
	},
	createObject: function(shapeType, rawShape){
		// summary: creates an instance of the passed shapeType class
		// shapeType: Function: a class constructor to create an instance of
		// rawShape: Object: properties to be passed in to the classes "setShape" method

		// SHOULD BE RE-IMPLEMENTED BY THE RENDERER!

		return null;	// dojox.gfx.Shape
	}
};

}


text:
package org.copperengine.monitoring.client.screenshotgen.view.repository;

import javafx.scene.layout.BorderPane;

import org.copperengine.monitoring.client.screenshotgen.view.fixture.ScreenshotPageBase;
import org.copperengine.monitoring.client.screenshotgen.view.fixture.TestFormContext;

public class Repository extends ScreenshotPageBase {

    @Override
    public void initGui(BorderPane pane, TestFormContext testFormContext) {
        testFormContext.createWorkflowRepositoryForm().show();
    }

    @Override
    public String getTitle() {
        return "Repository";
    }

}


text:
const assert = require('assert')

const { nextTick } = require('../lib/nextTick')

describe('process', () => {
  describe('#nextTick', () => {
    it('ticks', async () => {
      await nextTick()
      await nextTick()
      await nextTick()

      assert.ok(true, 'done')
    })
  })
})


text:
import { OneProjPage } from './app.po';

describe('one-point-oh-project App', () => {
  let page: OneProjPage;

  beforeEach(() => {
    page = new OneProjPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('app works!');
  });
});


text:
====================================
WeRoBot
====================================

.. image:: https://travis-ci.org/whtsky/WeRoBot.svg?branch=develop
    :target: https://travis-ci.org/whtsky/WeRoBot
.. image:: https://coveralls.io/repos/github/whtsky/WeRoBot/badge.svg?branch=develop
    :target: https://coveralls.io/github/whtsky/WeRoBot?branch=develop
.. image:: https://scrutinizer-ci.com/g/whtsky/WeRoBot/badges/quality-score.png?b=develop
    :target: https://scrutinizer-ci.com/g/whtsky/WeRoBot/?branch=develop

WeRoBot 是一个微信机器人框架,采用MIT协议发布。

文档在这里: https://werobot.readthedocs.org/en/latest/

安装
========

推荐使用 pip 进行安装 ::

    pip install werobot

如果你没有安装 pip 而且正在使用一台 OS X / Linux 电脑,那么你应该运行 ::

    curl http://peak.telecommunity.com/dist/ez_setup.py | python
    curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

如果你是 Windows 用户, 那么下载 http://peak.telecommunity.com/dist/ez_setup.py 和 https://raw.github.com/pypa/pip/master/contrib/get-pip.py 这两个文件,双击运行。

Hello World
=============

一个非常简单的 Hello World 微信机器人,会对收到的所有文本消息回复 Hello World ::

    import werobot

    robot = werobot.WeRoBot(token='tokenhere')

    @robot.text
    def hello_world():
        return 'Hello World!'

    robot.run()

Session
===========

WeRoBot 在 0.4.0 版本中开始支持 Session , Session 可以用来方便的记录用户数据 ::

    import werobot

    robot = werobot.WeRoBot(token='tokenhere', enable_session=True)

    @robot.text
    def session(message, session):
        last = session.get("last", None)
        if last:
            return last
        session["last"] = message.content
        return '这是你第一次和我说话'

    robot.run()


text:
.comments .btn {
  background: #92b3d4;
  color: white !important;
}
.comments .btn:hover,
.comments .btn:focus {
  background: #ffec82 !important;
  color: black !important;
}


text:
package org.gradle.initialization;

import org.gradle.StartParameter;
import org.gradle.api.internal.DynamicObjectAware;
import org.gradle.api.internal.GradleInternal;
import org.gradle.api.internal.SettingsInternal;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.internal.initialization.ScriptHandlerFactory;
import org.gradle.api.internal.properties.GradleProperties;
import org.gradle.groovy.scripts.ScriptSource;
import org.gradle.internal.extensibility.ExtensibleDynamicObject;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.service.scopes.ServiceRegistryFactory;

import java.io.File;
import java.util.Map;

import static java.util.Collections.emptyMap;

public class SettingsFactory {
    private final Instantiator instantiator;
    private final ServiceRegistryFactory serviceRegistryFactory;
    private final ScriptHandlerFactory scriptHandlerFactory;

    public SettingsFactory(Instantiator instantiator, ServiceRegistryFactory serviceRegistryFactory, ScriptHandlerFactory scriptHandlerFactory) {
        this.instantiator = instantiator;
        this.serviceRegistryFactory = serviceRegistryFactory;
        this.scriptHandlerFactory = scriptHandlerFactory;
    }

    public SettingsInternal createSettings(
        GradleInternal gradle,
        File settingsDir,
        ScriptSource settingsScript,
        GradleProperties gradleProperties,
        StartParameter startParameter,
        ClassLoaderScope baseClassLoaderScope
    ) {
        ClassLoaderScope classLoaderScope = baseClassLoaderScope.createChild("settings[" + gradle.getIdentityPath() + "]", null);
        DefaultSettings settings = instantiator.newInstance(
            DefaultSettings.class,
            serviceRegistryFactory,
            gradle,
            classLoaderScope,
            baseClassLoaderScope,
            scriptHandlerFactory.create(settingsScript, classLoaderScope),
            settingsDir,
            settingsScript,
            startParameter
        );
        Map<String, Object> properties = gradleProperties.mergeProperties(emptyMap());
        DynamicObject dynamicObject = ((DynamicObjectAware) settings).getAsDynamicObject();
        ((ExtensibleDynamicObject) dynamicObject).addProperties(properties);
        return settings;
    }
}


text:
<?php

namespace Etu\Module\BugsBundle\Notification\Helper;

use Etu\Core\CoreBundle\Entity\Notification;
use Etu\Core\CoreBundle\Notification\Helper\HelperInterface;

/**
 * Notification for a new comment on an issue.
 */
class NewCommentHelper implements HelperInterface
{
    /**
     * @var \Twig_Environment
     */
    protected $twig;

    public function __construct(\Twig_Environment $twig)
    {
        $this->twig = $twig;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'bugs_new_comment';
    }

    /**
     * @return string
     */
    public function render(Notification $notification)
    {
        return $this->twig->render('EtuModuleBugsBundle:Notification:newComment.html.twig', [
            'notif' => $notification,
        ]);
    }

    /**
     * @return string
     */
    public function renderMobile(Notification $notification)
    {
        if (1 == $notification->countEntities()) {
            return ['title' => 'Réponse à votre bug : '.$notification->getFirstEntity()->getIssue()->getTitle(), 'message' => $notification->getFirstEntity()->getUser()->getFullName().'a répondu à votre signalement.'];
        } elseif (2 == $notification->countEntities()) {
            return ['title' => 'Réponse à votre bug : '.$notification->getFirstEntity()->getIssue()->getTitle(), 'message' => $notification->getFirstEntity()->getUser()->getFullName().' et '.$notification->getEntities()[1]->getUser()->getFullName().' ont répondu à votre signalement.'];
        } elseif (3 == $notification->countEntities()) {
            return ['title' => 'Réponse à votre bug : '.$notification->getFirstEntity()->getIssue()->getTitle(), 'message' => $notification->getFirstEntity()->getUser()->getFullName().', '.$notification->getEntities()[1]->getUser()->getFullName().' et 1 autre ont répondu à votre signalement.'];
        }

        return ['title' => 'Réponse à votre bug : '.$notification->getFirstEntity()->getIssue()->getTitle(), 'message' => $notification->getFirstEntity()->getUser()->getFullName().', '.$notification->getEntities()[1]->getUser()->getFullName().' et '.($notification->countEntities() - 2).' autres ont répondu à votre signalement.'];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using libXNADeveloperConsole;
using Navier_Boats.Game.Entities;
using Navier_Boats.Engine.Entities;
using Navier_Boats.Engine.Level;
using Navier_Boats.Engine.Graphics;

namespace Navier_Boats.Engine.Graphics
{
    class FontManager
    {
        private static FontManager _instance;

        public static FontManager GetInstance()
        {
            if (_instance == null)
            {
                _instance = new FontManager();
            }
            return _instance;
        }

        private Dictionary<string, SpriteFont> loadedFonts;

        public SpriteFont this[string index]
        {
            get
            {
                if (loadedFonts.ContainsKey(index))
                {
                    return loadedFonts[index];
                }
                return null;
            }
            set { loadedFonts[index] = value; }
        }

        private FontManager()
        {
            loadedFonts = new Dictionary<string, SpriteFont>();
        }

        public void LoadFont(SpriteFont spriteFont, string fontName)
        {
            loadedFonts.Add(fontName, spriteFont);
        }
    }
}


text:
$("#add_new_image").click(function() {
	var num = $(".image_upload").size();
	var new_input = $(".image_upload").last().clone().attr("class", "image_upload");
	new_input.children("input").attr("name", "employer[images_attributes][" + num + "][file]")
														 .attr("id", "employer_images_attributes_" + num + "_file");
	$("#images_upload").append(new_input);
});


text:
package org.apache.spark.deploy.yarn.security

import java.util.concurrent.{Executors, TimeUnit}

import scala.util.control.NonFatal

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.security.{Credentials, UserGroupInformation}

import org.apache.spark.SparkConf
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.internal.Logging
import org.apache.spark.util.{ThreadUtils, Utils}

private[spark] class CredentialUpdater(
    sparkConf: SparkConf,
    hadoopConf: Configuration,
    credentialManager: YARNHadoopDelegationTokenManager) extends Logging {

  @volatile private var lastCredentialsFileSuffix = 0

  private val credentialsFile = sparkConf.get(CREDENTIALS_FILE_PATH)
  private val freshHadoopConf =
    SparkHadoopUtil.get.getConfBypassingFSCache(
      hadoopConf, new Path(credentialsFile).toUri.getScheme)

  private val credentialUpdater =
    Executors.newSingleThreadScheduledExecutor(
      ThreadUtils.namedThreadFactory("Credential Refresh Thread"))

  // This thread wakes up and picks up new credentials from HDFS, if any.
  private val credentialUpdaterRunnable =
    new Runnable {
      override def run(): Unit = Utils.logUncaughtExceptions(updateCredentialsIfRequired())
    }

  /** Start the credential updater task */
  def start(): Unit = {
    val startTime = sparkConf.get(CREDENTIALS_UPDATE_TIME)
    val remainingTime = startTime - System.currentTimeMillis()
    if (remainingTime <= 0) {
      credentialUpdater.schedule(credentialUpdaterRunnable, 1, TimeUnit.MINUTES)
    } else {
      logInfo(s"Scheduling credentials refresh from HDFS in $remainingTime ms.")
      credentialUpdater.schedule(credentialUpdaterRunnable, remainingTime, TimeUnit.MILLISECONDS)
    }
  }

  private def updateCredentialsIfRequired(): Unit = {
    val timeToNextUpdate = try {
      val credentialsFilePath = new Path(credentialsFile)
      val remoteFs = FileSystem.get(freshHadoopConf)
      SparkHadoopUtil.get.listFilesSorted(
        remoteFs, credentialsFilePath.getParent,
        credentialsFilePath.getName, SparkHadoopUtil.SPARK_YARN_CREDS_TEMP_EXTENSION)
        .lastOption.map { credentialsStatus =>
          val suffix = SparkHadoopUtil.get.getSuffixForCredentialsPath(credentialsStatus.getPath)
          if (suffix > lastCredentialsFileSuffix) {
            logInfo("Reading new credentials from " + credentialsStatus.getPath)
            val newCredentials = getCredentialsFromHDFSFile(remoteFs, credentialsStatus.getPath)
            lastCredentialsFileSuffix = suffix
            UserGroupInformation.getCurrentUser.addCredentials(newCredentials)
            logInfo("Credentials updated from credentials file.")

            val remainingTime = (getTimeOfNextUpdateFromFileName(credentialsStatus.getPath)
              - System.currentTimeMillis())
            if (remainingTime <= 0) TimeUnit.MINUTES.toMillis(1) else remainingTime
          } else {
            // If current credential file is older than expected, sleep 1 hour and check again.
            TimeUnit.HOURS.toMillis(1)
          }
      }.getOrElse {
        // Wait for 1 minute to check again if there's no credential file currently
        TimeUnit.MINUTES.toMillis(1)
      }
    } catch {
      // Since the file may get deleted while we are reading it, catch the Exception and come
      // back in an hour to try again
      case NonFatal(e) =>
        logWarning("Error while trying to update credentials, will try again in 1 hour", e)
        TimeUnit.HOURS.toMillis(1)
    }

    logInfo(s"Scheduling credentials refresh from HDFS in $timeToNextUpdate ms.")
    credentialUpdater.schedule(
      credentialUpdaterRunnable, timeToNextUpdate, TimeUnit.MILLISECONDS)
  }

  private def getCredentialsFromHDFSFile(remoteFs: FileSystem, tokenPath: Path): Credentials = {
    val stream = remoteFs.open(tokenPath)
    try {
      val newCredentials = new Credentials()
      newCredentials.readTokenStorageStream(stream)
      newCredentials
    } finally {
      stream.close()
    }
  }

  private def getTimeOfNextUpdateFromFileName(credentialsPath: Path): Long = {
    val name = credentialsPath.getName
    val index = name.lastIndexOf(SparkHadoopUtil.SPARK_YARN_CREDS_COUNTER_DELIM)
    val slice = name.substring(0, index)
    val last2index = slice.lastIndexOf(SparkHadoopUtil.SPARK_YARN_CREDS_COUNTER_DELIM)
    name.substring(last2index + 1, index).toLong
  }

  def stop(): Unit = {
    credentialUpdater.shutdown()
  }

}


text:
namespace base {
class UnguessableToken;
}

namespace gfx {
class Size;
}

namespace gpu {
class GpuChannelHost;
}

struct GpuStreamTextureMsg_MatrixChanged_Params;

namespace content {

// Class for handling all the IPC messages between the GPU process and
// StreamTextureProxy.
class StreamTextureHost : public IPC::Listener {
 public:
  explicit StreamTextureHost(scoped_refptr<gpu::GpuChannelHost> channel,
                             int32_t route_id);
  ~StreamTextureHost() override;

  // Listener class that is listening to the stream texture updates. It is
  // implemented by StreamTextureProxyImpl.
  class Listener {
   public:
    virtual void OnFrameAvailable() = 0;
    virtual ~Listener() {}
  };

  bool BindToCurrentThread(Listener* listener);

  // IPC::Channel::Listener implementation:
  bool OnMessageReceived(const IPC::Message& message) override;
  void OnChannelError() override;

  void EstablishPeer(int player_id, int frame_id);
  void SetStreamTextureSize(const gfx::Size& size);
  void ForwardStreamTextureForSurfaceRequest(
      const base::UnguessableToken& request_token);

 private:
  // Message handlers:
  void OnFrameAvailable();

  int32_t route_id_;
  Listener* listener_;
  scoped_refptr<gpu::GpuChannelHost> channel_;
  base::WeakPtrFactory<StreamTextureHost> weak_ptr_factory_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(StreamTextureHost);
};

}  // namespace content

#endif  // CONTENT_RENDERER_GPU_STREAM_TEXTURE_HOST_ANDROID_H_


text:
package org.wso2.carbon.identity.user.profile.mgt;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.core.AbstractAdmin;
import org.wso2.carbon.identity.base.IdentityConstants;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.user.api.Claim;
import org.wso2.carbon.user.api.ClaimMapping;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.claim.ClaimManager;
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
import org.wso2.carbon.user.core.profile.ProfileConfiguration;
import org.wso2.carbon.user.core.profile.ProfileConfigurationManager;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserProfileAdmin extends AbstractAdmin {

    private static final Log log = LogFactory.getLog(UserProfileAdmin.class);
    private static UserProfileAdmin userProfileAdmin = new UserProfileAdmin();
    private String authorizationFailureMessage = "You are not authorized to perform this action.";

    public static UserProfileAdmin getInstance() {
        return userProfileAdmin;
    }

    public boolean isReadOnlyUserStore() throws UserProfileException {
        try {
            UserRealm realm = getUserRealm();
            if ("true".equals(realm.getRealmConfiguration().getUserStoreProperty(
                    UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY))) {
                return true;
            }
            return false;
        } catch (UserStoreException e) {
            log.error(e.getMessage(), e);
            throw new UserProfileException(e.getMessage(), e);
        }
    }

    public void setUserProfile(String username, UserProfileDTO profile) throws UserProfileException {
        UserRealm realm = null;
        try {

            if (!this.isAuthorized(username)) {
                throw new UserProfileException(authorizationFailureMessage);
            }

            int indexOne;
            indexOne = username.indexOf("/");

            if (indexOne < 0) {
                /*if domain is not provided, this can be the scenario where user from a secondary user store
                logs in without domain name and tries to view his own profile*/
                MessageContext messageContext = MessageContext.getCurrentMessageContext();
                HttpServletRequest request = (HttpServletRequest) messageContext
                        .getProperty("transport.http.servletRequest");
                String domainName = (String) request.getSession().getAttribute("logged_in_domain");

                if (domainName != null) {
                    username = domainName + "/" + username;
                }
            }

            realm = getUserRealm();

            UserFieldDTO[] udatas = profile.getFieldValues();
            Map<String, String> map = new HashMap<String, String>();
            for (UserFieldDTO data : udatas) {
                String claimURI = data.getClaimUri();
                String value = data.getFieldValue();
                if (!data.isReadOnly()) {
                    // Quick fix for not to remove OTP checkbox when false
                    if (value == "" && "http://wso2.org/claims/identity/otp".equals(claimURI)) {
                        value = "false";
                    }
                    map.put(claimURI, value);
                }
            }

            if (profile.getProfileConifuration() != null) {
                map.put(UserCoreConstants.PROFILE_CONFIGURATION, profile.getProfileConifuration());
            } else {
                map.put(UserCoreConstants.PROFILE_CONFIGURATION,
                        UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
            }

            UserStoreManager admin = realm.getUserStoreManager();

            // User store manager expects tenant aware username
            admin.setUserClaimValues(MultitenantUtils.getTenantAwareUsername(username),
                    map,
                    profile.getProfileName());

        } catch (UserStoreException e) {
            // Not logging. Already logged.
            throw new UserProfileException(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new UserProfileException(e.getMessage(), e);
        }
    }

    public void deleteUserProfile(String username, String profileName) throws UserProfileException {
        UserRealm realm = null;
        try {
            if (!this.isAuthorized(username)) {
                throw new UserProfileException(authorizationFailureMessage);
            }

            if (UserCoreConstants.DEFAULT_PROFILE.equals(profileName)) {
                throw new UserProfileException("Cannot delete default profile");
            }
            realm = getUserRealm();

            ClaimManager claimManager = realm.getClaimManager();
            String[] claims = claimManager.getAllClaimUris();

            // User store manager expects tenant aware username
            username = MultitenantUtils.getTenantAwareUsername(username);
            UserStoreManager admin = realm.getUserStoreManager();
            admin.deleteUserClaimValues(username, claims, profileName);
            admin.deleteUserClaimValue(username, UserCoreConstants.PROFILE_CONFIGURATION,
                    profileName);
        } catch (UserStoreException e) {
            // Not logging. Already logged.
            throw new UserProfileException(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new UserProfileException(e.getMessage(), e);
        }
    }

    public UserProfileDTO[] getUserProfiles(String username)
            throws UserProfileException {
        UserProfileDTO[] profiles;
        String[] availableProfileConfigurations = new String[0];
        String profileConfig = null;
        try {
            if (!this.isAuthorized(username)) {
                throw new UserProfileException(authorizationFailureMessage);
            }

            UserRealm realm = getUserRealm();

            UserStoreManager userStoreManager = realm.getUserStoreManager();

            boolean isReadOnly = userStoreManager.isReadOnly();

            int index;
            index = username.indexOf("/");

            UserStoreManager secUserStoreManager = null;

            // Check whether we have a secondary UserStoreManager setup.
            if (index > 0) {
                // Using the short-circuit. User name comes with the domain name.
                String domain = username.substring(0, index);

                if (userStoreManager instanceof AbstractUserStoreManager) {
                    secUserStoreManager = ((AbstractUserStoreManager) userStoreManager)
                            .getSecondaryUserStoreManager(domain);
                    if (secUserStoreManager != null) {
                        isReadOnly = secUserStoreManager.isReadOnly();
                    }
                }
            }

            ProfileConfigurationManager profileAdmin = realm
                    .getProfileConfigurationManager();
            if (profileAdmin != null) {
                availableProfileConfigurations = getAvailableProfileConfiguration(profileAdmin);
            }

            // User store manager expects tenant aware username
            username = MultitenantUtils.getTenantAwareUsername(username);
            String[] profileNames = null;

            if (secUserStoreManager != null) {
                profileNames = secUserStoreManager.getProfileNames(username);
            } else {
                profileNames = userStoreManager.getProfileNames(username);
            }

            profiles = new UserProfileDTO[profileNames.length];
            Claim[] claims = getAllSupportedClaims(realm, UserCoreConstants.DEFAULT_CARBON_DIALECT);
            String[] claimUris = new String[claims.length + 1];
            for (int i = 0; i < claims.length; i++) {
                claimUris[i] = claims[i].getClaimUri();
            }

            claimUris[claims.length] = UserCoreConstants.PROFILE_CONFIGURATION;

            for (int i = 0; i < profileNames.length; i++) {
                String profile = profileNames[i];
                Map<String, String> valueMap =
                        userStoreManager.getUserClaimValues(username, claimUris, profile);
                List<UserFieldDTO> userFields = new ArrayList<UserFieldDTO>();
                for (int j = 0; j < claims.length; j++) {
                    UserFieldDTO data = new UserFieldDTO();
                    Claim claim = claims[j];
                    String claimUri = claim.getClaimUri();
                    if (!UserCoreConstants.PROFILE_CONFIGURATION.equals(claimUri)) {
                        data.setClaimUri(claimUri);
                        data.setFieldValue(valueMap.get(claimUri));
                        data.setDisplayName(claim.getDisplayTag());
                        data.setRegEx(claim.getRegEx());
                        data.setRequired(claim.isRequired());
                        data.setDisplayOrder(claim.getDisplayOrder());
                        data.setCheckedAttribute(claim.isCheckedAttribute());
                        data.setReadOnly(claim.isReadOnly());
                        userFields.add(data);
                    }
                }

                UserProfileDTO temp = new UserProfileDTO();
                temp.setProfileName(profile);
                temp.setFieldValues(userFields.toArray(new UserFieldDTO[userFields.size()]));
                temp.setProfileConfigurations(availableProfileConfigurations);

                profileConfig = valueMap.get(UserCoreConstants.PROFILE_CONFIGURATION);
                if (profileConfig == null) {
                    profileConfig = UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION;
                }

                if (isReadOnly) {
                    profileConfig = "readonly";
                }

                temp.setProfileConifuration(profileConfig);
                profiles[i] = temp;
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            // Not logging. Already logged.
            throw new UserProfileException(e.getMessage(), e);
        }
        return profiles;

    }

    public UserProfileDTO getProfileFieldsForInternalStore() throws UserProfileException {
        UserFieldDTO[] datas;
        UserProfileDTO profile = new UserProfileDTO();
        String[] availableProfileConfigurations = new String[0];
        try {
            UserRealm realm = getUserRealm();
            Claim[] claims = getClaimsToEnterData(realm);

            ProfileConfigurationManager profileAdmin = realm
                    .getProfileConfigurationManager();
            if (profileAdmin != null) {
                availableProfileConfigurations = getAvailableProfileConfiguration(profileAdmin);
            }

            String[] claimUris = new String[claims.length];
            for (int i = 0; i < claims.length; i++) {
                claimUris[i] = claims[i].getClaimUri();
            }
            datas = new UserFieldDTO[claims.length];
            for (int j = 0; j < claims.length; j++) {
                UserFieldDTO data = new UserFieldDTO();
                Claim claim = claims[j];
                String claimUri = claim.getClaimUri();
                data.setClaimUri(claimUri);
                data.setDisplayName(claim.getDisplayTag());
                data.setRegEx(claim.getRegEx());
                data.setRequired(claim.isRequired());
                data.setDisplayOrder(claim.getDisplayOrder());
                data.setRegEx(claim.getRegEx());
                data.setCheckedAttribute(claim.isCheckedAttribute());
                data.setReadOnly(claim.isReadOnly());
                datas[j] = data;
            }

        } catch (Exception e) {
            // Not logging. Already logged.
            throw new UserProfileException(e.getMessage(), e);
        }

        profile.setFieldValues(datas);
        profile.setProfileConfigurations(availableProfileConfigurations);

        return profile;
    }

    public UserProfileDTO getUserProfile(String username, String profileName)
            throws UserProfileException {
        UserProfileDTO profile = new UserProfileDTO();
        String[] availableProfileConfigurations = new String[0];
        String profileConfig = null;

        try {

            if (username == null || profileName == null) {
                throw new UserProfileException("Invalid input parameters");
            }

            if (!this.isAuthorized(username)) {
                throw new UserProfileException(authorizationFailureMessage);
            }

            UserRealm realm = getUserRealm();

            UserStoreManager userStoreManager = realm.getUserStoreManager();

            boolean isReadOnly = userStoreManager.isReadOnly();

            int indexOne;
            indexOne = username.indexOf("/");

            if (indexOne < 0) {
                /*if domain is not provided, this can be the scenario where user from a secondary user store
                logs in without domain name and tries to view his own profile*/
                MessageContext messageContext = MessageContext.getCurrentMessageContext();
                HttpServletRequest request = (HttpServletRequest) messageContext
                        .getProperty("transport.http.servletRequest");
                String domainName = (String) request.getSession().getAttribute("logged_in_domain");

                if (domainName != null) {
                    username = domainName + "/" + username;
                }
            }
            int index;
            index = username.indexOf("/");

            UserStoreManager secUserStoreManager = null;

            // Check whether we have a secondary UserStoreManager setup.
            if (index > 0) {
                // Using the short-circuit. User name comes with the domain name.
                String domain = username.substring(0, index);

                if (userStoreManager instanceof AbstractUserStoreManager) {
                    secUserStoreManager = ((AbstractUserStoreManager) userStoreManager)
                            .getSecondaryUserStoreManager(domain);
                    if (secUserStoreManager != null) {
                        isReadOnly = secUserStoreManager.isReadOnly();
                    }
                }
            }

            ProfileConfigurationManager profileAdmin = realm
                    .getProfileConfigurationManager();

            // User store manager expects tenant aware username
            username = MultitenantUtils.getTenantAwareUsername(username);
            String[] profileNames = null;

            if (secUserStoreManager != null) {
                profileNames = secUserStoreManager.getProfileNames(username);
            } else {
                profileNames = userStoreManager.getProfileNames(username);
            }

            boolean found = false;

            if (profileNames != null && profileNames.length > 0) {
                for (int i = 0; i < profileNames.length; i++) {
                    if (profileName.equals(profileNames[i])) {
                        found = true;
                        break;
                    }
                }
            }

            if (!found) {
                return null;
            }

            if (profileAdmin != null) {
                availableProfileConfigurations = getAvailableProfileConfiguration(profileAdmin);
            }

            Claim[] claims = getClaimsToEnterData(realm);
            String[] claimUris = new String[claims.length + 1];
            for (int i = 0; i < claims.length; i++) {
                claimUris[i] = claims[i].getClaimUri();
            }

            claimUris[claims.length] = UserCoreConstants.PROFILE_CONFIGURATION;

            Map<String, String> valueMap =
                    userStoreManager
                            .getUserClaimValues(username, claimUris, profileName);
            List<UserFieldDTO> userFields = new ArrayList<UserFieldDTO>();

            for (int j = 0; j < claims.length; j++) {
                UserFieldDTO data = new UserFieldDTO();
                Claim claim = claims[j];
                String claimUri = claim.getClaimUri();
                if (!UserCoreConstants.PROFILE_CONFIGURATION.equals(claimUri)) {
                    data.setClaimUri(claimUri);
                    data.setFieldValue(valueMap.get(claimUri));
                    data.setDisplayName(claim.getDisplayTag());
                    data.setRegEx(claim.getRegEx());
                    data.setRequired(claim.isRequired());
                    data.setDisplayOrder(claim.getDisplayOrder());
                    data.setReadOnly(claim.isReadOnly());
                    data.setCheckedAttribute(claim.isCheckedAttribute());
                    userFields.add(data);
                }
            }

            profile.setProfileName(profileName);
            profile.setProfileConfigurations(availableProfileConfigurations);

            profileConfig = valueMap.get(UserCoreConstants.PROFILE_CONFIGURATION);
            if (profileConfig == null) {
                profileConfig = UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION;
            }

            if (isReadOnly) {
                profileConfig = "readonly";
            }

            profile.setProfileConifuration(profileConfig);
            profile.setFieldValues(userFields.toArray(new UserFieldDTO[userFields.size()]));

        } catch (Exception e) {
            // Not logging. Already logged.
            throw new UserProfileException(e.getMessage(), e);
        }
        return profile;
    }

    public boolean isAddProfileEnabled() throws UserProfileException {
        UserRealm realm = getUserRealm();
        UserStoreManager userStoreManager = null;
        try {
            userStoreManager = realm.getUserStoreManager();
        } catch (UserStoreException e) {
            String errorMessage = "Error in obtaining UserStoreManager.";
            log.error(errorMessage, e);
            throw new UserProfileException(errorMessage, e);
        }
        return userStoreManager.isMultipleProfilesAllowed();
    }

    public boolean isAddProfileEnabledForDomain(String domain) throws UserProfileException {

        org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
        org.wso2.carbon.user.core.UserRealm realm = getUserRealm();
        boolean isAddProfileEnabled = false;

        try {
            if (StringUtils.isBlank(domain) || StringUtils.equals(domain, UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME)) {
                userStoreManager = realm.getUserStoreManager();
            } else {
                userStoreManager = realm.getUserStoreManager().getSecondaryUserStoreManager(domain);
            }

        } catch (UserStoreException e) {
            String errorMessage = "Error in obtaining SecondaryUserStoreManager.";
            log.error(errorMessage, e);
            throw new UserProfileException(errorMessage, e);
        }

        if (userStoreManager != null) {
            isAddProfileEnabled = userStoreManager.isMultipleProfilesAllowed();
        }

        return isAddProfileEnabled;
    }

    private Claim[] getClaimsToEnterData(UserRealm realm)
            throws UserStoreException {
        try {
            return getAllSupportedClaims(realm, UserCoreConstants.DEFAULT_CARBON_DIALECT);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new UserStoreException(e);
        }
    }

    private boolean isAuthorized(String targetUser) throws UserStoreException, CarbonException {
        boolean isAuthrized = false;
        MessageContext msgContext = MessageContext.getCurrentMessageContext();
        HttpServletRequest request = (HttpServletRequest) msgContext
                .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        HttpSession httpSession = request.getSession(false);
        if (httpSession != null) {
            String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
            isAuthrized = UserProfileUtil.isUserAuthorizedToConfigureProfile(getUserRealm(), userName, targetUser);
        }
        return isAuthrized;
    }

    /**
     * @return
     * @throws UserStoreException
     */
    private Claim[] getAllSupportedClaims(UserRealm realm, String dialectUri)
            throws org.wso2.carbon.user.api.UserStoreException {
        ClaimMapping[] claims = null;
        List<Claim> reqClaims = null;

        claims = realm.getClaimManager().getAllSupportClaimMappingsByDefault();
        reqClaims = new ArrayList<Claim>();
        for (int i = 0; i < claims.length; i++) {
            if (dialectUri.equals(claims[i].getClaim().getDialectURI()) && (claims[i] != null && claims[i].getClaim().getDisplayTag() != null
                    && !claims[i].getClaim().getClaimUri().equals(IdentityConstants.CLAIM_PPID))) {

                reqClaims.add((Claim) claims[i].getClaim());
            }
        }

        return reqClaims.toArray(new Claim[reqClaims.size()]);
    }

    private String[] getAvailableProfileConfiguration(
            ProfileConfigurationManager profileAdmin) throws UserStoreException {
        ProfileConfiguration[] configurations;
        String[] profileNames = new String[0];
        try {
            configurations = (ProfileConfiguration[]) profileAdmin.getAllProfiles();
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new UserStoreException(e);
        }

        if (configurations != null) {
            profileNames = new String[configurations.length];
            for (int i = 0; i < configurations.length; i++) {
                profileNames[i] = configurations[i].getProfileName();
            }
        }

        return profileNames;
    }

    public void associateID(String idpID, String associatedID) throws UserProfileException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        String sql = null;
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(CarbonContext.getThreadLocalCarbonContext()
                                                                          .getUsername());
        String domainName = getDomainName(tenantAwareUsername);
        tenantAwareUsername = getUsernameWithoutDomain(tenantAwareUsername);

        try {
            sql = "INSERT INTO IDN_ASSOCIATED_ID (TENANT_ID, IDP_ID, IDP_USER_ID, DOMAIN_NAME, USER_NAME) " +
                  "VALUES (? , (SELECT ID FROM IDP WHERE NAME = ? AND TENANT_ID = ? ), ? , ?, ?)";

            prepStmt = connection.prepareStatement(sql);
            prepStmt.setInt(1, tenantID);
            prepStmt.setString(2, idpID);
            prepStmt.setInt(3, tenantID);
            prepStmt.setString(4, associatedID);
            prepStmt.setString(5, domainName);
            prepStmt.setString(6, tenantAwareUsername);

            prepStmt.execute();
            connection.commit();
        } catch (SQLException e) {
            log.error("Error occurred while persisting the federated user ID", e);
            throw new UserProfileException("Error occurred while persisting the federated user ID", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
        }

    }

    public String getNameAssociatedWith(String idpID, String associatedID) throws UserProfileException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        ResultSet resultSet;
        String sql = null;
        String username = "";
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();

        try {
            sql = "SELECT DOMAIN_NAME, USER_NAME FROM IDN_ASSOCIATED_ID WHERE TENANT_ID = ? AND IDP_ID = (SELECT ID " +
                  "FROM IDP WHERE NAME = ? AND TENANT_ID = ?) AND IDP_USER_ID = ?";

            prepStmt = connection.prepareStatement(sql);
            prepStmt.setInt(1, tenantID);
            prepStmt.setString(2, idpID);
            prepStmt.setInt(3, tenantID);
            prepStmt.setString(4, associatedID);

            resultSet = prepStmt.executeQuery();
            connection.commit();

            if (resultSet.next()) {
                String domainName = resultSet.getString(1);
                username = resultSet.getString(2);
                if(!"PRIMARY".equals(domainName)) {
                    username = domainName + CarbonConstants.DOMAIN_SEPARATOR + username;
                }
                return username;
            }

        } catch (SQLException e) {
            log.error("Error occurred while getting associated name", e);
            throw new UserProfileException("Error occurred while getting associated name", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
        }
        return null;
    }

    public AssociatedAccountDTO[] getAssociatedIDs() throws UserProfileException {
        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        ResultSet resultSet;
        String sql = null;
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(CarbonContext.getThreadLocalCarbonContext()
                                                                          .getUsername());
        String domainName = getDomainName(tenantAwareUsername);
        tenantAwareUsername = getUsernameWithoutDomain(tenantAwareUsername);
        List<AssociatedAccountDTO> associatedIDs = new ArrayList<AssociatedAccountDTO>();
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();

        try {
            sql = "SELECT IDP.NAME, IDP_USER_ID FROM IDN_ASSOCIATED_ID JOIN IDP ON IDN_ASSOCIATED_ID.IDP_ID = IDP.ID " +
                  "WHERE IDN_ASSOCIATED_ID.TENANT_ID = ? AND USER_NAME = ? AND DOMAIN_NAME = ?";
            prepStmt = connection.prepareStatement(sql);
            prepStmt.setInt(1, tenantID);
            prepStmt.setString(2, tenantAwareUsername);
            prepStmt.setString(3, domainName);

            resultSet = prepStmt.executeQuery();
            connection.commit();
            while (resultSet.next()) {
                associatedIDs.add(new AssociatedAccountDTO(resultSet.getString(1), resultSet.getString(2)));
            }
            if(!associatedIDs.isEmpty()) {
                return associatedIDs.toArray(new AssociatedAccountDTO[associatedIDs.size()]);
            } else {
                return new AssociatedAccountDTO[0];
            }
        } catch (SQLException e) {
            log.error("Error occurred while getting associated IDs", e);
            throw new UserProfileException("Error occurred while getting associated IDs", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
        }
    }

    public void removeAssociateID(String idpID, String associatedID) throws UserProfileException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        String sql = null;
        int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(CarbonContext.getThreadLocalCarbonContext()
                                                                          .getUsername());
        String domainName = getDomainName(tenantAwareUsername);
        tenantAwareUsername = getUsernameWithoutDomain(tenantAwareUsername);

        try {

            sql = "DELETE FROM IDN_ASSOCIATED_ID WHERE TENANT_ID = ? AND IDP_ID = (SELECT ID FROM IDP WHERE NAME = ? " +
                  "AND TENANT_ID = ? ) AND IDP_USER_ID = ? AND USER_NAME = ? AND DOMAIN_NAME = ?";
            prepStmt = connection.prepareStatement(sql);
            prepStmt.setInt(1, tenantID);
            prepStmt.setString(2, idpID);
            prepStmt.setInt(3, tenantID);
            prepStmt.setString(4, associatedID);
            prepStmt.setString(5, tenantAwareUsername);
            prepStmt.setString(6, domainName);

            prepStmt.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            log.error("Error occurred while removing associated ID", e);
            throw new UserProfileException("Error occurred while removing associated ID", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
        }

    }

    private static String getDomainName(String username) {
        int index = username.indexOf(CarbonConstants.DOMAIN_SEPARATOR);
        if (index < 0) {
            return "PRIMARY";
        }
        return username.substring(0, index);
    }

    private static String getUsernameWithoutDomain(String username) {
        int index = username.indexOf(CarbonConstants.DOMAIN_SEPARATOR);
        if (index < 0) {
            return username;
        }
        return username.substring(index + 1, username.length());
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
module CodeGen where

import Fmt
import Types
import Prelude hiding (take, drop, head, tail)
import Data.Text hiding (reverse, zip, filter)
import Data.Monoid
import System.Environment
import Language.Haskell.Exts as HS hiding (prettyPrint)

-- all the magic
mkData :: DataOrNew -> Context -> Name -> [TyVarBind] -> [QualConDecl] -> [Deriving] -> Swift
mkData _ (x:xs) _ _ _ _         = error "constraints on data types not supported"
mkData _ _ (Symbol _) _ _ _     = error "symbols as names of data types not supported"
mkData _dn _ (Ident n) bs qs dr = Swift n' dr' bs' qs'
  where
    n' = pack n
    bs' = fmap mktyarg bs
    qs' = fmap mkcon qs
    dr' = fmap (dequal . fst) dr -- discard type arguments, multi param type classes not supported

    mktyarg (KindedVar _ _)          = error "kind annotations not supported"
    mktyarg (UnkindedVar (Ident n))  = toTitle' n
    mktyarg (UnkindedVar (Symbol _)) = error "symbols not supported in type arguments"

    -- TODO: un-support forall bindings
    mkcon (QualConDecl _ tvs ctx (ConDecl n ts)) = (unn n, fmap (\(k, t) ->
              (Left ("a" <> pack (show k)), typ (unb t))) (zip [1..] ts))
    mkcon (QualConDecl _ tvs ctx (RecDecl n ts)) = (unn n, fmap (\(ns, t) ->
              (Right (nameRec ns), typ (unb t))) ts)
    mkcon (QualConDecl _ tvs ctx (InfixConDecl _ _ _)) = error "infix con decls not supported"

    -- drop 1 _ from the start of records
    nameRec [(Ident ('_':n))] = pack n
    nameRec [(Ident n)] = pack n
    nameRec [(Symbol n)] = error "symbolic record names not supported"
    nameRec _ = error "multiple names on single record not supported" -- could be, does anyone use this?

    unb (UnBangedTy t) = t
    unb _ = error "bangs on types not supported"

typ :: Type -> Text
typ (TyTuple _ ts)                             = "(" <> intercalate ", " (fmap typ ts) <> ")"
typ (TyApp (TyCon (UnQual (Ident "Maybe"))) y) = typ y <> "?"
typ (TyApp x y)                                = let
  (h:xs)                                       = reverse (y:foldup x)
  in (typ h) <> "<" <> intercalate ", " (fmap typ xs) <> ">"
typ (TyVar (Ident n))                          = toTitle' n
typ (TyVar (Symbol _))                         = error "symbolic tyvars not supported"
typ (TyCon q)                                  = dequal q
typ (TyParen t)                                = typ t
typ (TyFun x y)                                = error $ "tyfun not supported: " <> (show (x, y))
-- not in language
typ (TyForall _ _ _)                           = error "foralls not supported"
typ (TyList _)                                 = error "list syntax not supported"
typ (TyInfix _ _ _)                            = error "infix types not supported"
typ (TyKind _ _)                               = error "type kinds not supported"
typ (TyPromoted _)                             = error "promoted types not supported"

foldup (TyApp l r) = (r:foldup l)
foldup x = [x]

-- meh
transform :: Module -> Text
transform (Module _ _ (x:xs) _ _ _ _) = error "'module pragma' is unsupported"
transform (Module _ _ _ _ _ (x:xs) _) = error "'import' is unsupported"
transform (Module _ _ _ _ _ [] xs)    =
     "import swiftz\nimport swiftz_core\n\n"
  <> (intercalate "\n\n" $ fmap (prettyPrint . produce) xs)

produce :: Decl -> Swift
produce (TypeDecl _ n bs t)              = mkType n bs t
produce (TypeFamDecl _ _ _ _)            = error "type families not supported"
produce (DataDecl _ dn ct n bs qs dr)    = mkData dn ct n bs qs dr
produce (GDataDecl _ dn ct n bs k gd dr) = mkGadt dn ct n bs k gd dr
produce (DataFamDecl _ _ _ _ _)          = error "data families not supported"
produce (TypeInsDecl _ _ _)              = error "data instances not supported"
produce (GDataInsDecl _ _ _ _ _ _)       = error "data instances (gadt) not supported"
produce (ClassDecl _ ct n bs fd cd)      = error "type classes not supported"
produce (InstDecl _ ct n ts ds)          = error "type class instances not supported"
produce (DerivDecl _ _ _ _)              = error "standalone deriving not supported"
produce (InfixDecl _ _ _ _)              = error "infix decls not supported"
produce (DefaultDecl _ _)                = error "default decl not supported"
produce (SpliceDecl _ _)                 = error "TH splice not supported"
produce (TypeSig _ _ _)                  = error "type signatures not supported"
produce (FunBind _)                      = error "no fun allowed"
produce (PatBind _ _ _ _ _)              = error "pattern binding not supported"
produce (ForImp _ _ _ _ _ _)             = error "foreign imports not supported"
produce (ForExp _ _ _ _ _)               = error "foreign exports not supported"
produce (RulePragmaDecl _ _)             = error "rule pragmas not supported"
produce (DeprPragmaDecl _ _)             = error "deprecated pragma not supported"
produce (WarnPragmaDecl _ _)             = error "warning pragma not supported"
produce (InlineSig _ _ _ _)              = error "inline pragma not supported"
produce (InlineConlikeSig _ _ _)         = error "inline conlike pragma not supported"
produce (SpecSig _ _ _ _)                = error "specialise pragma not supported"
produce (SpecInlineSig _ _ _ _ _)        = error "specialise inline pragma not supported"
produce (InstSig _ _ _ _)                = error "specialise instance pragma not supported"
produce (AnnPragma _ _)                  = error "ann pragma not supported"

mkType :: Name -> [TyVarBind] -> Type -> Swift
mkType n bs t = error "type aliases not supported"

mkGadt :: DataOrNew -> Context -> Name -> [TyVarBind] -> (Maybe Kind) -> [GadtDecl] -> [Deriving] -> Swift
mkGadt = error "gadts not supported"

dequal :: QName -> Text
dequal (UnQual (Ident s)) = pack s
dequal _ = error "names must be unqualified"

unn (Ident s) = pack s
unn (Symbol _) = error "symbolic names not supported"

toTitle' n = toTitle (take 1 (pack n)) <> drop 1 (pack n)


text:
data_dir=/hps/nobackup2/production/ensembl/anja/vep_data/
vep_cache_dir=/nfs/production/panda/ensembl/variation/data/VEP/tabixconverted/
perl  $HOME/bin/ensembl-vep/vep \
--cache_version 96 \
--vcf \
--hgvs \
--offline \
--dir_cache $vep_cache_dir \
--format vcf \
--output_file $data_dir/output/grch37/congenica_test_grch37_96.out \
--input_file $data_dir/input/grch37/congenica_test_grch37.vcf.gz \
--no_progress --force_overwrite --no_stats \
--fasta /nfs/production/panda/ensembl/variation/data/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa \
--merged \
--all_refseq \
--assembly GRCh37 \
--fork 2 \
--force_overwrite \
--sift b --polyphen b --ccds --uniprot --hgvs --symbol --numbers --domains --canonical --protein --biotype --uniprot --tsl --appris --gene_phenotype --af --af_1kg --af_esp --af_gnomad --max_af --pubmed --variant_class \


text:
require 'authlete'
require 'minitest/autorun'

class AuthorizationIssueRequestTest < Minitest::Test
  TICKET            = '<ticket>'
  SUBJECT           = '<subject>'
  AUTH_TIME         = 100
  ACR               = '<acr>'
  CLAIMS            = [ 'claim0', 'claim1' ]
  PROPERTY_KEY      = '<property0-key>'
  PROPERTY_VALUE    = '<property0-value>'
  PROPERTIES        = [ Authlete::Model::Property.new(key: PROPERTY_KEY, value: PROPERTY_VALUE) ]
  SCOPES            = [ 'scope0', 'scope1' ]
  SUB               = '<sub>'
  IDT_HEADER_PARAMS = '<idt-header-params>'

  def set_params(obj)
    obj.ticket          = TICKET
    obj.subject         = SUBJECT
    obj.auth_time       = AUTH_TIME
    obj.acr             = ACR
    obj.claims          = CLAIMS
    obj.properties      = PROPERTIES
    obj.scopes          = SCOPES
    obj.sub             = SUB
    obj.idtHeaderParams = IDT_HEADER_PARAMS
  end

  def match(obj)
    assert_equal TICKET,            obj.ticket
    assert_equal SUBJECT,           obj.subject
    assert_equal AUTH_TIME,         obj.authTime
    assert_equal ACR,               obj.acr
    assert_equal CLAIMS,            obj.claims
    assert_equal PROPERTY_KEY,      obj.properties[0].key
    assert_equal PROPERTY_VALUE,    obj.properties[0].value
    assert_equal SCOPES,            obj.scopes
    assert_equal SUB,               obj.sub
    assert_equal IDT_HEADER_PARAMS, obj.idtHeaderParams
  end

  def generate_hash
    {
      ticket:          '<ticket>',
      subject:         '<subject>',
      authTime:        100,
      acr:             '<acr>',
      claims:          [ 'claim0', 'claim1' ],
      properties:      [ { key: '<property0-key>', value: '<property0-value>', hidden: false } ],
      scopes:          [ 'scope0', 'scope1' ],
      sub:             '<sub>',
      idtHeaderParams: '<idt-header-params>'
    }
  end

  def test_setters
    actual = Authlete::Model::Request::AuthorizationIssueRequest.new
    set_params(actual)

    match(actual)
  end

  def test_to_hash
    obj = Authlete::Model::Request::AuthorizationIssueRequest.new
    set_params(obj)
    actual   = obj.to_hash
    expected = generate_hash

    assert_equal expected, actual
  end
end