text:
using System.Collections.Generic;
using Spatial4n.Core.Shapes;

namespace Lucene.Net.Spatial.Util
{
    /// <summary>
    /// Bounded Cache of Shapes associated with docIds.  Note, multiple Shapes can be
    /// associated with a given docId
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ShapeFieldCache<T> where T : Shape
    {
        private readonly IList<T>[] cache;
        public int defaultLength;

        public ShapeFieldCache(int length, int defaultLength)
        {
            cache = new IList<T>[length];
            this.defaultLength = defaultLength;
        }

        public void Add(int docid, T s)
        {
            IList<T> list = cache[docid];
            if (list == null)
            {
                list = cache[docid] = new List<T>(defaultLength);
            }
            list.Add(s);
        }

        public IList<T> GetShapes(int docid)
        {
            return cache[docid];
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
FactoryGirl.define do
  factory :comment do
    user
    board_item
    content "MyText"
  end

end


text:
package nam.model;

import java.util.Collection;
import java.util.List;

import nam.model.Module;
import nam.model.Namespace;
import nam.model.Project;
import nam.model.Service;
import nam.model.src.main.java.ElementUtilBuilder;
import nam.model.src.main.java.ModelBeanClassBuilder;
import nam.model.src.main.java.ModelFixtureClassBuilder;
import nam.model.src.main.java.ModelHelperClassBuilder;
import nam.model.src.main.java.ObjectFactoryClassBuilder;
import nam.model.src.main.java.ServiceFaultBuilder;
import nam.model.src.main.resources.model.ModelXSDBuilder;
import aries.codegen.application.AbstractModuleBuilder;
import aries.generation.engine.GenerationContext;
import aries.generation.model.ModelClass;
import aries.generation.model.ModelFile;
import aries.generation.model.ModelPackage;

public class ModelModuleBuilder extends AbstractModuleBuilder {

	// main sources area
	private ModelModuleHelper modelModuleHelper;
	private ModelBeanClassBuilder modelBeanClassBuilder;
	private ModelHelperClassBuilder modelHelperClassBuilder;
	private ObjectFactoryClassBuilder objectFactoryClassBuilder;
	private ElementUtilBuilder elementUtilBuilder;
	private ServiceFaultBuilder serviceFaultBuilder;

	//main resources
	private ModelXSDBuilder modelXSDBuilder;

	// test sources area
	private ModelFixtureClassBuilder modelFixtureClassBuilder;

	public ModelModuleBuilder(GenerationContext context) {
		// main sources area
		modelModuleHelper = new ModelModuleHelper(context);
		modelBeanClassBuilder = new ModelBeanClassBuilder(context);
		modelHelperClassBuilder = new ModelHelperClassBuilder(context);
		modelFixtureClassBuilder = new ModelFixtureClassBuilder(context);
		objectFactoryClassBuilder = new ObjectFactoryClassBuilder(context);
		elementUtilBuilder = new ElementUtilBuilder(context);
		serviceFaultBuilder = new ServiceFaultBuilder(context);

		//main resources
		modelXSDBuilder = new ModelXSDBuilder(context);

		// test sources area
		this.context = context;
	}

	public void initialize(Project project, Module module) throws Exception {
		modelModuleHelper.initialize(project, module);
		context.initialize(project, module);
	}

	/*
	 * Main classes
	 * ------------
	 */

	public Collection<ModelPackage> buildModelBeanPackages(List<Namespace> namespaces) throws Exception {
		return modelBeanClassBuilder.buildPackages(namespaces);
	}

	public ModelPackage buildModelBeanPackage(Namespace namespace) throws Exception {
		return modelBeanClassBuilder.buildPackage(namespace);
	}

	public Collection<ModelClass> buildModelHelperClasses(List<Namespace> namespaces) throws Exception {
		return modelHelperClassBuilder.buildClasses(namespaces);
	}

	public ModelClass buildModelHelperClass(Namespace namespace) throws Exception {
		return modelHelperClassBuilder.buildClass(namespace);
	}

	public Collection<ModelClass> buildObjectFactoryClasses(List<Namespace> namespaces) throws Exception {
		return objectFactoryClassBuilder.buildModelClasses(namespaces);
	}

	public Collection<ModelClass> buildElementUtilClasses(List<Namespace> namespaces) throws Exception {
		return elementUtilBuilder.buildClasses(namespaces);
	}

	public Collection<ModelClass> buildServiceFaultClasses(Service service) throws Exception {
		return serviceFaultBuilder.buildClasses(service);
	}

	/*
	 * Main resources
	 * --------------
	 */

	public Collection<ModelFile> buildModelXSDFiles(List<Namespace> namespaces) throws Exception {
		List<ModelFile> modelFiles = modelXSDBuilder.buildFiles(namespaces);
		return modelFiles;
	}

	/*
	 * Test classes
	 * ------------
	 */

	public List<ModelClass> buildModelFixtureClasses(List<Namespace> namespaces) throws Exception {
		return modelFixtureClassBuilder.buildClasses(namespaces);
	}

}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'maradji'

require 'micronaut/expectations'

World(Micronaut::Matchers)


text:
// Copyright 2010 Chris Patterson
//
// 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.
namespace Stact.Configuration.RegistryConfigurators
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using Internal;
	using Magnum.Extensions;

	public class ActorRegistryConfiguratorImpl :
		SchedulerFactoryConfiguratorImpl<ActorRegistryConfigurator>,
		ActorRegistryConfigurator
	{
		readonly IList<RegistryBuilderConfigurator> _configurators;
		Func<Fiber, Scheduler, RegistryBuilder> _builderFactory;

		public ActorRegistryConfiguratorImpl()
		{
			UseTimerScheduler();

			_builderFactory = DefaultBuilderFactory;
			_configurators = new List<RegistryBuilderConfigurator>();
		}

		public void ValidateConfiguration()
		{
			ValidateFiberFactoryConfiguration();

			_configurators.Each(x => x.ValidateConfiguration());
		}

		public void UseBuilder(Func<Fiber, Scheduler, RegistryBuilder> builderFactory)
		{
			_builderFactory = builderFactory;
		}

		public void AddConfigurator(RegistryBuilderConfigurator configurator)
		{
			_configurators.Add(configurator);
		}

		static RegistryBuilder DefaultBuilderFactory(Fiber fiber, Scheduler scheduler)
		{
			return new InMemoryRegistryBuilder(fiber, scheduler);
		}

		public ActorRegistry CreateRegistry()
		{
			ValidateConfiguration();

			FiberFactory fiberFactory = GetConfiguredFiberFactory();
			Fiber fiber = fiberFactory();

			Scheduler scheduler = GetConfiguredScheduler();

			RegistryBuilder builder = _builderFactory(fiber, scheduler);

			return _configurators
				.Aggregate(builder, (current, configurator) => configurator.Configure(current))
				.Build();
		}
	}
}


text:
using namespace naoth;
using namespace std;

void InertialSensorData::print(ostream& stream) const
{
  stream << "values (deg):" << std::endl;
  stream << "x = " << Math::toDegrees(data.x) << std::endl;
  stream << "y = " << Math::toDegrees(data.y) << std::endl;
}

void Serializer<InertialSensorData>::serialize(const InertialSensorData& representation, std::ostream& stream)
{
  naothmessages::InertialSensorData msg;

  naoth::DataConversion::toMessage(representation.data, *msg.mutable_data());

  google::protobuf::io::OstreamOutputStream buf(&stream);
  msg.SerializeToZeroCopyStream(&buf);
}

void Serializer<InertialSensorData>::deserialize(std::istream& stream, InertialSensorData& representation)
{
  naothmessages::InertialSensorData msg;
  google::protobuf::io::IstreamInputStream buf(&stream);
  msg.ParseFromZeroCopyStream(&buf);

  // allows to parse old log files
  if(msg.legacypackeddata_size() == 2) {
    representation.data.x = msg.legacypackeddata(0);
    representation.data.y = msg.legacypackeddata(1);
  }

  if(msg.has_data()) {
    naoth::DataConversion::fromMessage(*msg.mutable_data(), representation.data);
  }
}


text:
import os
from django.test import TestCase
from django.core.files import File
from events.logo import models
from django.conf import settings

class LogoTestCase(TestCase):
    def setup(self):
        f = open(os.path.join(settings.BASE_DIR, 'static','images/logo.png'), 'rb')
        sub = models.Submission()
        sub.name = 'Jon Smith'
        sub.college_name = 'SSC'
        sub.email='jon@smith.com'
        sub.logo = File(f)
        sub.tagline = 'Hello World!'
        sub.save()
        self.s = sub

    def test_str_function(self):
        self.assertEqual(self.s.__str__(), 'Jon Smith')


text:
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

blockquote, q { quotes: none; }

blockquote:before, blockquote:after,
q:before, q:after { content: ''; content: none; }

ins { background-color: #ff9; color: #000; text-decoration: none; }

mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; }

del { text-decoration: line-through; }

abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; }

table { border-collapse: collapse; border-spacing: 0; }

hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }

input, select { vertical-align: middle; }

body { font:13px/1.231 sans-serif; *font-size:small; }
select, input, textarea, button { font: 99% "Helvetica Neue", Arial, sans-serif; }

pre, code, kbd, samp { font-family: monospace, sans-serif; }

a:hover, a:active { outline: none; }

ul, ol { margin-left: 2em; }
ol { list-style-type: decimal; }
nav ul, nav li { margin: 0; list-style:none; list-style-image: none; }

small { font-size: 85%; }
strong, th { font-weight: bold; }

td { vertical-align: top; }

sup { top: -0.5em; }
sub { bottom: -0.25em; }

pre {
  white-space: pre; white-space: pre-wrap; word-wrap: break-word;
  padding: 15px;
}

textarea { overflow: auto; } /* www.sitepoint.com/blogs/2010/08/20/ie-remove-textarea-scrollbars/ */

.ie6 legend, .ie7 legend { margin-left: -7px; }

input[type="radio"] { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; }
.ie7 input[type="checkbox"] { vertical-align: baseline; }
.ie6 input { vertical-align: text-bottom; }

label, input[type="button"], input[type="submit"], input[type="image"], button { cursor: pointer; }

button, input, select, textarea { margin: 0; }

input:valid, textarea:valid   {  }
input:invalid, textarea:invalid {
   border-radius: 1px; -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; box-shadow: 0px 0px 5px red;
}
.no-boxshadow input:invalid, .no-boxshadow textarea:invalid { background-color: #f0dddd; }

::-moz-selection{ background: #FF5E99; color:#fff; text-shadow: none; }
::selection { background:#FF5E99; color:#fff; text-shadow: none; }

a:link { -webkit-tap-highlight-color: #FF5E99; }

button {  width: auto; overflow: visible; }

.ie7 img { -ms-interpolation-mode: bicubic; }

body, select, input, textarea {
  color: #444;
  font-family: "Helvetica Neue", Arial, sans-serif;
}

h1, h2, h3, h4, h5, h6 { font-weight: normal; }

.ir { display: block; text-indent: -999em; overflow: hidden; background-repeat: no-repeat; text-align: left; direction: ltr; }
.hidden { display: none; visibility: hidden; }

.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }
.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; }
.invisible { visibility: hidden; }

.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }

button::-moz-focus-inner {
  border: 0;
}

/**
 * Media queries for responsive design.
 *
 * These follow after primary styles so they will successfully override.
 */

@media all and (orientation:portrait) {
  /* Style adjustments for portrait mode goes here */

}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */

}

/* Grade-A Mobile Browsers (Opera Mobile, Mobile Safari, Android Chrome)
   consider this: www.cloudfour.com/css-media-query-for-mobile-is-fools-gold/ */
@media screen and (max-device-width: 480px) {

  /* Uncomment if you don't want iOS and WinMobile to mobile-optimize the text for you: j.mp/textsizeadjust */
  /* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */
}

/**
 * Print styles.
 *
 * Inlined to avoid required HTTP connection: www.phpied.com/delay-loading-your-print-css/
 */
@media print {
  * { background: transparent !important; color: black !important; text-shadow: none !important; filter:none !important;
  -ms-filter: none !important; } /* Black prints faster: sanbeiji.com/archives/953 */
  a, a:visited { color: #444 !important; text-decoration: underline; }
  a[href]:after { content: " (" attr(href) ")"; }
  abbr[title]:after { content: " (" attr(title) ")"; }
  .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }  /* Don't show links for images, or javascript/internal links */
  pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
  thead { display: table-header-group; } /* css-discuss.incutio.com/wiki/Printing_Tables */
  tr, img { page-break-inside: avoid; }
  @page { margin: 0.5cm; }
  p, h2, h3 { orphans: 3; widows: 3; }
  h2, h3{ page-break-after: avoid; }
}


text:
package android.graphics.cts;

import junit.framework.TestCase;
import android.graphics.MaskFilter;

public class MaskFilterTest extends TestCase {

    public void testConstructor() {
        // new the MaskFilter instance
        new MaskFilter();
    }
}


text:
/**
 * contentscript.js handles only requests to modify the DOM.
 *
 * menu items are initialized in background.js
 */

var Collections = {

	TWEET_ACTION : "
" +
		"+" +
		"
",

	MODAL : "

" +
		"

Add Tweet to Collection

" +
		"

Add this tweet to:
" +
		"
" +
		"
" +
		"
" +
		"
 " +
		" Create New Collection " +
		" Save " +
		" Cancel " +
		"
 " +
		"

",

	init : function(){

		// add collection modal
		$(document.body).append(Collections.MODAL);

		// immediately hide collection modal & batch save button
		Collections.hideModal();

		// collection modal: enable single save
		$("#collectionModal").on("click", ".collectionModalListItem", function(){
			var tweetId = $(this).data("tweet-id");
			var collectionId = $(this).data("collection-id");
			Collections.saveTweetToCollections(tweetId, [collectionId]);
			return false;
		});

		// collection modal: enable bulk select
		$("#collectionModal").on("click", ".collectionModalListItemCheckbox", function(){
			var collectionIds = Collections.getSelected();
			if (collectionIds.length > 0){
				$("#collectionModalSave").show();
			} else {
				$("#collectionModalSave").hide();
			}
		});

		// collection modal: enable bulk save
		$("#collectionModal").on("click", "#collectionModalSave", function(){
			var tweetId = $(this).data("tweet-id");
			var collectionIds = Collections.getSelected();
			if (collectionIds.length > 0){
				Collections.saveTweetToCollections(tweetId, collectionIds);
			}
			return false;
		});

		// collection modal: enable cancel
		$("#collectionModal").on("click", "#collectionModalCancel", function(){
			Collections.hideModal();
			return false;
		});

		// collection modal: enable new (link in new window)
		$("#collectionModal").on("click", "#collectionModalNew", function(){
			var url = $(this).data('url');
			url = URL.make("save", {url : url});
			window.open(url, '_target');
			Collections.hideModal();
			return false;
		});

		// add icon to each tweet
		Collections.injectAddins();

	},

	getSelected : function(){
		var collectionIds = [];
		$(".collectionModalListItemCheckbox").each(function(){
			if ($(this).prop('checked')){
				collectionIds[collectionIds.length] = $(this).data("collection-id");
			}
		});
		return collectionIds;
	},

	saveTweetToCollections : function(tweetId, collectionIds){

		async.each(collectionIds, function(collectionId, callback){
			var request = {
				type: "background.saveTweetsToCollection",
				collectionId : collectionId,
				ids : [tweetId]
			};
			chrome.runtime.sendMessage(request, function(response){
				callback(null);
			});
		}, function(err){

			$("#contents").hide();
			$("#footer").hide();
			$("#headerText").html("Saved to Collections.");

			setTimeout(function() {
				$("#collectionModal").fadeOut();
			}, 1000 /* Settings.UI_TIMEOUT */);

		});

	},

	showModal : function(tweetId, tweetUrl) {

		$("#header").show();
		$("#contents").show();
		$("#footer").show();
		$("#headerText").html("Add Tweet to Collection");
		$("#collectionModalList").html("

");
		$("#collectionModalSave").hide();
		$("#collectionModal").show();

		chrome.runtime.sendMessage({type: "background.loadCollections"},
		  function(response) {

			var htmlList = "";

			if (response && response.response && response.response.results){
				for (var i = 0; i < response.response.results.length; i++){
					var collectionId = response.response.results[i].timeline_id;
					var collection = response.objects.timelines[collectionId];
					var html = "
<input type='checkbox' class='collectionModalListItemCheckbox' data-tweet-id='"+tweetId+"' data-collection-id='"+collectionId+"'></input>  " + collection.name + "
";
					htmlList = htmlList + html;
				}
			}
			htmlList = "
" + htmlList + "
";
			$("#collectionModalList").html(htmlList);
			$("#collectionModalNew").data("url", tweetUrl);
			$("#collectionModalSave").data("tweet-id", tweetId);
			$("#footer").show();

		});
	},

	hideModal : function(){
		$("#collectionModal").hide();
	},

	injectCollectionAction : function(){

		// insert collection icon for every tweet
		$(".tweet, .js-tweet").each(function(){

			var tweetId = $(this).data("tweet-id");
			var existingCollectionAction = $(this).find(".ProfileTweet-action--collection");

			// only add once
			if (!existingCollectionAction || existingCollectionAction.length == 0){
				var href = $(this).find(".js-permalink").attr("href");
				var url = "http://twitter.com" + href;

				var lastAction = $(this).find(".ProfileTweet-actionList div.ProfileTweet-action:last-child");
				lastAction.before(Collections.TWEET_ACTION.replace('%URL%', url));

				$(this).on("click", ".ProfileTweet-action--collection", function(){
					Collections.showModal(tweetId, url);
					return false;
				});
			}

		});

	},

	injectAddins : function(){

		setInterval(function(){
			Collections.injectCollectionAction();
		}, 2000);

	},

}

var HTML = {

	insertTextAtPosition : function(txt) {

		var found = false;
		var focusEl = window.top.document;
		var failSafe = 0;
		var parent = window;

		var text = txt;
		var html = null;

		while (false === found) {

			// has an active element so need to keep searching, ie in a frame
			if (focusEl.activeElement) {

				// set next focusEl
				focusEl = focusEl.activeElement;

				if (focusEl instanceof HTMLIFrameElement) {

					parent = focusEl.contentDocument;
					focusEl = focusEl.contentDocument;

				}

				// found iframe in design mode
				if (focusEl.designMode == 'on' || focusEl.contentEditable) {

					// no need to carry on
					found = true;

				}

			}
			// no more active elements so we can stop
			else {

				found = true;

			}

			failSafe++;

			// failsafe in case something went wrong to prevent infinite loop
			if (failSafe > 100) {
				found = true;
				alert('Sorry, couldn\'t find target to insert text into.');
				return false;
			}

		}

		// design mode editor
		if (focusEl.designMode == 'on') {
			console.log('designmode');

			if (!html) {
				// replace line breaks with
 tags
				text = text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,
						'$1
$2');
			}

			// insert
			focusEl.execCommand('insertHtml', false, text);

		}
		// input, textarea
		else if (focusEl.tagName.toLowerCase() == 'input'
				|| focusEl.tagName.toLowerCase() == 'textarea') {
			console.log('input');
			// get start and end position of caret
			var startPos = focusEl.selectionStart;
			var endPos = focusEl.selectionEnd;

			// insert text
			focusEl.value = focusEl.value.substring(0, startPos) + text
					+ focusEl.value.substring(endPos, focusEl.value.length);

			// update caret position
			focusEl.setSelectionRange(startPos + text.length, startPos
					+ text.length);

		}
		// if content editable
		else if (focusEl.contentEditable) {
			console.log('contentEditable');
			// get selection
			var selection = parent.getSelection();
			var range = selection.getRangeAt(0);

			range.deleteContents();

			// get text
			if (html) {
				var div = document.createElement('div');
				div.innerHTML = text;
				range.insertNode(div);
			} else {
				var text = text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,
						'$1
$2');
				var texts = text.split('
');

				// insert
				for ( var i = texts.length - 1; i >= 0; i--) {
					range.insertNode(document.createTextNode(texts[i]));
					if (i > 0) {
						range.insertNode(document.createElement('br'));
					}
				}
			}
			range.collapse(true);
			range.detach();

		}

	},

}

//prevent IFRAMES from loading this listener multiple times.
if (!window.top.listenerLoaded) {

	window.top.listenerLoaded = true;

	chrome.extension.onMessage.addListener(function(request, sender,
			sendResponse) {

		console.log('contentscript.js: ' + JSON.stringify(request));

		var type = request.type;

		if (type == "contentscript.insertTextAtPosition") {
			var text = request.content;
			HTML.insertTextAtPosition(text);

			sendResponse({});
		}

		// allow async callback of sendResponse()
		return true;

	});

	Collections.init();

	console.log('contentscript.js: loaded');

}


text:
/* global Leap:true, console: true */
/* jshint browser: true*/

var AudioContext = window.AudioContext || window.webkitAudioContext;

var actx = new AudioContext();
var audio = document.getElementById('punch-audio');

actx.createMediaElementSource(audio).connect(actx.destination);

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

var counter = document.getElementById('counter');

function vectorLength(v) {
    return Math.sqrt(v.reduce(function(prev, curr) {
        return prev + curr * curr;
    }, 0));
}

function Fist(name) {
    this.name = name;

    // 当前状态: front(z < 0), back(z > 0)
    this.state = null;
}

Fist.prototype.action = function(hand) {
    var p = hand.palmPosition,
        v = hand.palmVelocity;

    if (this.state != 'back' && p[2] < -10) {
        this.state = 'back';
        if (this.onhit) this.onhit(p, v);
        return;
    }

    if (this.state != 'front' && p[2] > 10) {
        this.state = 'front';
    }
};

var left = new Fist('left');
var right = new Fist('right');
var punchs = [];

left.onhit = right.onhit = function(p, v) {
    audio.currentTime = 400;
    audio.play();
    punchs.push({
        position: p,
        power: vectorLength(v),
        life: 100
    });
    counter.textContent = ++counter.textContent;
};

var fists = {
    left: left,
    right: right
};

function renderPunchs() {
    var i = 0, punch;
    while(punchs[0] && punchs[0].life <= 0) punchs.shift();

    canvas.width = canvas.width;

    ctx.save();

    // 转换为 Leap Motion 坐标系
    ctx.translate(400, 500);
    ctx.scale(1, -1);

    while(punch = punchs[i++]) {
        ctx.beginPath();
        var r = punch.power * punch.life / 2000;
        var p = punch.position;
        ctx.arc(p[0] * 3, p[1], r, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = 'rgba(255, 0, 0, ' + (punch.life / 100) + ')';
        ctx.fill();
        punch.life -= 3;
    }

    ctx.restore();

    window.requestAnimationFrame(renderPunchs);
}

renderPunchs();

Leap.loop({
    hand: function (hand) {
        var type = hand.palmPosition[0] > 0 ? 'right' : 'left';
        fists[type].action(hand);
    }
});


text:
Rails.application.routes.draw do
  devise_for :users

  resources :links, only: [:index, :create]

  root to: 'links#index'
end


text:
from django.shortcuts import render_to_response, redirect
from resejamforaren.settings import STATIC_URL
from resejamforaren.config import MAPQUEST_KEY, RESROBOT_KEY, STREETSMART_URL, PRICE_PETROL, PRICE_DRIVING, PRICE_UPDATED, GOOGLE_ANALYTICS_KEY, \
    MAP_CENTER_POINT
from django.utils import translation

def index(req):
    context = {
        'django_static_url': STATIC_URL,
        'price_petrol': PRICE_PETROL,
        'price_driving': PRICE_DRIVING,
        'price_updated': PRICE_UPDATED,
    }
    if req.session.has_key(translation.LANGUAGE_SESSION_KEY) and req.session[translation.LANGUAGE_SESSION_KEY].startswith('en'):
        context['other_lang_code'] = 'sv'
        context['other_lang_name'] = 'Swedish'
    else:
        context['other_lang_code'] = 'en'
        context['other_lang_name'] = 'English'
    return render_to_response('rjweb/index.html', context)

def config(req):
    context = {
        'MapQuestKey': MAPQUEST_KEY,
        'ResRobotKey': RESROBOT_KEY,
        'GoogleAnalyticsKey': GOOGLE_ANALYTICS_KEY,
        'StreetSmartUrl': STREETSMART_URL,
        'PriceDriving': PRICE_DRIVING,
        'MapCenterPoint': MAP_CENTER_POINT,
    }
    return render_to_response('rjweb/config.js', context)

def info(req, page):
    context = {
        'django_static_url': STATIC_URL,
        'price_petrol': PRICE_PETROL,
        'price_driving': PRICE_DRIVING,
        'price_updated': PRICE_UPDATED,
    }
    return render_to_response('rjweb/info_%s.html' % (page, ), context)

def set_language(req):
    lang = req.GET['lang']
    translation.activate(lang)
    req.session[translation.LANGUAGE_SESSION_KEY] = lang
    return redirect('index')

def ping(req):
    return render_to_response('rjweb/ping.txt')


text:
var path = require('path'),
    fs = require('fs'),
    exists = fs.existsSync || path.existsSync,
    exec = require('child_process').spawn,
    cpr = require('cpr').cpr;

module.exports = function(grunt) {

    var STAMP = [
        '/*',
        '<%= buildtag %>',
        '<%= copyright %>',
        '<%= license %>',
        '*/',
        '',
        ''
    ].join('\n'),
        VERSION, start;

    grunt.registerTask('dist', 'Create a YUI Dist Release', [
        'dist-boot',
        'dist-tag',
        'dist-docs',
        'dist-api',
        'dist-releasenotes',
        'dist-tests',
        'dist-skins',
        'dist-extras'
    ]);

    grunt.registerTask('dist-boot', 'Booting dist build', function() {
        grunt.log.ok('Booting dist build');
        VERSION = grunt.config.get('version'),
        start = path.join(process.cwd(), 'release', VERSION);
    });

    grunt.registerTask('dist-tag', 'Tag files with copyright stamp', function() {
        var stamp = grunt.template.process(STAMP),
            count = 0;
        grunt.log.ok('Adding build stamp and copyright');
        grunt.log.ok('Adding the following stamp to all JS and CSS files');
        grunt.log.writeln('\n' + stamp);
        grunt.file.recurse(path.join(start, 'dist', 'build'), function(abs, root, part, file) {
            if (path.extname(file) === '.js' || path.extname(file) === '.css') {
                count++;
                grunt.verbose.writeln(abs);
                var data = grunt.file.read(abs);
                grunt.file.write(abs, stamp + data);
            }
        });
        grunt.log.ok('Finished processing ' + count + ' files.');
    });

    grunt.registerTask('dist-api', 'Dist Release API Docs', function() {
        grunt.log.writeln('Using YUIDoc to generate docs');
        var done = this.async(),
            base = path.join(start, 'dist', 'api'),
            yuidoc = path.join(process.cwd(), 'node_modules/yogi/node_modules/yuidocjs/lib/cli.js'),
            fakeJSON = grunt.file.readJSON(path.join(process.cwd(), 'src/common/api/dist.json')),
            docJSON = path.join(start, 'yuidoc-dist.json'),
            child;

        fakeJSON.version = VERSION;

        grunt.file.write(docJSON, JSON.stringify(fakeJSON, null, 4) + '\n');

        child = exec(process.execPath, [
            yuidoc,
            '--config',
            docJSON,
            '--outdir',
            base
        ], {
            cwd: path.join(process.cwd(), 'src'),
            env: process.env
        });

        child.on('exit', function(code) {
            if (code) {
                grunt.fail.fatal('YUIDoc exited with code ' + code, code);
            }
            grunt.log.ok('YUIDoc API Docs Complete');
            fs.unlinkSync(docJSON);
            done();
        });
    });

    grunt.registerTask('dist-docs', 'Dist Release Docs', function() {

        grunt.log.writeln('Using Selleck to generate docs');
        var done = this.async(),
            base = path.join(start, 'dist', 'docs'),
            selleck = path.join(process.cwd(), 'node_modules/yogi/node_modules/selleck/bin/selleck'),
            fakeJSON = grunt.file.readJSON(path.join(process.cwd(), 'src/common/docs/dist.json')),
            selleckJSON = path.join(start, 'selleck-dist.json'),
            child;

        fakeJSON.yuiVersion = VERSION;
        grunt.file.write(selleckJSON, JSON.stringify(fakeJSON, null, 4) + '\n');

        child = exec(process.execPath, [
            selleck,
            '--meta',
            selleckJSON,
            '--out',
            base
        ], {
            cwd: path.join(process.cwd(), 'src'),
            env: process.env
        });

        child.on('exit', function(code) {
            if (code) {
                grunt.fail.fatal('Selleck exited with code ' + code, code);
            }
            grunt.log.ok('Selleck docs complete');
            fs.unlinkSync(selleckJSON);
            done();
        });

    });

    grunt.registerTask('dist-extras', 'Adding extras to release', function() {
        grunt.log.writeln('Adding extras to release');

        var RM = path.join(process.cwd(), 'README.md'),
            RRM = path.join(start, 'dist', 'README.md'),
            L = path.join(process.cwd(), 'LICENSE.md'),
            RL = path.join(start, 'dist', 'LICENSE.md');

        grunt.file.copy(RM, RRM);
        grunt.file.copy(L, RL);

    });

    grunt.registerTask('dist-skins', 'Munging skins', function() {
        grunt.log.writeln('Munging skins into the dist');
        var done = this.async(),
            base = path.join(start, 'dist', 'build'),
            skinSrc = {};

        grunt.log.writeln('Creating rollup skins');

        cpr(path.join(process.cwd(), 'src/common/assets'),
            path.join(base, 'assets'),
            function() {
                grunt.file.recurse(base, function(abs, root, part, file) {
                    var skinName, parts, dest;
                    if (grunt.file.isMatch('*/assets/skins/'+'*', part)) {
                        if (file.indexOf('-skin.css') > -1) {
                            skinName = path.basename(part);
                            skinSrc[skinName] = skinSrc[skinName] || [];
                            skinSrc[skinName].push(grunt.file.read(abs));
                        } else {
                            parts = part.split(path.sep);
                            parts.shift();
                            dest = path.resolve(root, parts.join(path.sep), file);
                            grunt.file.copy(abs, dest);
                        }
                    }
                });

                Object.keys(skinSrc).forEach(function(dir) {
                    var skinFile = path.join(base, 'assets/skin/', dir, 'skin.css');
                    grunt.log.ok('Writing compiled skin:' + skinFile);
                    grunt.file.write(skinFile, skinSrc[dir].join('\n'));
                });
            done();
        });

    });

    grunt.registerTask('dist-releasenotes', 'Preparing Dist Release', function() {
        grunt.log.writeln('Copying Release Notes for release');
        var base = path.join(start, 'dist', 'releasenotes'),
            root, dirs, count;

        grunt.file.mkdir(base);
        root = path.join(process.cwd(), 'src');
        dirs = fs.readdirSync(root);
        count = 0;
        dirs.forEach(function(f) {
            var history = path.join(root, f, 'HISTORY.md'),
                newHist;
            if (exists(history)) {
                count++;
                newHist = path.join(base, 'HISTORY.' + f + '.md');
                grunt.file.copy(history, newHist);
            }
        });
        grunt.log.writeln('Copied ' + count + ' history files.');
    });

    grunt.registerTask('dist-tests', 'Dist Release Tests', function() {
        grunt.log.writeln('Copying tests for release');
        var base = path.join(start, 'dist', 'tests'),
            done = this.async(),
            root = path.join(process.cwd(), 'src'),
            dirs = fs.readdirSync(root),
            count = 0,
            complete = 0,
            check = function() {
                if (count === complete) {
                    grunt.log.writeln('Copied ' + count + ' test dirs.');
                    done();
                }
            };

        grunt.file.mkdir(base);

        dirs.forEach(function(f) {
            var tests = path.join(root, f, 'tests'),
                newTests;
            if (exists(tests)) {
                count++;
                newTests = path.join(base, f, 'tests');
                cpr(tests, newTests, function() {
                    complete++;
                    check();
                });
            }
        });
    });

};


text:
<resources>
    <string name="app_name">UploadManagerSamples</string>
    <string name="action_settings">Settings</string>
    <string name="fill_url">Fill your url in UploadManagerActivity first</string>
</resources>


text:
import {Injectable, EventEmitter}         from 'angular2/core';

export class AuthEventService {

    Stream:EventEmitter<boolean>;

    constructor(){
        this.Stream = new EventEmitter();
    }

    authenicatedEvent(result: boolean) {
        this.Stream.emit(result);
    }

    subscribe(s: Function) {
        this.Stream.subscribe(s);
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Posts on Abhishek Pratap Singh</title>
    <link>https://procrypt.github.io/post/</link>
    <description>Recent content in Posts on Abhishek Pratap Singh</description>
    <generator>Hugo -- gohugo.io</generator>
    <managingEditor>abhishek@linux.com (Abhishek Pratap Singh)</managingEditor>
    <webMaster>abhishek@linux.com (Abhishek Pratap Singh)</webMaster>
    <lastBuildDate>Thu, 15 Mar 2018 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://procrypt.github.io/post/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Hacker Rank 30 Days Challenge in Golang</title>
      <link>https://procrypt.github.io/post/2018-03-15-hacker-rank-30-days-challenge-solution-golang/</link>
      <pubDate>Thu, 15 Mar 2018 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2018-03-15-hacker-rank-30-days-challenge-solution-golang/</guid>
      <description>Day 0: Hello, World. Task To complete this challenge, you must save a line of input from stdin to a variable, print Hello, World. on a single line, and finally print the value of your variable on a second line.
package main import ( &#34;fmt&#34; &#34;bufio&#34; &#34;os&#34; ) func main() { reader := bufio.NewReader(os.Stdin) inputString, _ := reader.ReadString(&#39;\n&#39;) fmt.Println(&#34;Hello, World.&#34;) fmt.Println(inputString) } Day 1: Data Type Task  Declare 3 variables: one of type int, one of type double, and one of type String.</description>
    </item>

    <item>
      <title>Sorting Structs in Golang</title>
      <link>https://procrypt.github.io/post/2017-06-01-sorting-structs-in-golang/</link>
      <pubDate>Thu, 01 Jun 2017 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2017-06-01-sorting-structs-in-golang/</guid>
      <description>We can not directly use the sorting library Sort for sorting structs in Golang. In order to sort a struct the underlying struct should implement a special interface called sort.Interface
This interface requires three methods
Len, Swap and Less
Let&rsquo;s try to understand this using an example.
Define a struct type EnvVar struct { Name string value string } Here we have a struct struct named EnvVar with two fields Name and value</description>
    </item>

    <item>
      <title>Setting up Multinode OpenShift Cluster</title>
      <link>https://procrypt.github.io/post/2017-2-22-setting-up-multinode-openshift-cluster/</link>
      <pubDate>Wed, 22 Feb 2017 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2017-2-22-setting-up-multinode-openshift-cluster/</guid>
      <description>OpenShift is Red Hat&rsquo;s PaaS (Platform-as-a-Service) that allow developers to quickly develop, host, and scale applications in cloud. Based on top of Docker containers and the Kubernetes container cluster manager, OpenShift adds developer and operational centric tools to enable rapid application development, easy deployment and scaling, and long-term lifecycle maintenance for small and large teams and applications.
In this blog, we will be setting up a Multinode OpenShift Cluster (Single Master with two nodes) and will deploy a sample application on it.</description>
    </item>

    <item>
      <title>Installing Minikube</title>
      <link>https://procrypt.github.io/post/2016-12-16-installing-minikube/</link>
      <pubDate>Fri, 16 Dec 2016 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2016-12-16-installing-minikube/</guid>
      <description>Kubernetes is a container orchestration tool developed by Google, written completely in Golang. It provides a platform for deployment, scaling and automating your application in a containerized environment. Kubernetes helps you scale up your application with ease and make deployment quick. Containerize an application by creating Docker config files and build processes to produce all the necessary Docker images Configure and launch an auto-scaling, self-healing Kubernetes cluster. It is sometimes very difficult to set up a Kubernetes cluster bit thanks to minikube we can set it it up within few commands so that you can run a single node Kunbernetes cluster locally.</description>
    </item>

    <item>
      <title>Getting started with OpenShift</title>
      <link>https://procrypt.github.io/post/2016-12-08-getting-started-with-openshift/</link>
      <pubDate>Thu, 08 Dec 2016 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2016-12-08-getting-started-with-openshift/</guid>
      <description>OpenShift is Red Hat&rsquo;s PaaS (Platform-as-a-Service) that allow developers to quickly develop, host, and scale applications in cloud. Based on top of Docker containers and the Kubernetes container cluster manager, OpenShift adds developer and operational centric tools to enable rapid application development, easy deployment and scaling, and long-term lifecycle maintenance for small and large teams and applications.
There are a couple of ways by which you can setup your OpenShift cluster like minishift , oc cluster up.</description>
    </item>

    <item>
      <title>Getting started with Kompose</title>
      <link>https://procrypt.github.io/post/2016-11-02-getting-started-with-kompose/</link>
      <pubDate>Wed, 16 Nov 2016 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2016-11-02-getting-started-with-kompose/</guid>
      <description>kompose is a tool to help users, familiar with docker-compose, move to Kubernetes. It takes a Docker Compose file and translates it into Kubernetes resources.
kompose is a convenience tool to go from local Docker development to managing your application with Kubernetes. We don&rsquo;t assume that the transformation from docker compose format to Kubernetes API objects will be perfect, but it helps tremendously to start Kubernetizing your application.
In this example we will create OpenShift artifacts for guestbook app from the docker-compose file using kompose.</description>
    </item>

    <item>
      <title>Getting started with Ansible Containers</title>
      <link>https://procrypt.github.io/post/2016-11-08-getting-started-with-ansible-container/</link>
      <pubDate>Tue, 08 Nov 2016 00:00:00 +0000</pubDate>
      <author>abhishek@linux.com (Abhishek Pratap Singh)</author>
      <guid>https://procrypt.github.io/post/2016-11-08-getting-started-with-ansible-container/</guid>
      <description>Ansible Container is the ultimate workflow for container development, testing, and deployment.
Ansible Container enables you to build Docker images and orchestrate containers using only Ansible playbooks. Describe your application in a Docker Compose-like format and, rather than using a Dockerfile, provide a playbook with tasks for building images. Ansible Container will take it from there.
With Ansible Container, you are no longer limited by Dockerfile. You can now apply the power of Ansible to the image build process.</description>
    </item>

  </channel>
</rss>


text:
/* */
'use strict';
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _SafeAnchor = require('./SafeAnchor');
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var PageItem = _react2['default'].createClass({
  displayName: 'PageItem',
  propTypes: {
    href: _react2['default'].PropTypes.string,
    target: _react2['default'].PropTypes.string,
    title: _react2['default'].PropTypes.string,
    disabled: _react2['default'].PropTypes.bool,
    previous: _react2['default'].PropTypes.bool,
    next: _react2['default'].PropTypes.bool,
    onSelect: _react2['default'].PropTypes.func,
    eventKey: _react2['default'].PropTypes.any
  },
  getDefaultProps: function getDefaultProps() {
    return {
      disabled: false,
      previous: false,
      next: false
    };
  },
  render: function render() {
    var classes = {
      'disabled': this.props.disabled,
      'previous': this.props.previous,
      'next': this.props.next
    };
    return _react2['default'].createElement('li', _extends({}, this.props, {className: _classnames2['default'](this.props.className, classes)}), _react2['default'].createElement(_SafeAnchor2['default'], {
      href: this.props.href,
      title: this.props.title,
      target: this.props.target,
      onClick: this.handleSelect
    }, this.props.children));
  },
  handleSelect: function handleSelect(e) {
    if (this.props.onSelect || this.props.disabled) {
      e.preventDefault();
      if (!this.props.disabled) {
        this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
      }
    }
  }
});
exports['default'] = PageItem;
module.exports = exports['default'];


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="EditorInspectorPlugin" inherits="Reference" version="4.0">
	<brief_description>
		Plugin for adding custom property editors on inspector.
	</brief_description>
	<description>
		These plugins allow adding custom property editors to [EditorInspector].
		Plugins are registered via [method EditorPlugin.add_inspector_plugin].
		When an object is edited, the [method can_handle] function is called and must return [code]true[/code] if the object type is supported.
		If supported, the function [method parse_begin] will be called, allowing to place custom controls at the beginning of the class.
		Subsequently, the [method parse_category] and [method parse_property] are called for every category and property. They offer the ability to add custom controls to the inspector too.
		Finally, [method parse_end] will be called.
		On each of these calls, the "add" functions can be called.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="add_custom_control">
			<return type="void">
			</return>
			<argument index="0" name="control" type="Control">
			</argument>
			<description>
				Adds a custom control, not necessarily a property editor.
			</description>
		</method>
		<method name="add_property_editor">
			<return type="void">
			</return>
			<argument index="0" name="property" type="String">
			</argument>
			<argument index="1" name="editor" type="Control">
			</argument>
			<description>
				Adds a property editor, this must inherit [EditorProperty].
			</description>
		</method>
		<method name="add_property_editor_for_multiple_properties">
			<return type="void">
			</return>
			<argument index="0" name="label" type="String">
			</argument>
			<argument index="1" name="properties" type="PackedStringArray">
			</argument>
			<argument index="2" name="editor" type="Control">
			</argument>
			<description>
				Adds an editor that allows modifying multiple properties, this must inherit [EditorProperty].
			</description>
		</method>
		<method name="can_handle" qualifiers="virtual">
			<return type="bool">
			</return>
			<argument index="0" name="object" type="Object">
			</argument>
			<description>
				Returns [code]true[/code] if this object can be handled by this plugin.
			</description>
		</method>
		<method name="parse_begin" qualifiers="virtual">
			<return type="void">
			</return>
			<argument index="0" name="object" type="Object">
			</argument>
			<description>
				Called to allow adding controls at the beginning of the list.
			</description>
		</method>
		<method name="parse_category" qualifiers="virtual">
			<return type="void">
			</return>
			<argument index="0" name="object" type="Object">
			</argument>
			<argument index="1" name="category" type="String">
			</argument>
			<description>
				Called to allow adding controls at the beginning of the category.
			</description>
		</method>
		<method name="parse_end" qualifiers="virtual">
			<return type="void">
			</return>
			<description>
				Called to allow adding controls at the end of the list.
			</description>
		</method>
		<method name="parse_property" qualifiers="virtual">
			<return type="bool">
			</return>
			<argument index="0" name="object" type="Object">
			</argument>
			<argument index="1" name="type" type="int">
			</argument>
			<argument index="2" name="path" type="String">
			</argument>
			<argument index="3" name="hint" type="int">
			</argument>
			<argument index="4" name="hint_text" type="String">
			</argument>
			<argument index="5" name="usage" type="int">
			</argument>
			<description>
				Called to allow adding property specific editors to the inspector. Usually these inherit [EditorProperty]. Returning [code]true[/code] removes the built-in editor for this property, otherwise allows to insert a custom editor before the built-in one.
			</description>
		</method>
	</methods>
	<constants>
	</constants>
</class>


text:
<?php

/**
 * This is the model class for table "privilegio".
 *
 * The followings are the available columns in table 'privilegio':
 * @property integer $id
 * @property string $nombre
 *
 * The followings are the available model relations:
 * @property User[] $users
 */
class Privilegio extends MkActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'privilegio';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('nombre, rol', 'required'),
			array('nombre', 'length', 'max'=>45),
			array('rol', 'unique','className'=>'Authitem','attributeName'=>'name' ),
			array('rol', 'match','pattern'=>'/[\-_a-zA-Z]$/' ),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, nombre', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'users' => array(self::HAS_MANY, 'User', 'privilegio'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nombre' => 'Nombre',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('nombre',$this->nombre,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Privilegio the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public function afterSave(){
        $auth=Yii::app()->authManager;
        $role=$auth->createRole($this->rol,$this->rol);
    }
}


text:
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
	'id'=>'propinsi-form',
	'enableAjaxValidation'=>false,
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model); ?>

	<?php echo $form->textFieldRow($model,'idprop',array('class'=>'span5')); ?>

	<?php echo $form->textFieldRow($model,'nama_prop',array('class'=>'span5','maxlength'=>30)); ?>

		<?php $this->widget('bootstrap.widgets.TbButton', array(
			'buttonType'=>'submit',
			'type'=>'primary',
			'label'=>$model->isNewRecord ? 'Create' : 'Save',
		)); ?>

<?php $this->endWidget(); ?>


text:
import useSiteToken from '../../../hooks/useSiteToken';
import React from 'react';
import {
  Space,
  Typography,
  Tour,
  Tag,
  DatePicker,
  Alert,
  Modal,
  FloatButton,
  Progress,
} from 'antd';
import dayjs from 'dayjs';
import { CustomerServiceOutlined, QuestionCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { css } from '@emotion/react';
import useLocale from '../../../hooks/useLocale';

const SAMPLE_CONTENT_EN =
  'Ant Design 5.0 use CSS-in-JS technology to provide dynamic & mix theme ability. And which use component level CSS-in-JS solution get your application a better performance.';

const SAMPLE_CONTENT_CN =
  'Ant Design 5.0 使用 CSS-in-JS 技术以提供动态与混合主题的能力。与此同时,我们使用组件级别的 CSS-in-JS 解决方案,让你的应用获得更好的性能。';

const locales = {
  cn: {
    yesterday: '昨天',
    lastWeek: '上周',
    lastMonth: '上月',
    lastYear: '去年',
    new: '新增',
    update: '更新',
    sampleContent: SAMPLE_CONTENT_CN,
    inProgress: '进行中',
    success: '成功',
    taskFailed: '任务失败',
    tour: '漫游导览帮助用户对新加的功能进行快速了解',
  },
  en: {
    yesterday: 'Yesterday',
    lastWeek: 'Last Week',
    lastMonth: 'Last Month',
    lastYear: 'Last Year',
    new: 'New',
    update: 'Update',
    sampleContent: SAMPLE_CONTENT_EN,
    inProgress: 'In Progress',
    success: 'Success',
    taskFailed: 'Task Failed',
    tour: 'A quick guide for new come user about how to use app.',
  },
};

const useStyle = () => {
  const { token } = useSiteToken();

  return {
    card: css`
      border-radius: ${token.borderRadius}px;
      background: #f5f8ff;
      padding: ${token.paddingXL}px;
      flex: none;
      overflow: hidden;
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: stretch;

      > * {
        flex: none;
      }
    `,
    cardCircle: css`
      position: absolute;
      width: 120px;
      height: 120px;
      background: #1677ff;
      border-radius: 50%;
      filter: blur(40px);
      opacity: 0.1;
    `,
  };
};

export default function ComponentsList() {
  const { token } = useSiteToken();
  const styles = useStyle();
  const [locale] = useLocale(locales);

  const COMPONENTS: {
    title: React.ReactNode;
    type: 'new' | 'update';
    node: React.ReactNode;
  }[] = React.useMemo(
    () => [
      {
        title: 'Modal',
        type: 'update',
        node: (
          <Modal._InternalPanelDoNotUseOrYouWillBeFired title="Ant Design 5.0" width={300}>
            {locale.sampleContent}
          </Modal._InternalPanelDoNotUseOrYouWillBeFired>
        ),
      },

      {
        title: 'DatePicker',
        type: 'update',
        node: (
          <DatePicker._InternalPanelDoNotUseOrYouWillBeFired
            showToday={false}
            presets={[
              { label: locale.yesterday, value: dayjs().add(-1, 'd') },
              { label: locale.lastWeek, value: dayjs().add(-7, 'd') },
              { label: locale.lastMonth, value: dayjs().add(-1, 'month') },
              { label: locale.lastYear, value: dayjs().add(-1, 'year') },
            ]}
            value={dayjs('2022-11-18 14:00:00')}
          />
        ),
      },

      {
        title: 'Progress',
        type: 'update',
        node: (
          <Space direction="vertical">
            <Space>
              <Progress type="circle" trailColor="#e6f4ff" percent={60} width={14} />
              {locale.inProgress}
            </Space>
            <Space>
              <Progress type="circle" percent={100} width={14} />
              {locale.success}
            </Space>
            <Space>
              <Progress type="circle" status="exception" percent={88} width={14} />
              {locale.taskFailed}
            </Space>
          </Space>
        ),
      },

      {
        title: 'Tour',
        type: 'new',
        node: (
          <Tour._InternalPanelDoNotUseOrYouWillBeFired
            title="Ant Design 5.0"
            description={locale.tour}
            style={{ width: 350 }}
            current={3}
            total={9}
          />
        ),
      },
      {
        title: 'FloatButton',
        type: 'new',
        node: (
          <Space size="large">
            <FloatButton._InternalPanelDoNotUseOrYouWillBeFired
              shape="square"
              items={[
                {
                  icon: <QuestionCircleOutlined />,
                },
                {
                  icon: <CustomerServiceOutlined />,
                },
                {
                  icon: <SyncOutlined />,
                },
              ]}
            />
            <FloatButton._InternalPanelDoNotUseOrYouWillBeFired backTop />
            <FloatButton._InternalPanelDoNotUseOrYouWillBeFired
              items={[
                {
                  icon: <QuestionCircleOutlined />,
                },
                {
                  icon: <CustomerServiceOutlined />,
                },
                {
                  icon: <SyncOutlined />,
                },
              ]}
            />
          </Space>
        ),
      },

      // {
      //   title: 'Steps',
      //   type: 'update',
      //   node: <Button style={{ width: PLACEHOLDER_WIDTH }}>Placeholder</Button>,
      // },

      {
        title: 'Alert',
        type: 'update',
        node: (
          <Alert
            style={{ width: 400 }}
            message="Ant Design 5.0"
            description={locale.sampleContent}
            closable
          />
        ),
      },
    ],
    [],
  );

  return (

        {COMPONENTS.map(({ title, node, type }, index) => {
          const tagColor = type === 'new' ? 'processing' : 'warning';
          const tagText = type === 'new' ? locale.new : locale.update;

          return (

              {/* Decorator */}

              {/* Title */}
              <Space>
                <Typography.Title level={4} style={{ fontWeight: 'normal', margin: 0 }}>
                  {title}
                </Typography.Title>
                <Tag color={tagColor}>{tagText}</Tag>
              </Space>

                {node}

          );
        })}

  );
}


text:
class Notification < ActiveRecord::Base
  belongs_to :action_user, class_name: 'User'
  belongs_to :trackable,   polymorphic: true
  belongs_to :user

  scope :unread, -> { where(read: false) }

  after_create  :increment_notifications_count
  after_destroy :decrement_notifications_count

  private

  # 通知ページにアクセスしたとき、通知数をリセットするので、
  # read onlyになるカウンターキャッシュを使用せず、自前でインクリメントする
  def increment_notifications_count
    user.increment!(:notifications_count)
  end

  def decrement_notifications_count
    user.decrement!(:notifications_count)
  end
end


text:
/// <summary>**************************************************************************
///
/// $Id: XYZNumber.java,v 1.1 2002/07/25 14:56:31 grosbois Exp $
///
/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650
/// $Date $
/// ***************************************************************************
/// </summary>
using System;
using ICCProfile = CSJ2K.Icc.ICCProfile;
namespace CSJ2K.Icc.Types
{

	/// <summary> A convientient representation for the contents of the
	/// ICCXYZTypeTag class.
	///
	/// </summary>
	/// <seealso cref="jj2000.j2k.icc.tags.ICCXYZType">
	/// </seealso>
	/// <version> 	1.0
	/// </version>
	/// <author> 	Bruce A. Kern
	/// </author>
	public class XYZNumber
	{
		//UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
		//UPGRADE_NOTE: The initialization of  'size' was moved to static method 'icc.types.XYZNumber'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'"
		public static readonly int size;

		/// <summary>x value </summary>
		public int dwX;
		/// <summary>y value </summary>
		// X tristimulus value
		public int dwY;
		/// <summary>z value </summary>
		// Y tristimulus value
		public int dwZ; // Z tristimulus value

		/// <summary>Construct from constituent parts. </summary>
		public XYZNumber(int x, int y, int z)
		{
			dwX = x; dwY = y; dwZ = z;
		}

		/// <summary>Normalization utility </summary>
		public static int DoubleToXYZ(double x)
		{
			//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
			return (int) System.Math.Floor(x * 65536.0 + 0.5);
		}

		/// <summary>Normalization utility </summary>
		public static double XYZToDouble(int x)
		{
			return (double) x / 65536.0;
		}

		/// <summary>Write to a file </summary>
		//UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'"
		public virtual void  write(System.IO.FileStream raf)
		{
			System.IO.BinaryWriter temp_BinaryWriter;
			temp_BinaryWriter = new System.IO.BinaryWriter(raf);
			temp_BinaryWriter.Write((System.Int32) dwX);
			System.IO.BinaryWriter temp_BinaryWriter2;
			temp_BinaryWriter2 = new System.IO.BinaryWriter(raf);
			temp_BinaryWriter2.Write((System.Int32) dwY);
			System.IO.BinaryWriter temp_BinaryWriter3;
			temp_BinaryWriter3 = new System.IO.BinaryWriter(raf);
			temp_BinaryWriter3.Write((System.Int32) dwZ);
		}

		/// <summary>String representation of class instance. </summary>
		public override System.String ToString()
		{
			return "[" + dwX + ", " + dwY + ", " + dwZ + "]";
		}

		/* end class XYZNumber */
		static XYZNumber()
		{
			size = 3 * ICCProfile.int_size;
		}
	}
}


text:
package br.com.uol.pagseguro.api.environment;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Spy;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import br.com.uol.pagseguro.api.Case4Test;
import br.com.uol.pagseguro.api.PagSeguroEnv;
import br.com.uol.pagseguro.api.exception.PagSeguroLibException;

import static org.junit.Assert.*;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;

/**
 * @author PagSeguro Internet Ltda.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({DefaultEnvironmentProviderChain.class, JVMEnvVariableEnvironmentProvider.class,
                SystemPropEnvironmentProvider.class, SystemEnvVariableEnvironmentProvider.class})
public class DefaultEnvironmentProviderChainTest extends Case4Test {

  private JVMEnvVariableEnvironmentProvider jvmEnvVariableEnvironmentProvider;

  private SystemPropEnvironmentProvider systemPropEnvironmentProvider;

  private SystemEnvVariableEnvironmentProvider systemEnvVariableEnvironmentProvider;

  private DefaultEnvironmentProviderChain providerChain;

  @Before
  public void setUp() throws Exception {
    jvmEnvVariableEnvironmentProvider = mock(JVMEnvVariableEnvironmentProvider.class);
    systemPropEnvironmentProvider = mock(SystemPropEnvironmentProvider.class);
    systemEnvVariableEnvironmentProvider = mock(SystemEnvVariableEnvironmentProvider.class);
    whenNew(JVMEnvVariableEnvironmentProvider.class).withAnyArguments()
        .thenReturn(jvmEnvVariableEnvironmentProvider);
    whenNew(SystemPropEnvironmentProvider.class).withAnyArguments()
        .thenReturn(systemPropEnvironmentProvider);
    whenNew(SystemEnvVariableEnvironmentProvider.class).withAnyArguments()
        .thenReturn(systemEnvVariableEnvironmentProvider);
    providerChain = new DefaultEnvironmentProviderChain();
  }

  @Test
  public void shouldGetCredentialsFromJvmEnv() throws Exception {
    PagSeguroEnv expectedEnv = PagSeguroEnv.SANDBOX;

    when(jvmEnvVariableEnvironmentProvider.getEnvironment()).thenReturn(expectedEnv);

    PagSeguroEnv env = providerChain.getEnvironment();

    assertEquals(expectedEnv, env);
    InOrder inOrder = inOrder(jvmEnvVariableEnvironmentProvider, systemPropEnvironmentProvider,
        systemEnvVariableEnvironmentProvider);
    inOrder.verify(jvmEnvVariableEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verify(systemPropEnvironmentProvider, times(0)).getEnvironment();
    inOrder.verify(systemEnvVariableEnvironmentProvider, times(0)).getEnvironment();
    inOrder.verifyNoMoreInteractions();
  }

  @Test
  public void shouldGetCredentialsFromSysProp() throws Exception {
    PagSeguroEnv expectedEnv = PagSeguroEnv.SANDBOX;

    when(jvmEnvVariableEnvironmentProvider.getEnvironment())
        .thenThrow(new IllegalArgumentException());
    when(systemPropEnvironmentProvider.getEnvironment()).thenReturn(expectedEnv);

    PagSeguroEnv env = providerChain.getEnvironment();

    assertEquals(expectedEnv, env);
    InOrder inOrder = inOrder(jvmEnvVariableEnvironmentProvider, systemPropEnvironmentProvider,
        systemEnvVariableEnvironmentProvider);
    inOrder.verify(jvmEnvVariableEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verify(systemPropEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verify(systemEnvVariableEnvironmentProvider, times(0)).getEnvironment();
    inOrder.verifyNoMoreInteractions();
  }

  @Test
  public void shouldGetCredentialsFromSysEnv() throws Exception {
    PagSeguroEnv expectedEnv = PagSeguroEnv.SANDBOX;

    when(jvmEnvVariableEnvironmentProvider.getEnvironment())
        .thenThrow(new IllegalArgumentException());
    when(systemPropEnvironmentProvider.getEnvironment()).thenThrow(new IllegalArgumentException());
    when(systemEnvVariableEnvironmentProvider.getEnvironment()).thenReturn(expectedEnv);

    PagSeguroEnv env = providerChain.getEnvironment();

    assertEquals(expectedEnv, env);
    InOrder inOrder = inOrder(jvmEnvVariableEnvironmentProvider, systemPropEnvironmentProvider,
        systemEnvVariableEnvironmentProvider);
    inOrder.verify(jvmEnvVariableEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verify(systemPropEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verify(systemEnvVariableEnvironmentProvider, times(1)).getEnvironment();
    inOrder.verifyNoMoreInteractions();
  }

  @Test(expected = PagSeguroLibException.class)
  public void shouldThrowException() throws Exception {
    when(jvmEnvVariableEnvironmentProvider.getEnvironment())
        .thenThrow(new IllegalArgumentException());
    when(systemPropEnvironmentProvider.getEnvironment()).thenThrow(new IllegalArgumentException());
    when(systemEnvVariableEnvironmentProvider.getEnvironment())
        .thenThrow(new IllegalArgumentException());

    providerChain.getEnvironment();
  }
}


text:
from __future__ import absolute_import
from django.conf import settings

import hashlib
from zerver.lib.utils import make_safe_digest
if False:
    from zerver.models import UserProfile

from six import text_type

def gravatar_hash(email):
    # type: (str) -> str
    """Compute the Gravatar hash for an email address."""
    # Non-ASCII characters aren't permitted by the currently active e-mail
    # RFCs. However, the IETF has published https://tools.ietf.org/html/rfc4952,
    # outlining internationalization of email addresses, and regardless if we
    # typo an address or someone manages to give us a non-ASCII address, let's
    # not error out on it.
    return make_safe_digest(email.lower(), hashlib.md5)

def user_avatar_hash(email):
    # type: (str) -> str
    # Salting the user_key may be overkill, but it prevents us from
    # basically mimicking Gravatar's hashing scheme, which could lead
    # to some abuse scenarios like folks using us as a free Gravatar
    # replacement.
    user_key = email.lower() + settings.AVATAR_SALT
    return make_safe_digest(user_key, hashlib.sha1)

def avatar_url(user_profile):
    # type: (UserProfile) -> text_type
    return get_avatar_url(
            user_profile.avatar_source,
            user_profile.email
    )

def get_avatar_url(avatar_source, email):
    # type: (str, str) -> str
    if avatar_source == 'U':
        hash_key = user_avatar_hash(email)
        if settings.LOCAL_UPLOADS_DIR is not None:
            # ?x=x allows templates to append additional parameters with &s
            return "/user_avatars/%s.png?x=x" % (hash_key)
        else:
            bucket = settings.S3_AVATAR_BUCKET
            return "https://%s.s3.amazonaws.com/%s?x=x" % (bucket, hash_key)
    elif settings.ENABLE_GRAVATAR:
        hash_key = gravatar_hash(email)
        return "https://secure.gravatar.com/avatar/%s?d=identicon" % (hash_key,)
    else:
        return settings.DEFAULT_AVATAR_URI+'?x=x'


text:
<#
Copyright 2015 Brandon Olin

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.
#>

function Get-NSStat {
    <#
    .SYNOPSIS
        Gets the specified stat object.

    .DESCRIPTION
        Gets the specified stat object.

    .EXAMPLE
        Get-NSStat -Type 'lbvserver'

        Get all stats of type lbvserver

    .EXAMPLE
        Get-NSStat -Type 'servicegroup' -Name 'sg01'

        Get the stats for service group with name sg01

    .PARAMETER Session
        The NetScaler session object.

    .PARAMETER Type
        The type of stat object to retrieve

    .PARAMETER Name
        The name or names of specific stat objects to retrieve
    #>
    [cmdletbinding()]
    param(
        $Session = $script:session,

        [ValidateSet('aaa', 'appflow', 'appfw', 'appfwpolicy', 'appfwpolicylabel', 'appfwprofile', 'appqoe', 'appqoepolicy',
            'audit', 'authenticationloginschemapolicy', 'authenticationpolicy', 'authenticationpolicylabel', 'authenticationsamlidpolicy',
            'authenticationvserver', 'authorizationpolicylabel', 'autoscalepolicy', 'service', 'servicegroup', 'servicegroupmember',
            'ca', 'cache', 'cachecontentgroup', 'cachepolicy', 'cachepolicylabel', 'clusterinstance', 'clusternode', 'cmp', 'cmppolicy',
            'cmppolicylabel', 'crvserver', 'cvserver', 'dns', 'dnspolicylabel', 'dnsrecords', 'dos', 'dospolicy', 'feo', 'gslbdomain', 'gslbservice',
            'gslbsite', 'dslbvserver', 'hanode', 'icapolicy', 'ipseccounters', 'lbvserver', 'lldp', 'lsn', 'lsndslite', 'lsngroup', 'lsnnat64',
            'mediaclassification', 'interface', 'bridge', 'inat', 'inatsession', 'nat64', 'rnat', 'rnatip', 'tunnelip', 'tunnelip6', 'vlan', 'vpath',
            'vxlan', 'ns', 'nsacl', 'nsacl6', 'nslimitidentifier', 'nsmemory', 'nspartition', 'nspbr', 'nssimpleacl', 'nssimpleacl6',
            'nstrafficdomain', 'pq', 'pqpolicy', 'protocolhttp', 'protocolicmp', 'protocolicmpv6', 'protocolip', 'protocolipv6', 'protocoltcp',
            'ptotocoludp', 'qos', 'rewritepolicy', 'rewritepolicylabel', 'responderpolicy', 'responderpolicylabel', 'sc', 'scpolicy', 'snmp',
            'spilloverpolicy', 'ssl', 'sslvserver', 'streamidentifier', 'system', 'systembw', 'systemcpu', 'systemmemory', 'tmsessionpolicy',
            'tmtrafficpolicy', 'transformpolicy', 'transformpolicylabel', 'vpn', 'vpnvserver', 'pcpserver')]
        [parameter(Mandatory, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$Type,

        [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$Name = @()
    )

    begin {
        _AssertSessionActive
        $stats = @()
    }

    process {
        foreach ($statType in $Type) {
            if ($Name.Count -gt 0) {
                foreach ($item in $Name) {
                    $stats = _InvokeNSRestApi -Session $Session -Method Get -Type $statType -Stat -Resource $item
                    if ($stats | Get-Member -MemberType NoteProperty | Where-Object {$_.name -eq $statType}) {
                        $stats.$statType
                    }
                }
            } else {
                $stats = _InvokeNSRestApi -Session $Session -Method Get -Type $statType -Stat
                if ($stats | Get-Member -MemberType NoteProperty | Where-Object {$_.name -eq $statType}) {
                    $stats.$statType
                }
            }
        }
    }
}


text:
void GeometryHandler::initialize(std::vector<unsigned int> indices, std::vector<float> vertices) {
  size_t indices_size = indices.size();
  size_t vertices_size = vertices.size();
  size_t indices_mod = indices_size%3;
  size_t vertices_mod = vertices_size%3;

  if(indices_mod != 0)
    log_msg<LOG_WARNING>(L"GeometryHandler::initialize - index vector not multiple of 3");

  if(vertices_mod != 0)
    log_msg<LOG_WARNING>(L"GeometryHandler::initialize - vertice vector not multiple of 3");

  this->indices_ = indices;
  this->vertices_ = vertices;

  log_msg<LOG_INFO>(
    L"GeometryHandler::initialize - Handler initialized with %d indices %d vertices %d triangles")
    % this->getNumberOfIndices() % this->getNumberOfVertices() %this->getNumberOfTriangles();

  // Search bounding box
  float max_x, max_y, max_z;
  float min_x, min_y, min_z;
  max_x = max_y = max_z = -9999999999.f;
  min_x = min_y = min_z = 9999999999.f;

  for(unsigned int i = 0; i < this->getNumberOfVertices(); i++) {
    float current_x = *(this->getVertexAt(i));
    float current_y = *(this->getVertexAt(i)+1);
    float current_z = *(this->getVertexAt(i)+2);

    if(current_x < min_x) {min_x = current_x;}
    if(current_x > max_x) {max_x = current_x;}
    if(current_y < min_y) {min_y = current_y;}
    if(current_y > max_y) {max_y = current_y;}
    if(current_z < min_z) {min_z = current_z;}
    if(current_z > max_z) {max_z = current_z;}
  }
  this->bounding_box_max_.set(max_x, max_y, max_z);
  this->bounding_box_min_.set(min_x, min_y, min_z);
  this->offset_.set(min_x, min_y, min_z);
  // Get rid of the offset
  for(unsigned int i = 0; i < this->getNumberOfVertices(); i++) {
    *(this->getVertexAt(i)) -= bounding_box_min_.x;
    *(this->getVertexAt(i)+1) -= bounding_box_min_.y;
    *(this->getVertexAt(i)+2) -= bounding_box_min_.z;
  }

  this->bounding_box_max_ -= this->bounding_box_min_;
  this->bounding_box_min_ -= this->bounding_box_min_;

  nv::Vec3f dif = this->bounding_box_max_ - this->bounding_box_min_;
  this->longest_edge_ = MAX((MAX(dif.x, dif.y)), (dif.z));

  log_msg<LOG_INFO>(L"GeometryHandler::initialize - bounding box %f %f %f , %f %f %f ")
                    % min_x %min_y %min_z %max_x %max_y %max_z ;
  log_msg<LOG_INFO>(L"GeometryHandler::initialize - geometry offset %f %f %f ")
                    % this->offset_.x % this->offset_.y % this->offset_.z;
  log_msg<LOG_INFO>(L"GeometryHandler::initialize - longest edge %f")
                    %this->longest_edge_ ;
}

void GeometryHandler::initialize(unsigned int* indices, float* vertices,
                                 unsigned int number_of_indices,
                                 unsigned int number_of_vertices) {
  std::vector< unsigned int > indice_vector;
  indice_vector.assign(number_of_indices, 0);

  std::vector< float > vertice_vector;
  vertice_vector.assign(number_of_vertices, 0.f);

  log_msg<LOG_INFO>
  (L"GeometryHandler::initialize from pointers - vertices: %d indices: %d")
  %number_of_vertices
  %number_of_indices;

  for(unsigned int i = 0; i < number_of_indices; i++) {
    indice_vector.at(i) = indices[i];
  }

  for(unsigned int i = 0; i < number_of_vertices; i++){
    vertice_vector.at(i) = vertices[i];
  }

  log_msg<LOG_INFO>
  (L"GeometryHandler::initialize from pointers - vectors done, sizes %d, %d")
  %indice_vector.size()
  %vertice_vector.size();

  initialize(indice_vector, vertice_vector);
}

void GeometryHandler::setVertexAt(unsigned int i, float x, float  y, float z) {
  float* vert = this->getVertexAt(i);
  vert[0] = x;
  vert[1] = y;
  vert[2] = z;
}

void GeometryHandler::rotateGeometryAzimuth(float angle) {
  log_msg<LOG_INFO>(L"GeometryHandler::rotateGeometryAzimuth - rotate %f degrees") %angle;
  float rad = angle/180.f*(float)PI;
  for(unsigned int i = 0; i < this->getNumberOfVertices(); i++) {
    float* vert = this->getVertexAt(i);
    float x = vert[0];
    float y = vert[1];
    vert[0] = x*cosf(rad)-y*sinf(rad);
    vert[1] = x*sinf(rad)+y*cosf(rad);
  }

}

void GeometryHandler::rotateGeometryElevation(float angle) {
  log_msg<LOG_INFO>(L"GeometryHandler::rotateGeometryElevation - rotate %f degrees") %angle;
  float rad = angle/180.f*(float)PI;
  for(unsigned int i = 0; i < this->getNumberOfVertices(); i++) {
    float* vert = this->getVertexAt(i);
    float x = vert[0];
    float z = vert[2];
    vert[0] = z*cosf(rad)-x*sinf(rad);
    vert[1] = z*sinf(rad)+x*cosf(rad);
  }

}

float GeometryHandler::getSurfaceAreaAt(unsigned int idx) {
  float ret = 0.f;
  unsigned int* tri = getTriangleAt(idx);
  float* vert_0 = getVertexAt(tri[0]);
  float* vert_1 = getVertexAt(tri[1]);
  float* vert_2 = getVertexAt(tri[2]);

  nv::Vec3f u(vert_0[0]-vert_1[0],
            vert_0[1]-vert_1[1],
            vert_0[2]-vert_1[2]);
  nv::Vec3f v(vert_0[0]-vert_2[0],
            vert_0[1]-vert_2[1],
            vert_0[2]-vert_2[2]);

  ret = nv::length_(u.crossed(v))*0.5f;
  return ret;
}

float GeometryHandler::getTotalSurfaceArea() {
  float total_area = 0.f;
  for(unsigned int i = 0; i < this->getNumberOfTriangles(); i++) {
    total_area += getSurfaceAreaAt(i);
  }
  return total_area;
}

void GeometryHandler::setLayerIndices(std::vector<int> indices, std::string name) {
  int num_indices = (int)indices.size();
  int min = 99999999;
  int max = -99999999;
  for(int i = 0; i < num_indices; i++) {
    if(indices.at(i)<min)
      min = indices.at(i);
    if(indices.at(i)>max)
      max = indices.at(i);
  }
  log_msg<LOG_INFO>(L"GeometryHandler::setLayerIndices - name: %s, number of indices: %d , min val: %d max mal: %d")
                    %name.c_str() %num_indices %min %max;

  if(max >= this->getNumberOfTriangles()) {
    log_msg<LOG_INFO>(L"GeometryHandler::setLayerIndices - index %d larger than number of triangles %d, returning")
                      %max %this->getNumberOfTriangles();
    return;
  }
  if(min < 0) {
    log_msg<LOG_INFO>(L"GeometryHandler::setLayerIndices - index less than zero, returning");
    return;
  }

  this->layers_[name] = indices;
}


text:
package org.ms2ms.io;

import org.expasy.mzjava.core.ms.spectrum.RetentionTimeList;
import org.expasy.mzjava.core.ms.spectrum.ScanNumberList;
import org.expasy.mzjava.proteomics.io.ms.ident.MzIdentMlReader;
import org.expasy.mzjava.proteomics.io.ms.ident.NamespaceFilterXMLReader;
import org.expasy.mzjava.proteomics.io.ms.ident.PSMReaderCallback;
import org.expasy.mzjava.proteomics.io.ms.ident.mzidentml.v110.*;
import org.expasy.mzjava.proteomics.mol.AAMassCalculator;
import org.expasy.mzjava.proteomics.mol.modification.ModificationResolver;
import org.expasy.mzjava.proteomics.ms.ident.PeptideMatch;
import org.expasy.mzjava.proteomics.ms.ident.SpectrumIdentifier;
import org.ms2ms.math.Stats;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.sax.SAXSource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuw on 10/10/2015.
 */
public class MzIdentMLReader extends MzIdentMlReader
{
  public static Map<String, String> mScoreMap = new HashMap<>();

  static
  {
    mScoreMap.put("MS:1001330", "X\\!Tandem:expect");
    mScoreMap.put("MS:1001331", "X\\!Tandem:hyperscore");
    mScoreMap.put("MS:1001328", "OMSSA:evalue");
    mScoreMap.put("MS:1001329", "OMSSA:pvalue");
    mScoreMap.put("MS:1002049", "MS-GF:RawScore");
    mScoreMap.put("MS:1002050", "MS-GF:DeNovoScore");
    mScoreMap.put("MS:1002052", "MS-GF:SpecEValue");
    mScoreMap.put("MS:1002053", "MS-GF:EValue");
    mScoreMap.put("MS:1002054", "MS-GF:QValue");
    mScoreMap.put("MS:1002055", "MS-GF:PepQValue");
    mScoreMap.put("MS:1001171", "Mascot:score");
    mScoreMap.put("MS:1001172", "Mascot:expectation value");
    mScoreMap.put("MS:1002012", "Mascot:delta score");
    mScoreMap.put("MS:1001589", "MyriMatch:MVH");
    mScoreMap.put("MS:1001590", "MyriMatch:mzFidelity");
    mScoreMap.put("MS:1001121", "number of matched peaks");
    mScoreMap.put("MS:1001362", "number of unmatched peaks");
    mScoreMap.put("user:xcorr", "xcorr");
//    mScoreMap.put("", "");
  }
  public MzIdentMLReader(ModificationResolver modResolver) { super(modResolver); }

  public void parse(InputSource is, PSMReaderCallback callback) throws SAXException, JAXBException
  {
    //peptideRefMap = null;

    Class<MzIdentMLType> docClass = MzIdentMLType.class;

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setFeature("http://apache.org/xml/features/allow-java-encodings", true);

    NamespaceFilterXMLReader filter = new NamespaceFilterXMLReader("http://psidev.info/psi/pi/mzIdentML/1.1");
    filter.setParent(reader);

    SAXSource ss = new SAXSource(filter, is);

    String packageName = docClass.getPackage().getName();
    JAXBContext jc     = JAXBContext.newInstance(packageName);
    Unmarshaller u     = jc.createUnmarshaller();
    MzIdentMLType doc  = (MzIdentMLType) ((JAXBElement) u.unmarshal(ss)).getValue();

    readPeptideIDProteinMap(doc);
    readPeptideIDProteinPositionMap(doc);

    SpectraDataType spectraDataType = doc.getDataCollection().getInputs().getSpectraData().get(0);

    String msFileLocation = spectraDataType.getLocation();

    String fileName = null;
    if (msFileLocation != null)
    {
      File tmp = new File(msFileLocation);
      fileName = tmp.getName();
    }

    for (SpectrumIdentificationListType identList : doc.getDataCollection().getAnalysisData().getSpectrumIdentificationList())
    {
      for (SpectrumIdentificationResultType idResult : identList.getSpectrumIdentificationResult())
      {
        Map<String, AbstractParamType> idResultCVParamMap = MsReaders.toCVMap(idResult.getParamGroup());

        ScanNumberList       scanNumbers = MsReaders.newScanNumberList(idResultCVParamMap);
        RetentionTimeList retentionTimes = MsReaders.newRetentionTimeList(idResultCVParamMap);
//        int                        index = Stats.toInt(idResult.getSpectrumID());
        String                     title = idResultCVParamMap.containsKey(TITLE_CV)?idResultCVParamMap.get(TITLE_CV).getValue():"unTitled";

        for (SpectrumIdentificationItemType idItem : idResult.getSpectrumIdentificationItem())
        {
          SpectrumIdentifier identifier = new SpectrumIdentifier(title);

          identifier.setSpectrumFile(fileName);
          identifier.addRetentionTime(retentionTimes);
          identifier.addScanNumber(scanNumbers);
//          identifier.setIndex(index);
          identifier.setAssumedCharge(idItem.getChargeState());
          identifier.setPrecursorNeutralMass(AAMassCalculator.getInstance().calculateNeutralMolecularMass(idItem.getExperimentalMassToCharge(), idItem.getChargeState()));

          PeptideMatch peptideMatch = readPeptide(idItem.getPeptideRef(), doc.getSequenceCollection());

          Map<String, AbstractParamType> idItemCVParamMap = MsReaders.toCVMap(idItem.getParamGroup());

          for (String cv : mScoreMap.keySet())
            if (idItemCVParamMap.containsKey(cv))
              peptideMatch.addScore(mScoreMap.get(cv), Stats.toDouble(idItemCVParamMap.get(cv).getValue()));

          peptideMatch.setRank(idItem.getRank());
          peptideMatch.setMassDiff(idItem.getExperimentalMassToCharge() - idItem.getCalculatedMassToCharge());
          peptideMatch.setRejected(false);

          callback.resultRead(identifier, peptideMatch);
        }
      }
    }
  }
  @Override
  protected void readPeptideIDProteinPositionMap(MzIdentMLType doc)
  {
    // fix the syntax problem before calling the super()
    SequenceCollectionType seqCollection = doc.getSequenceCollection();
    if (seqCollection == null) return;

    List<PeptideEvidenceType> peptideEvidences = seqCollection.getPeptideEvidence();
    if (peptideEvidences == null || peptideEvidences.isEmpty()) return;

    for (PeptideEvidenceType entry : peptideEvidences)
    {
      if (entry.getPost().length()>1) entry.setPost(entry.getPost().substring(0, 1));
      if (entry.getPre( ).length()>1) entry.setPre( entry.getPre( ).substring(0, 1));
    }

    super.readPeptideIDProteinPositionMap(doc);
  }
}


text:
package com.milaboratory.util.sorting;

import java.util.Comparator;

/**
 * Represents a property a sequence of objects can be sorted by.
 *
 * @param <T> type of objects in stream
 */
public interface SortingProperty<T> extends Comparator<T>, Property<T, Object> {
    /**
     * Returns relation to other property. See docs for {@link SortingPropertyRelation} for details.
     *
     * @param other other property defined for the same object type
     * @return relation to other property
     */
    default SortingPropertyRelation relationTo(SortingProperty<?> other) {
        return this.equals(other) ? SortingPropertyRelation.Equal : SortingPropertyRelation.None;
    }
}


text:
layout: regulamento_es
title: Reglamento de Velocistas
---
[](velocistas_gl)

### Reglamento de Velocistas

  - Revisión 2 (2018): vigente desde OSHWDem 2018

##### Objetivo

Un robot participa para ser el más rápido de un circuito. Cada robot tiene dos
intentos para completar el recorrido y se tendrá en cuenta para la
clasificación únicamente el menor de los tiempos. Cada intento constará de
tres vueltas al circuito. El reglamento se detalla a continuación.

##### Zona de competición

- La zona de competición será un espacio que consiste en una lona blanca con un
trazado negro sobre la misma.
- Entre el borde exterior de la lona y el trazado habrá un margen libre de
obstáculos de al menos 10 cm.
- Esta zona de competición es de uso exclusivo de los jueces y los constructores
de cada equipo, que deberán ubicar al robot en el circuito al comienzo de la
competición debiendo retirarse acto seguido de la zona de competición.
- La zona de competición puede presentar pequeñas irregularidades, debido a la
naturaleza de la misma, que se tratarán de minimizar todo lo posible.

##### Trazado

- El trazado o recorrido del circuito es cerrado, los puntos de salida y llegada
son el mismo.
- El trazado será de color negro. Tendrán una longitud aproximada de
entre 8 y 10 metros, con un ancho de línea de 20 milímetros y servirá como
guía de navegación para los robots.
- El trazado incluye rectas y curvas de diferentes radios.
- **El radio mínimo de curva es de 40 centímetros.**
- Los sensores utilizados en los robots para detectar la pista deberán poder
configurarse in-situ para evitar posibles variaciones en las magnitudes
absolutas de sus parámetros puesto que la pista podrá estar iluminada con
diferentes niveles de intensidad luminosa.

##### Reglamentación para los robots

- La masa total de los robots debe ser inferior a 2000 gramos y sus dimensiones
máximas no deben superar la superficie de un folio tamaño A4 (210 x 297 mm), y
con una altura máxima de 130 milímetros.
- El funcionamiento del robot debe ser completamente autónomo una vez comience
su recorrido. Se puede utilizar cualquier método de control, siempre y cuando
esté integrado enteramente en el robot y no reciba señales o indicaciones
externas, de cualquier tipo.
- Las ruedas de los robots no deben tener ninguna sustancia pegajosa y/o que
dañe o ensucie la pista.
- **Las ruedas de los robots pueden contener sustancias adherentes, limitándose únicamente a aquellas destinadas específicamente al modelismo o slot. Cualquier exceso de adherente que ensucie la pista, invalidará el intento para el robot. El juez realizará comprobaciones, previas a cada intento, sobre un folio blanco que no podrá quedar pegado a las ruedas del robot ni dejar rastros de suciedad.**
- El robot puede aprender o memorizar el trazado del circuito de manera autónoma
una vez comienza la competición. No se permite aprender o memorizar el
circuito ni programar sus dimensiones en las fases previas a la competición o
durante las fases de prueba del circuito.
- No se podrá reprogramar o modificar el firmware del robot una vez dé comienzo
la competición. Sí será posible realizar pequeños ajustes en el hardware
siempre en un tiempo inferior a 20 segundos (baterías, potenciómetros, ajuste
sensores).
- Los robots deben funcionar únicamente con la energía proporcionada por pilas o
baterías eléctricas integradas en el propio robot.

##### Desarrollo de la prueba y puntuación

- Todos los robots deberán presentarse para su verificación a la hora de
comienzo de la prueba.
- Los robots competirán en estricto orden de inscripción.
- Cada robot tendrá dos intentos para completar la prueba y contará para la
clasificación únicamente el menor de los tiempos. Cada intento consistirá en
tres vueltas completas al circuito y sin pausa entre ellas.
- Al inicio de cada intento, el robot deberá situar su parte más adelantada en
la posición de salida sin sobrepasar esta.
- El cronómetro de tiempo se pondrá en marcha con el primer movimiento del robot
y se detendrá al finalizar la tercera vuelta.
- El robot que se salte parte del recorrido o no siga la línea perderá ese
intento y no será contabilizado su tiempo.
- Los tres robots ganadores serán los que obtengan, por orden, los tres mejores
tiempos de la clasificación.

##### Jueces

En la sala habrá en todo momento una serie de jueces, uno de ellos
identificado como "juez principal" que será la persona encargada de comunicar
cualquier decisión final con respecto al desarrollo de la competición e
interpretación de las normas. El participante siempre se debe dirigir al juez
principal para cualquier reclamación o aclaración de las normas.
Las decisiones finales siempre las toma el juez principal.

##### Recursos de interés

  * [Raptor](https://bricolabs.cc/wiki/proyectos/raptor)
  * [Cyclops](https://github.com/Resaj/cyclops-project)
  * [Pandatron](https://github.com/JavierIH/pandatron)
  * [VelociBotCBR](http://www.cantabrobots.es/?page_id=179)

----

Esta obra está bajo una licencia de Creative Commons Reconocimiento 4.0 Internacional.


text:
package com.futureplatforms.kirin.android.app;

import android.app.Application;

import com.futureplatforms.kirin.IKirinNativeObject;
import com.futureplatforms.kirin.KirinModule;

abstract public class KirinApplication<Module extends KirinModule<KirinNativeObj>, KirinNativeObj extends IKirinNativeObject>
		extends Application implements IKirinNativeObject, IKirinModuleHost<Module> {
	private Module module;

	@Override
	public void onCreate() {
		super.onCreate();
		KirinAndroidMethods.onCreate(this);
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		KirinAndroidMethods.onUnload(this);
	}

	@Override
	public Module getModule() {
		return module;
	}

	@Override
	public void setModule(Module module) {
		this.module = module;
	}

}


text:
echo -e "Build environment variables:"
echo "REGISTRY_URL=${REGISTRY_URL}"
echo "REGISTRY_NAMESPACE=${REGISTRY_NAMESPACE}"
echo "IMAGE_NAME=${IMAGE_NAME}"

IMAGE=$IMAGE_NAME

echo $IMAGE

echo "Files changed in previous commit :"
echo `git log -m -1 --name-only`

# Check for mentions of the config and docker directories in the last commit.
if [ `git log -m -1 --name-only | grep "config/"` ] || [ `git log -m -1 --name-only | grep "docker/"` ] ; then
  echo "Changes found in config/ or docker/ directory"
  # Call the build-on-config-change.sh script
  . ./pipeline-build-on-config-change.sh
  . ./pipeline-build-on-code-change.sh
# Check for changes to the /code directory in the last commit.
elif git log -m -1 --name-only | grep "code/" ; then
  echo "Changes found in code/ directory"
  # Call the build-on-code-change.sh script
  . ./pipeline-build-on-code-change.sh
fi

# Pass kubernetes files along with build artifacts
cp -r ../kubernetes/ $ARCHIVE_DIR

echo -e "Copying artifacts needed for deployment and testing"

# Save the registry url and namespace in the build artifacts to be used in deploy stage.
echo "REGISTRY_URL=${REGISTRY_URL}" >> $ARCHIVE_DIR/build.properties
echo "REGISTRY_NAMESPACE=${REGISTRY_NAMESPACE}" >> $ARCHIVE_DIR/build.properties
echo "IMAGE=${IMAGE}" >> $ARCHIVE_DIR/build.properties

# IMAGE_NAME from build.properties is used by Vulnerability Advisor job to reference the image qualified location in registry
echo "IMAGE_NAME=${REGISTRY_URL}/${REGISTRY_NAMESPACE}/${IMAGE}:latest" >> $ARCHIVE_DIR/build.properties


text:
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu ("Camera Filter Pack/Distortion/ShockWave")]
public class CameraFilterPack_Distortion_ShockWave : MonoBehaviour {
#region Variables
public Shader SCShader;
private float TimeX = 1.0f;
private Vector4 ScreenResolution;
private Material SCMaterial;
[Range(-1.5f, 1.5f)]
public float PosX = 0.5f;
[Range(-1.5f, 1.5f)]
public float PosY = 0.5f;
[Range(0f, 10f)]
public float Speed = 1f;
[Range(0f, 10f)]
private float Size = 1f;
public static float ChangeValue;
public static float ChangeValue2;
public static float ChangeValue3;
public static float ChangeValue4;
#endregion
#region Properties
Material material
{
get
{
if(SCMaterial == null)
{
SCMaterial = new Material(SCShader);
SCMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return SCMaterial;
}
}
#endregion
void Start ()
{
ChangeValue = PosX;
ChangeValue2 = PosY;
ChangeValue3 = Speed;
ChangeValue4 = Size;
SCShader = Shader.Find("CameraFilterPack/Distortion_ShockWave");
if(!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
}

void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
{
if(SCShader != null)
{
TimeX+=Time.deltaTime;
if (TimeX>100)  TimeX=0;
material.SetFloat("_TimeX", TimeX);
material.SetFloat("_Value", PosX);
material.SetFloat("_Value2", PosY);
material.SetFloat("_Value3", Speed);
material.SetFloat("_Value4", Size);
material.SetVector("_ScreenResolution",new Vector4(sourceTexture.width,sourceTexture.height,0.0f,0.0f));
Graphics.Blit(sourceTexture, destTexture, material);
}
else
{
Graphics.Blit(sourceTexture, destTexture);
}
}
void OnValidate(){ChangeValue=PosX;ChangeValue2=PosY;ChangeValue3=Speed;ChangeValue4=Size;}void Update ()
{
if (Application.isPlaying)
{
PosX = ChangeValue;
PosY = ChangeValue2;
Speed = ChangeValue3;
Size = ChangeValue4;
}
#if UNITY_EDITOR
if (Application.isPlaying!=true)
{
SCShader = Shader.Find("CameraFilterPack/Distortion_ShockWave");
}
#endif
}
void OnDisable ()
{
if(SCMaterial)
{
DestroyImmediate(SCMaterial);
}
}
}


text:
> Instantiates a special "other items proxy", which nests TouchBar elements inherited
> from Chromium at the space indicated by the proxy. By default, this proxy is added
> to each TouchBar at the end of the input. For more information, see the AppKit docs on
> [NSTouchBarItemIdentifierOtherItemsProxy](https://developer.apple.com/documentation/appkit/nstouchbaritemidentifierotheritemsproxy)
>
> Note: Only one instance of this class can be added per TouchBar.

Process: [Main](../glossary.md#main-process)

### `new TouchBarOtherItemsProxy()`


text:
<?php

namespace Olssonm\Zxcvbn;

use ZxcvbnPhp\Zxcvbn as ZxcvbnPhp;
use Illuminate\Support\ServiceProvider;
use Validator;

class ZxcvbnServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        /**
         * Extend the Laravel Validator with the "zxcvbn_min" rule
         */
        Validator::extend('zxcvbn_min', function($attribute, $value, $parameters) {
            $zxcvbn = new ZxcvbnPhp();
            $zxcvbn = $zxcvbn->passwordStrength($value);
            $target = 5;

            if (isset($parameters[0])) {
                $target = $parameters[0];
            }

            return ($zxcvbn['score'] >= $target);
        }, 'Your :attribute is not secure enough.');

        Validator::replacer('zxcvbn_min', function($message, $attribute) {
            $message = str_replace(':attribute', $attribute, $message);
            return $message;
        });

        /**
         * Extend the Laravel Validator with the "zxcvbn_dictionary" rule
         */
        Validator::extend('zxcvbn_dictionary', function($attribute, $value, $parameters) {
            $email = null;
            $username = null;

            if (isset($parameters[0])) {
                $email = $parameters[0];
                $username = $parameters[1];
            }

            $zxcvbn = new ZxcvbnPhp();
            $zxcvbn = $zxcvbn->passwordStrength($value, [$username, $email]);

            if (isset($zxcvbn['sequence'][0])) {
                $dictionary = $zxcvbn['sequence'][0];
                if (isset($dictionary->dictionaryName)) {
                    return false;
                }
            }

            return true;

        }, 'Your :attribute is insecure. It either matches a commonly used password, or you have used a similar username/password combination.');

        Validator::replacer('zxcvbn_dictionary', function($message, $attribute) {
            $message = str_replace(':attribute', $attribute, $message);
            return $message;
        });
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('zxcvbn', function() {
            return new ZxcvbnPhp();
        });
    }
}


text:
/*
 ONOS GUI -- Topology Mastership controller.
 Controller that handles the state of the selected mastership
 */

(function () {

    var instance;

    angular.module('ovTopo2')
        .factory('Topo2MastershipService', [

            function () {

                var MastershipController = function () {
                    instance = this;
                    this.region = null;
                    this.currentMastership = null;
                };

                MastershipController.prototype = {
                    displayMastership: function () {
                        var nodes = this.region.regionNodes(),
                            links = this.region.regionLinks();

                        _.each(nodes.concat(links), function (n) {
                            n.displayMastership(this.currentMastership);
                        });
                    },
                    mastership: function () {
                        return this.currentMastership;
                    },
                    setMastership: function (id) {
                        this.currentMastership = id;
                        this.displayMastership();
                    }
                }

                return instance || new MastershipController();
            }
        ]);
})();