text:
/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */

define( [ "util/lang", "util/time", "text!layouts/controls.html" ],
  function( LangUtils, Time, CONTROLS_LAYOUT ) {

  function Controls( container, options ) {

    var LEFT_MOUSE_BUTTON = 0,
        SPACE_BAR = 32;

    var _controls = LangUtils.domFragment( CONTROLS_LAYOUT ).querySelector( "#butter-controls" ),
        _container = typeof container === "string" ? document.getElementById( container ) : container, p,
        // variables
        muteButton, playButton, currentTimeDialog, fullscreenButton,
        durationDialog, timebar, progressBar, bigPlayButton,
        scrubber, seeking, playStateCache, active,
        volume, volumeProgressBar, volumeScrubber, position,
        controlsShare, controlsRemix, controlsFullscreen, controlsLogo,
        // functions
        bigPlayClicked, activate, deactivate, volumechange,
        togglePlay, timeMouseMove, timeMouseUp,
        timeMouseDown, volumeMouseMove, volumeMouseUp,
        volumeMouseDown, durationchange, mutechange;

    // Deal with callbacks for various buttons in controls
    options = options || {};
    var nop = function(){},
        onShareClick = options.onShareClick || nop,
        onRemixClick = options.onRemixClick || nop,
        onFullscreenClick = options.onFullscreenClick || nop,
        onLogoClick = options.onLogoClick || nop,
        init = options.init || nop;

    function onInit() {

      document.removeEventListener( "click", onInit, false );
      function setPopcorn( popcorn ) {
        p = popcorn;
      }
      init( setPopcorn );

      p.controls( false );
      if ( p.readyState() >= 1 ) {

        ready();
      } else {

        p.media.addEventListener( "loadedmetadata", ready, false );
      }
    }

    var ready = function() {
      p.media.removeEventListener( "loadedmetadata", ready, false );

      muteButton = document.getElementById( "controls-mute" );
      playButton = document.getElementById( "controls-play" );
      currentTimeDialog = document.getElementById( "controls-currenttime" );
      durationDialog = document.getElementById( "controls-duration" );
      timebar = document.getElementById( "controls-timebar" );
      progressBar = document.getElementById( "controls-progressbar" );
      bigPlayButton = document.getElementById( "controls-big-play-button" );
      scrubber = document.getElementById( "controls-scrubber" );
      volume = document.getElementById( "controls-volume" );
      fullscreenButton = document.getElementById( "controls-fullscreen" );
      volumeProgressBar = document.getElementById( "controls-volume-progressbar" );
      volumeScrubber = document.getElementById( "controls-volume-scrubber" );
      controlsShare = document.getElementById( "controls-share" );
      controlsRemix = document.getElementById( "controls-remix" );
      controlsFullscreen = document.getElementById( "controls-fullscreen" );
      controlsLogo = document.getElementById( "controls-logo" );
      seeking = false;
      playStateCache = false;
      active = false;

      // Wire custom callbacks for right-hand buttons
      controlsShare.addEventListener( "click", onShareClick, false );
      controlsRemix && controlsRemix.addEventListener( "click", onRemixClick, false );
      controlsFullscreen.addEventListener( "click", onFullscreenClick, false );
      controlsLogo.addEventListener( "click", onLogoClick, false );

      if ( bigPlayButton ) {

        bigPlayButton.classList.add( "controls-ready" );

        bigPlayClicked = function() {

          p.media.removeEventListener( "play", bigPlayClicked, false );
          bigPlayButton.removeEventListener( "click", bigPlayClicked, false );
          bigPlayButton.classList.remove( "controls-ready" );
          bigPlayButton.classList.add( "hide-button" );
          p.media.addEventListener( "mouseover", activate, false );
          if ( p.paused() ) {
            p.play();
          }
        };

        bigPlayButton.addEventListener( "click", bigPlayClicked, false );
        p.media.addEventListener( "play", bigPlayClicked, false );
      }

      // this block is used to ensure that when the video is played on a mobile device that the controls and playButton overlay
      // are in the correct state when it begins playing
      if ( !p.paused() ) {
        if ( bigPlayButton ) {
          bigPlayClicked();
        }
        playButton.classList.remove( "controls-paused" );
        playButton.classList.add( "controls-playing" );
      }

      _controls.classList.add( "controls-ready" );

      activate = function() {

        active = true;
        _controls.classList.add( "controls-active" );
      };

      deactivate = function() {

        active = false;
        if ( !seeking ) {
          _controls.classList.remove( "controls-active" );
        }
      };

      p.media.addEventListener( "mouseout", deactivate, false );
      _controls.addEventListener( "mouseover", activate, false );
      _controls.addEventListener( "mouseout", deactivate, false );

      togglePlay = function( e ) {

        // Only continue if event was triggered by the left mouse button or the spacebar
        if ( e.button !== LEFT_MOUSE_BUTTON && e.which !== SPACE_BAR ) {
          return;
        }

        if ( p.paused() ) {

          p.play();
        } else {

          p.pause();
        }
      };

      p.media.addEventListener( "click", togglePlay, false );
      window.addEventListener( "keypress", togglePlay, false );

      if ( playButton ) {

        playButton.addEventListener( "click", togglePlay, false );

        p.on( "play", function() {

          playButton.classList.remove( "controls-paused" );
          playButton.classList.add( "controls-playing" );
        });
        p.on( "pause", function() {

          playButton.classList.remove( "controls-playing" );
          playButton.classList.add( "controls-paused" );
        });
      }

      if ( muteButton ) {

        muteButton.addEventListener( "click", function( e ) {

          if ( e.button !== 0 ) {

            return;
          }

          p[ p.muted() ? "unmute" : "mute" ]();
        }, false );

        mutechange = function() {

          if ( p.muted() ) {

            muteButton.classList.remove( "controls-unmuted" );
            muteButton.classList.add( "controls-muted" );
          } else {

            muteButton.classList.remove( "controls-muted" );
            muteButton.classList.add( "controls-unmuted" );
          }
        };

        p.on( "volumechange", mutechange );
        mutechange();
      }

      if ( volume ) {

        volumeMouseMove = function( e ) {

          e.preventDefault();

          position = e.clientX - volume.getBoundingClientRect().left;

          if ( position <= 0 ) {

            p.mute();
            position = 0;
          } else if ( position > volume.offsetWidth ) {

            position = volume.offsetWidth;
          } else if ( p.muted() ) {

            p.unmute();
          }

          if ( volumeProgressBar ) {

            volumeProgressBar.style.width = ( position / volume.offsetWidth * 100 ) + "%";
          }

          if ( volumeScrubber ) {

            volumeScrubber.style.left = ( ( position - ( volumeScrubber.offsetWidth / 2 ) ) / volume.offsetWidth * 100 ) + "%";
          }

          p.volume( position / volume.offsetWidth );
        };

        volumeMouseUp = function( e ) {

          if ( e.button !== 0 ) {

            return;
          }

          e.preventDefault();
          window.removeEventListener( "mouseup", volumeMouseUp, false );
          window.removeEventListener( "mousemove", volumeMouseMove, false );
        };

        volumeMouseDown = function( e ) {

          if ( e.button !== 0 ) {

            return;
          }

          position = e.clientX - volume.getBoundingClientRect().left;

          e.preventDefault();
          window.addEventListener( "mouseup", volumeMouseUp, false );
          window.addEventListener( "mousemove", volumeMouseMove, false );

          if ( position === 0 ) {

            p.mute();
          } else if ( p.muted() ) {

            p.unmute();
          }

          if ( volumeProgressBar ) {

            volumeProgressBar.style.width = ( position / volume.offsetWidth * 100 ) + "%";
          }

          if ( volumeScrubber ) {

            volumeScrubber.style.left = ( ( position - ( volumeScrubber.offsetWidth / 2 ) ) / volume.offsetWidth * 100 ) + "%";
          }

          p.volume( position / volume.offsetWidth );
        };

        volume.addEventListener( "mousedown", volumeMouseDown, false );

        volumechange = function() {

          var width;

          if ( p.muted() ) {

            width = 0;
          } else {

            width = p.volume();
          }

          if ( width === 0 ) {

            if ( muteButton ) {

              muteButton.classList.remove( "controls-unmuted" );
              muteButton.classList.add( "controls-muted" );
            }
          }

          if ( volumeProgressBar ) {

            volumeProgressBar.style.width = ( width * 100 ) + "%";
          }

          if ( volumeScrubber ) {

            volumeScrubber.style.left = ( ( width - ( volumeScrubber.offsetWidth / 2 ) ) * 100 ) + "%";
          }
        };

        p.on( "volumechange", volumechange );

        // fire to get and set initially volume slider position
        volumechange();
      }

      if ( durationDialog ) {

        durationchange = function() {
          durationDialog.innerHTML = Time.toTimecode( p.duration(), 0 );
        };

        durationchange();
      }

      if ( timebar ) {

        timeMouseMove = function( e ) {

          e.preventDefault();

          position = e.clientX - timebar.getBoundingClientRect().left;

          if ( position < 0 ) {

            position = 0;
          } else if ( position > timebar.offsetWidth ) {

            position = timebar.offsetWidth;
          }

          if ( progressBar ) {

            progressBar.style.width = ( position / timebar.offsetWidth * 100 ) + "%";
          }

          if ( scrubber ) {

            scrubber.style.left = ( ( position - ( scrubber.offsetWidth / 2 ) ) / timebar.offsetWidth * 100 ) + "%";
          }

          p.currentTime( position / timebar.offsetWidth * 100 * p.duration() / 100 );
        };

        timeMouseUp = function( e ) {

          if ( e.button !== 0 ) {

            return;
          }

          e.preventDefault();
          seeking = false;
          if ( !active ) {
            deactivate();
          }
          if ( playStateCache ) {
            p.play();
          }
          window.removeEventListener( "mouseup", timeMouseUp, false );
          window.removeEventListener( "mousemove", timeMouseMove, false );
        };

        timeMouseDown = function( e ) {

          if ( e.button !== 0 ) {

            return;
          }

          position = e.clientX - timebar.getBoundingClientRect().left;

          e.preventDefault();
          seeking = true;
          playStateCache = !p.paused();
          p.pause();
          window.addEventListener( "mouseup", timeMouseUp, false );
          window.addEventListener( "mousemove", timeMouseMove, false );

          if ( progressBar ) {

            progressBar.style.width = ( position / timebar.offsetWidth * 100 ) + "%";
          }

          if ( scrubber ) {

            scrubber.style.left = ( ( position - ( scrubber.offsetWidth / 2 ) ) / timebar.offsetWidth * 100 ) + "%";
          }

          p.currentTime( position / timebar.offsetWidth * 100 * p.duration() / 100 );
        };

        timebar.addEventListener( "mousedown", timeMouseDown, false );

        p.on( "timeupdate", function() {

          var time = p.currentTime(),
              width = ( time / p.duration() * 100 * timebar.offsetWidth / 100 );

          if ( progressBar ) {

            progressBar.style.width = ( width / timebar.offsetWidth * 100 ) + "%";
          }

          if ( scrubber ) {

            scrubber.style.left = ( ( width - ( scrubber.offsetWidth / 2 ) ) / timebar.offsetWidth * 100 ) + "%";
          }

          if ( currentTimeDialog ) {

            currentTimeDialog.innerHTML = Time.toTimecode( time, 0 );
          }
        });
      }
    };

    _container.appendChild( _controls );

    // If we're not autoPlay, wait for user interaction before we're ready.
    if ( !options.preload ) {
      document.addEventListener( "click", onInit, false );
    } else {
      onInit();
    }

    if ( !_container ) {

      return;
    }

    return _container;
  }

  return {
    create: Controls
  };
});


text:
using Hepsi.CommandProcessor.Handlers;

namespace Hepsi.CommandProcessor.Builder
{
    /// <summary>
    /// Interface INeedAHandlers{CC2D43FA-BBC4-448A-9D0B-7B57ADF2655C}
    /// </summary>
    public interface INeedAHandlers
    {
        /// <summary>
        /// Handlerses the specified the registry.
        /// </summary>
        /// <param name="theRegistry">The registry.</param>
        /// <returns>INeedPolicy.</returns>
        INeedPolicy Handlers(HandlerConfiguration theRegistry);
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

describe('genestimate.view1 module', function() {

  beforeEach(module('genestimate.login'));

  describe('login controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view1Ctrl = $controller('LoginCtrl');
      expect(view1Ctrl).toBeDefined();
    }));

  });
});


text:
 Gets the hash code

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public override int GetHashCode()
```
### Return Value
Type: int
Returns HashCode

## See also
- [Folder](OfficeDevPnP.Core.Framework.Provisioning.Model.Folder.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)


text:
<?php
Rhaco::import("model.PublishBase");
Rhaco::import("tag.feed.Rss20");
Rhaco::import("abbr.V");

class WidgetDelicious extends PublishBase{

    function execute($rss20)
    {
    	if(!class_exists("FilterDelicious")) return $rss20;
        $channel = $rss20->getChannel();
        $items = $rss20->getItem();

        $rss20_filtered = new Rss20();
        $rss20_filtered->setChannel($channel->getTitle(),
            $channel->getDescription(),
            $channel->getLink(),
            "ja"
        );
        $properties = explode("\n",$this->variable("property"));
        foreach($items as $item) {
        	if(!method_exists($item,"getMeta")) {
        		return $rss20;
        	}
        	if(!method_exists($item,"getWidget")){
        			$item = V::mixin($item,V::anonym("widget",array("setWidget",'$name,$value','$this->widget[$name]=$value;'),array("getWidget",'$name=""','if(empty($name))return $this->widget; else return $this->widget[$name];')));
        	}
        	$delicious = array();
        	$users = $item->getMeta("delicious_users") or ($users = false);
       		$delicious["url"] = "http://badges.del.icio.us/url/".md5($item->getLink());
        	$content = "";
        	if($users && in_array("users",$properties)) {
    			$content = $content."
";
        		if($user < 2) {
        			$content = $user;
        		}elseif($users >= 2 && $users < 10) {
        			$content = "".$user."";
        		}elseif($users >= 10) {
        			$content = "".$user."";
        		}
        		$content = $content."
";
        	}
        	if($item->getMeta("tag") && in_array("tag",$properties)) {
        		$content = $content."
".implode(" ",$item->getMeta("tag"))."
";
        	}
        	if($item->getMeta("cloud") && in_array("cloud",$properties)) {
        		$content = $content."
".implode(" ",$item->getMeta("cloud"))."
";
        	}
        	$delicious["content"] = $content;
        	$item->setWidget("delicious",$delicious);
        	$rss20_filtered->setItem($item);
        }
        return $rss20_filtered;
    }

    function description() {
    	return "Deliciousに登録した人の数やタグなどを表示するボタンを作成する";
    }

	function config()
	{
		return array(
			"property"=>array("表示する内容(users,tag,cloud)","textarea","users\ntag\ncloud",true),
		);
	}

	function rhacover(){
		return "1.3.1";
	}

}
?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <title>standard.lib.str.SubStr</title>
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

    Concept Framework 2.2 documentation
  	Contents | Index

standard.lib.str.SubStr

     Name
     Version
     Deprecated

     SubStr
     version 1.0
     no

Prototype:

string SubStr(string str, number start, number length)

Description:

Returns a sub string from the given string(str). The start parameter is the index of the start character, the length is the length of the sub string.

Returns:

Returns the sub string.

Documented by Eduard Suica, generation time: Sun Jan 27 18:15:13 2013
 GMT	(c)2013 Devronium Applications


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('members', '0008_auto_20160923_2056'),
        ('boards', '0030_auto_20160925_1843'),
    ]

    operations = [
        migrations.CreateModel(
            name='JournalEntry',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=128, verbose_name='Title')),
                ('slug', models.SlugField(max_length=64, unique=True, verbose_name='Slug for this journal entry')),
                ('uuid', models.CharField(max_length=16, unique=True, verbose_name='Unique uuid for short urls')),
                ('content', models.TextField(help_text='Content of this journal entry', verbose_name='Content')),
                ('creation_datetime', models.DateTimeField(verbose_name='Creation datetime')),
                ('last_update_datetime', models.DateTimeField(verbose_name='Last update datetime')),
                ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='journal_entries', to='members.Member', verbose_name='Member')),
                ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='journal_entries', to='boards.Board', verbose_name='Board')),
            ],
        ),
    ]


text:
const { FILES_BUCKET_FIELD, FILES_TEMP_FIELD } = require('../constant');

// action handler
// if file is temporary, use provider index `1`
// if it's permanent - use index 0
function uploadSelector({ temp }) {
  return this.providers[temp ? 1 : 0];
}

// downloads can be performed from both public and temp store
// therefore we need to make selection based on the bucket name
//
// Used in the following actions:
//  * download
//  * remove
//  * access
function downloadSelector(opts, headers = {}) {
  const bucket = headers['x-cappasity-source'] === 'cn-beijing'
    ? '3dshot'
    : opts[FILES_BUCKET_FIELD];

  // backwards-compatibility
  if (!bucket) {
    // if temp - bucket for temp files, else - default bucket
    // operates under assumption that 0 index is always permanent
    // and 1 is always temporary
    return this.providers[opts[FILES_TEMP_FIELD] ? 1 : 0];
  }

  // find the bucket amongst what we have
  const provider = this.providersByBucket[bucket];

  // return provider right away
  if (provider !== undefined) {
    return provider;
  }

  throw new Error(`Bucket "${bucket}" is not defined`);
}

// type map
const ACTION_TO_SELECTOR = Object.setPrototypeOf({
  // upload action is different
  upload: uploadSelector,
  // these are all the same
  access: downloadSelector,
  download: downloadSelector,
  remove: downloadSelector,
  sync: downloadSelector,
}, null);

// fn for selection
function selectTransport(action, opts, headers) {
  const thunk = ACTION_TO_SELECTOR[action];

  if (typeof thunk !== 'function') {
    throw new Error(`${action} selector not defined`);
  }

  return thunk.call(this, opts, headers);
}

// public API
module.exports = selectTransport;


text:
using System;
using System.Collections;
using System.Configuration.Provider;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Security;
using Umbraco.Web;
using Umbraco.Web.Models;
using Umbraco.Web.Security;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.businesslogic.Exceptions;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.web;
using umbraco.controls;
using umbraco.presentation.channels.businesslogic;
using umbraco.uicontrols;
using umbraco.providers;
using umbraco.cms.presentation.Trees;
using Umbraco.Core.IO;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType;
using System.Text.RegularExpressions;
using System.Text;

namespace umbraco.cms.presentation.user
{
    /// <summary>
    /// Summary description for EditUser.
    /// </summary>
    public partial class EditUser : UmbracoEnsuredPage
    {
        public EditUser()
        {
            CurrentApp = DefaultApps.users.ToString();
        }
        protected HtmlTable macroProperties;
        protected TextBox uname = new TextBox() { ID = "uname" };
        protected RequiredFieldValidator unameValidator = new RequiredFieldValidator();
        protected TextBox lname = new TextBox() { ID = "lname" };
        protected RequiredFieldValidator lnameValidator = new RequiredFieldValidator();
        protected CustomValidator lnameCustomValidator = new CustomValidator();
        protected PlaceHolder passw = new PlaceHolder();
        protected CheckBoxList lapps = new CheckBoxList();
        protected TextBox email = new TextBox() { ID = "email" };
        protected RequiredFieldValidator emailValidator = new RequiredFieldValidator();
        protected CustomValidator emailCustomValidator = new CustomValidator();
        protected DropDownList userType = new DropDownList();
        protected DropDownList userLanguage = new DropDownList();
        protected CheckBox NoConsole = new CheckBox();
        protected CheckBox Disabled = new CheckBox();

        protected ContentPicker mediaPicker = new ContentPicker();
        protected ContentPicker contentPicker = new ContentPicker();

        protected TextBox cName = new TextBox();
        protected CheckBox cFulltree = new CheckBox();
        protected DropDownList cDocumentType = new DropDownList();
        protected DropDownList cDescription = new DropDownList();
        protected DropDownList cCategories = new DropDownList();
        protected DropDownList cExcerpt = new DropDownList();
        protected ContentPicker cMediaPicker = new ContentPicker();
        protected ContentPicker cContentPicker = new ContentPicker();
        protected CustomValidator sectionValidator = new CustomValidator();

        protected Pane pp = new Pane();

        private User u;

        private MembershipHelper _membershipHelper;

        private MembershipProvider BackOfficeProvider
        {
            get { return global::Umbraco.Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _membershipHelper = new MembershipHelper(UmbracoContext.Current);
            int UID = int.Parse(Request.QueryString["id"]);
            u = BusinessLogic.User.GetUser(UID);

            //the true admin can only edit the true admin
            if (u.Id == 0 && CurrentUser.Id != 0)
            {
                throw new Exception("Only the root user can edit the 'root' user (id:0)");
            }

            //only another admin can edit another admin (who is not the true admin)
            if (u.IsAdmin() && CurrentUser.IsAdmin() == false)
            {
                throw new Exception("Admin users can only be edited by admins");
            }

            // Populate usertype list
            foreach (UserType ut in UserType.getAll)
            {
                if (CurrentUser.IsAdmin() || ut.Alias != "admin")
                {
                    ListItem li = new ListItem(ui.Text("user", ut.Name.ToLower(), UmbracoUser), ut.Id.ToString());
                    if (ut.Id == u.UserType.Id)
                        li.Selected = true;

                    userType.Items.Add(li);
                }
            }

            var userCulture = UserExtensions.GetUserCulture(u.Language, Services.TextService);

            // Populate ui language lsit
            foreach (var lang in Services.TextService.GetSupportedCultures())
            {
                var regionCode = Services.TextService.ConvertToRegionCodeFromSupportedCulture(lang);

                var li = new ListItem(lang.DisplayName, regionCode);

                if (Equals(lang, userCulture))
                    li.Selected = true;

                userLanguage.Items.Add(li);
            }

            // Console access and disabling
            NoConsole.Checked = u.NoConsole;
            Disabled.Checked = u.Disabled;

            PlaceHolder medias = new PlaceHolder();
            mediaPicker.AppAlias = Constants.Applications.Media;
            mediaPicker.TreeAlias = "media";

            if (u.StartMediaId > 0)
                mediaPicker.Value = u.StartMediaId.ToString();
            else
                mediaPicker.Value = "-1";

            medias.Controls.Add(mediaPicker);

            PlaceHolder content = new PlaceHolder();
            contentPicker.AppAlias = Constants.Applications.Content;
            contentPicker.TreeAlias = "content";

            if (u.StartNodeId > 0)
                contentPicker.Value = u.StartNodeId.ToString();
            else
                contentPicker.Value = "-1";

            content.Controls.Add(contentPicker);

            // Add password changer
            var passwordChanger = (passwordChanger)LoadControl(SystemDirectories.Umbraco + "/controls/passwordChanger.ascx");
            passwordChanger.MembershipProviderName = UmbracoSettings.DefaultBackofficeProvider;

            //Add a custom validation message for the password changer
            var passwordValidation = new CustomValidator
            {
                ID = "PasswordChangerValidator"
            };
            var validatorContainer = new HtmlGenericControl("div")
            {
                Visible = false,
                EnableViewState = false
            };
            validatorContainer.Attributes["class"] = "alert alert-error";
            validatorContainer.Style.Add(HtmlTextWriterStyle.MarginTop, "10px");
            validatorContainer.Style.Add(HtmlTextWriterStyle.Width, "300px");
            var validatorContainer2 = new HtmlGenericControl("p");
            validatorContainer.Controls.Add(validatorContainer2);
            validatorContainer2.Controls.Add(passwordValidation);
            passw.Controls.Add(passwordChanger);
            passw.Controls.Add(validatorContainer);

            var validationSummary = new ValidationSummary
            {
                ID = "validationSummary",
                DisplayMode = ValidationSummaryDisplayMode.BulletList,
                CssClass = "error"
            };

            pp.addProperty(validationSummary);

            pp.addProperty(ui.Text("user", "username", UmbracoUser), uname, unameValidator);
            pp.addProperty(ui.Text("user", "loginname", UmbracoUser), lname, lnameValidator, lnameCustomValidator);
            pp.addProperty(ui.Text("user", "password", UmbracoUser), passw);

            pp.addProperty(ui.Text("general", "email", UmbracoUser), email, emailValidator, emailCustomValidator);
            pp.addProperty(ui.Text("user", "usertype", UmbracoUser), userType);
            pp.addProperty(ui.Text("user", "language", UmbracoUser), userLanguage);

            //Media  / content root nodes
            Pane ppNodes = new Pane();
            ppNodes.addProperty(ui.Text("user", "startnode", UmbracoUser), content);
            ppNodes.addProperty(ui.Text("user", "mediastartnode", UmbracoUser), medias);

            //Generel umrbaco access
            Pane ppAccess = new Pane();
            ppAccess.addProperty(ui.Text("user", "noConsole", UmbracoUser), NoConsole);
            ppAccess.addProperty(ui.Text("user", "disabled", UmbracoUser), Disabled);

            //access to which modules...
            Pane ppModules = new Pane();
            ppModules.addProperty(ui.Text("user", "modules", UmbracoUser), lapps);
            ppModules.addProperty(" ", sectionValidator);

            TabPage userInfo = UserTabs.NewTabPage(u.Name);

            userInfo.Controls.Add(pp);

            userInfo.Controls.Add(ppAccess);
            userInfo.Controls.Add(ppNodes);

            userInfo.Controls.Add(ppModules);

            userInfo.HasMenu = true;

            var save = userInfo.Menu.NewButton();
            save.Click += SaveUser_Click;
            save.ID = "save";
            save.ToolTip = ui.Text("save");
            save.Text = ui.Text("save");
            save.ButtonType = MenuButtonType.Primary;

            sectionValidator.ServerValidate += SectionValidator_OnServerValidate;
            sectionValidator.ControlToValidate = lapps.ID;
            sectionValidator.ErrorMessage = ui.Text("errorHandling", "errorMandatoryWithoutTab", ui.Text("user", "modules", UmbracoUser), UmbracoUser);
            sectionValidator.CssClass = "error";
            sectionValidator.Style.Add("color", "red");

            unameValidator.ControlToValidate = uname.ID;
            unameValidator.Display = ValidatorDisplay.Dynamic;
            unameValidator.ErrorMessage = ui.Text("defaultdialogs", "requiredField", UmbracoUser);
            unameValidator.CssClass = "error";
            unameValidator.Style.Add("color", "red");
            unameValidator.Style.Add("margin-left", "5px");
            unameValidator.Style.Add("line-height", "28px");

            lnameValidator.ControlToValidate = lname.ID;
            lnameValidator.Display = ValidatorDisplay.Dynamic;
            lnameValidator.ErrorMessage = ui.Text("defaultdialogs", "requiredField", UmbracoUser);
            lnameValidator.CssClass = "error";
            lnameValidator.Style.Add("color", "red");
            lnameValidator.Style.Add("margin-left", "5px");
            lnameValidator.Style.Add("line-height", "28px");

            lnameCustomValidator.ServerValidate += LnameCustomValidator_OnServerValidate;
            lnameCustomValidator.Display = ValidatorDisplay.Dynamic;
            lnameCustomValidator.ControlToValidate = lname.ID;
            var localizedLname = ui.Text("user", "loginname", UmbracoUser);
            lnameCustomValidator.ErrorMessage = ui.Text("errorHandling", "errorExistsWithoutTab", localizedLname, UmbracoUser);
            lnameCustomValidator.CssClass = "error";
            lnameCustomValidator.Style.Add("color", "red");
            lnameCustomValidator.Style.Add("margin-left", "5px");
            lnameCustomValidator.Style.Add("line-height", "28px");

            emailValidator.ControlToValidate = email.ID;
            emailValidator.Display = ValidatorDisplay.Dynamic;
            emailValidator.ErrorMessage = ui.Text("defaultdialogs", "requiredField", UmbracoUser);
            emailValidator.CssClass = "error";
            emailValidator.Style.Add("color", "red");
            emailValidator.Style.Add("margin-left", "5px");
            emailValidator.Style.Add("line-height", "28px");

            emailCustomValidator.ServerValidate += EmailCustomValidator_OnServerValidate;
            emailCustomValidator.Display = ValidatorDisplay.Dynamic;
            emailCustomValidator.ControlToValidate = email.ID;
            var localizedEmail = ui.Text("general", "email", UmbracoUser);
            emailCustomValidator.ErrorMessage = ui.Text("errorHandling", "errorRegExpWithoutTab", localizedEmail, UmbracoUser);
            emailCustomValidator.CssClass = "error";
            emailCustomValidator.Style.Add("color", "red");
            emailCustomValidator.Style.Add("margin-left", "5px");
            emailCustomValidator.Style.Add("line-height", "28px");

            SetupForm();
            SetupChannel();

            ClientTools
                .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadUsers>().Tree.Alias)
                .SyncTree(UID.ToString(), IsPostBack);
        }

        private void LnameCustomValidator_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            var usersWithLoginName = ApplicationContext.Services.UserService.GetByUsername(lname.Text);
            args.IsValid = usersWithLoginName == null || usersWithLoginName.Id == u.Id;
        }

        private void EmailCustomValidator_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = MembershipProviderBase.IsEmailValid(email.Text.Trim());
        }

        private void SectionValidator_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;

            if (lapps.SelectedIndex >= 0)
                args.IsValid = true;
        }

        private void SetupChannel()
        {
            Channel userChannel;
            try
            {
                userChannel =
                    new Channel(u.Id);
            }
            catch
            {
                userChannel = new Channel();
            }

            // Populate dropdowns
            var allContentTypes = Services.ContentTypeService.GetAllContentTypes().ToList();
            foreach (var dt in allContentTypes)
            {
                cDocumentType.Items.Add(new ListItem(dt.Name, dt.Alias));
            }

            // populate fields
            var fields = new ArrayList();
            cDescription.ID = "cDescription";
            cCategories.ID = "cCategories";
            cExcerpt.ID = "cExcerpt";
            cDescription.Items.Add(new ListItem(ui.Text("choose"), ""));
            cCategories.Items.Add(new ListItem(ui.Text("choose"), ""));
            cExcerpt.Items.Add(new ListItem(ui.Text("choose"), ""));

            foreach (var pt in allContentTypes.SelectMany(x => x.PropertyTypes).OrderBy(x => x.Name))
            {
                if (fields.Contains(pt.Alias) == false)
                {
                    cDescription.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias));
                    cCategories.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias));
                    cExcerpt.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias));
                    fields.Add(pt.Alias);
                }
            }

            // Handle content and media pickers

            PlaceHolder medias = new PlaceHolder();
            cMediaPicker.AppAlias = Constants.Applications.Media;
            cMediaPicker.TreeAlias = "media";

            if (userChannel.MediaFolder > 0)
                cMediaPicker.Value = userChannel.MediaFolder.ToString();
            else
                cMediaPicker.Value = "-1";

            medias.Controls.Add(cMediaPicker);

            PlaceHolder content = new PlaceHolder();
            cContentPicker.AppAlias = Constants.Applications.Content;
            cContentPicker.TreeAlias = "content";

            if (userChannel.StartNode > 0)
                cContentPicker.Value = userChannel.StartNode.ToString();
            else
                cContentPicker.Value = "-1";

            content.Controls.Add(cContentPicker);

            // Setup the panes
            Pane ppInfo = new Pane();
            ppInfo.addProperty(ui.Text("name", UmbracoUser), cName);
            ppInfo.addProperty(ui.Text("user", "startnode", UmbracoUser), content);
            ppInfo.addProperty(ui.Text("user", "searchAllChildren", UmbracoUser), cFulltree);
            ppInfo.addProperty(ui.Text("user", "mediastartnode", UmbracoUser), medias);

            Pane ppFields = new Pane();
            ppFields.addProperty(ui.Text("user", "documentType", UmbracoUser), cDocumentType);
            ppFields.addProperty(ui.Text("user", "descriptionField", UmbracoUser), cDescription);
            ppFields.addProperty(ui.Text("user", "categoryField", UmbracoUser), cCategories);
            ppFields.addProperty(ui.Text("user", "excerptField", UmbracoUser), cExcerpt);

            TabPage channelInfo = UserTabs.NewTabPage(ui.Text("user", "contentChannel", UmbracoUser));

            channelInfo.Controls.Add(ppInfo);
            channelInfo.Controls.Add(ppFields);

            if (!IsPostBack)
            {
                cName.Text = userChannel.Name;
                cDescription.SelectedValue = userChannel.FieldDescriptionAlias;
                cCategories.SelectedValue = userChannel.FieldCategoriesAlias;
                cExcerpt.SelectedValue = userChannel.FieldExcerptAlias;
                cDocumentType.SelectedValue = userChannel.DocumentTypeAlias;
                cFulltree.Checked = userChannel.FullTree;
            }
        }

        /// <summary>
        /// Setups the form.
        /// </summary>
        private void SetupForm()
        {

            if (!IsPostBack)
            {
                MembershipUser user = BackOfficeProvider.GetUser(u.LoginName, false);
                uname.Text = u.Name;
                lname.Text = (user == null) ? u.LoginName : user.UserName;
                email.Text = (user == null) ? u.Email : user.Email;

                contentPicker.Value = u.StartNodeId.ToString(CultureInfo.InvariantCulture);
                mediaPicker.Value = u.StartMediaId.ToString(CultureInfo.InvariantCulture);

                // get the current users applications
                string currentUserApps = ";";
                foreach (Application a in CurrentUser.Applications)
                    currentUserApps += a.alias + ";";

                Application[] uapps = u.Applications;
                foreach (Application app in BusinessLogic.Application.getAll())
                {
                    if (CurrentUser.IsAdmin() || currentUserApps.Contains(";" + app.alias + ";"))
                    {
                        ListItem li = new ListItem(ui.Text("sections", app.alias), app.alias);
                        if (!IsPostBack) foreach (Application tmp in uapps) if (app.alias == tmp.alias) li.Selected = true;
                        lapps.Items.Add(li);
                    }
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //lapps.SelectionMode = ListSelectionMode.Multiple;
            lapps.RepeatLayout = RepeatLayout.Flow;
            lapps.RepeatDirection = RepeatDirection.Vertical;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/CMSNode.asmx"));
            //      ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/legacyAjaxCalls.asmx"));

        }

        /// <summary>
        /// This handles changing the password
        /// </summary>
        /// <param name="passwordChangerControl"></param>
        /// <param name="membershipUser"></param>
        /// <param name="passwordChangerValidator"></param>
        private void ChangePassword(passwordChanger passwordChangerControl, MembershipUser membershipUser, CustomValidator passwordChangerValidator)
        {
            if (passwordChangerControl.IsChangingPassword)
            {
                //SD: not sure why this check is here but must have been for some reason at some point?
                if (string.IsNullOrEmpty(passwordChangerControl.ChangingPasswordModel.NewPassword) == false)
                {
                    // make sure password is not empty
                    if (string.IsNullOrEmpty(u.Password)) u.Password = "default";
                }

                var changePasswordModel = passwordChangerControl.ChangingPasswordModel;

                //now do the actual change
                var changePassResult = _membershipHelper.ChangePassword(
                    membershipUser.UserName, changePasswordModel, BackOfficeProvider);

                if (changePassResult.Success)
                {
                    //if it is successful, we need to show the generated password if there was one, so set
                    //that back on the control
                    passwordChangerControl.ChangingPasswordModel.GeneratedPassword = changePassResult.Result.ResetPassword;
                }
                else
                {
                    passwordChangerValidator.IsValid = false;
                    passwordChangerValidator.ErrorMessage = changePassResult.Result.ChangeError.ErrorMessage;
                    passw.Controls[1].Visible = true;
                }

            }
        }

        /// <summary>
        /// Handles the Click event of the saveUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        private void SaveUser_Click(object sender, EventArgs e)
        {
            if (base.IsValid)
            {
                try
                {
                    var membershipUser = BackOfficeProvider.GetUser(u.LoginName, false);
                    if (membershipUser == null)
                    {
                        throw new ProviderException("Could not find user in the membership provider with login name " + u.LoginName);
                    }

                    var passwordChangerControl = (passwordChanger)passw.Controls[0];
                    var passwordChangerValidator = (CustomValidator)passw.Controls[1].Controls[0].Controls[0];

                    //perform the changing password logic
                    ChangePassword(passwordChangerControl, membershipUser, passwordChangerValidator);

                    //update the membership provider
                    UpdateMembershipProvider(membershipUser);

                    //update the Umbraco user properties - even though we are updating some of these properties in the membership provider that is
                    // ok since the membership provider might be storing these details someplace totally different! But we want to keep our UI in sync.
                    u.Name = uname.Text.Trim();
                    u.Language = userLanguage.SelectedValue;
                    u.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue));
                    u.Email = email.Text.Trim();
                    u.LoginName = lname.Text;
                    u.Disabled = Disabled.Checked;
                    u.NoConsole = NoConsole.Checked;

                    int startNode;
                    if (int.TryParse(contentPicker.Value, out startNode) == false)
                    {
                        //set to default if nothing is choosen
                        if (u.StartNodeId > 0)
                            startNode = u.StartNodeId;
                        else
                            startNode = -1;
                    }
                    u.StartNodeId = startNode;

                    int mstartNode;
                    if (int.TryParse(mediaPicker.Value, out mstartNode) == false)
                    {
                        //set to default if nothing is choosen
                        if (u.StartMediaId > 0)
                            mstartNode = u.StartMediaId;
                        else
                            mstartNode = -1;
                    }
                    u.StartMediaId = mstartNode;

                    u.ClearApplications();
                    foreach (ListItem li in lapps.Items)
                    {
                        if (li.Selected) u.AddApplication(li.Value);
                    }

                    u.Save();

                    // save data
                    if (cName.Text != "")
                    {
                        Channel c;
                        try
                        {
                            c = new Channel(u.Id);
                        }
                        catch
                        {
                            c = new Channel();
                            c.User = u;
                        }

                        c.Name = cName.Text;
                        c.FullTree = cFulltree.Checked;
                        c.StartNode = int.Parse(cContentPicker.Value);
                        c.MediaFolder = int.Parse(cMediaPicker.Value);
                        c.FieldCategoriesAlias = cCategories.SelectedValue;
                        c.FieldDescriptionAlias = cDescription.SelectedValue;
                        c.FieldExcerptAlias = cExcerpt.SelectedValue;
                        c.DocumentTypeAlias = cDocumentType.SelectedValue;

                        //
                        c.MediaTypeAlias = Constants.Conventions.MediaTypes.Image; // [LK:2013-03-22] This was previously lowercase; unsure if using const will cause an issue.
                        c.MediaTypeFileProperty = Constants.Conventions.Media.File;
                        c.ImageSupport = true;

                        c.Save();

                    }

                    ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserSaved", UmbracoUser), "");
                }
                catch (Exception ex)
                {
                    ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", UmbracoUser), "");
                    LogHelper.Error<EditUser>("Exception", ex);
                }
            }
            else
            {
                ClientTools.ShowSpeechBubble(speechBubbleIcon.error,
                    ui.Text("speechBubbles", "validationFailedHeader", UmbracoUser),
                    ui.Text("speechBubbles", "validationFailedMessage", UmbracoUser));
            }
        }

        private void UpdateMembershipProvider(MembershipUser membershipUser)
        {
            //SD: This check must be here for some reason but apparently we don't want to try to
            // update when the AD provider is active.
            if ((BackOfficeProvider is ActiveDirectoryMembershipProvider) == false)
            {
                var membershipHelper = new MembershipHelper(ApplicationContext, new HttpContextWrapper(Context));
                //set the writable properties that we are editing
                membershipHelper.UpdateMember(membershipUser, BackOfficeProvider,
                                              email.Text.Trim(),
                                              Disabled.Checked == false);
            }
        }

        /// <summary>
        /// UserTabs control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected TabView UserTabs;
    }
}


text:
package apiserver

import (
	"fmt"
	"sync"

	"k8s.io/apimachinery/pkg/apimachinery/registered"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apiserver/pkg/registry/rest"
	genericapiserver "k8s.io/apiserver/pkg/server"
	kinternalinformers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"

	quotaapiv1 "github.com/openshift/origin/pkg/quota/apis/quota/v1"
	"github.com/openshift/origin/pkg/quota/controller/clusterquotamapping"
	quotainformer "github.com/openshift/origin/pkg/quota/generated/informers/internalversion"
	appliedclusterresourcequotaregistry "github.com/openshift/origin/pkg/quota/registry/appliedclusterresourcequota"
	clusterresourcequotaetcd "github.com/openshift/origin/pkg/quota/registry/clusterresourcequota/etcd"
)

type QuotaAPIServerConfig struct {
	GenericConfig *genericapiserver.Config

	ClusterQuotaMappingController *clusterquotamapping.ClusterQuotaMappingController
	QuotaInformers                quotainformer.SharedInformerFactory
	KubeInternalInformers         kinternalinformers.SharedInformerFactory

	// TODO these should all become local eventually
	Scheme   *runtime.Scheme
	Registry *registered.APIRegistrationManager
	Codecs   serializer.CodecFactory

	makeV1Storage sync.Once
	v1Storage     map[string]rest.Storage
	v1StorageErr  error
}

type QuotaAPIServer struct {
	GenericAPIServer *genericapiserver.GenericAPIServer
}

type completedConfig struct {
	*QuotaAPIServerConfig
}

// Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.
func (c *QuotaAPIServerConfig) Complete() completedConfig {
	c.GenericConfig.Complete()

	return completedConfig{c}
}

// SkipComplete provides a way to construct a server instance without config completion.
func (c *QuotaAPIServerConfig) SkipComplete() completedConfig {
	return completedConfig{c}
}

// New returns a new instance of QuotaAPIServer from the given config.
func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*QuotaAPIServer, error) {
	genericServer, err := c.QuotaAPIServerConfig.GenericConfig.SkipComplete().New("quota.openshift.io-apiserver", delegationTarget) // completion is done in Complete, no need for a second time
	if err != nil {
		return nil, err
	}

	s := &QuotaAPIServer{
		GenericAPIServer: genericServer,
	}

	v1Storage, err := c.V1RESTStorage()
	if err != nil {
		return nil, err
	}

	apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(quotaapiv1.GroupName, c.Registry, c.Scheme, metav1.ParameterCodec, c.Codecs)
	apiGroupInfo.GroupMeta.GroupVersion = quotaapiv1.SchemeGroupVersion
	apiGroupInfo.VersionedResourcesStorageMap[quotaapiv1.SchemeGroupVersion.Version] = v1Storage
	if err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil {
		return nil, err
	}

	return s, nil
}

func (c *QuotaAPIServerConfig) V1RESTStorage() (map[string]rest.Storage, error) {
	c.makeV1Storage.Do(func() {
		c.v1Storage, c.v1StorageErr = c.newV1RESTStorage()
	})

	return c.v1Storage, c.v1StorageErr
}

func (c *QuotaAPIServerConfig) newV1RESTStorage() (map[string]rest.Storage, error) {
	clusterResourceQuotaStorage, clusterResourceQuotaStatusStorage, err := clusterresourcequotaetcd.NewREST(c.GenericConfig.RESTOptionsGetter)
	if err != nil {
		return nil, fmt.Errorf("error building REST storage: %v", err)
	}

	v1Storage := map[string]rest.Storage{}
	v1Storage["clusterResourceQuotas"] = clusterResourceQuotaStorage
	v1Storage["clusterResourceQuotas/status"] = clusterResourceQuotaStatusStorage
	v1Storage["appliedClusterResourceQuotas"] = appliedclusterresourcequotaregistry.NewREST(
		c.ClusterQuotaMappingController.GetClusterQuotaMapper(),
		c.QuotaInformers.Quota().InternalVersion().ClusterResourceQuotas().Lister(),
		c.KubeInternalInformers.Core().InternalVersion().Namespaces().Lister(),
	)
	return v1Storage, nil
}


text:
package com.intellij.util.concurrency;

import com.intellij.concurrency.ContextCallable;
import com.intellij.concurrency.ContextRunnable;
import com.intellij.concurrency.ThreadContext;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.concurrency.SchedulingWrapper.MyScheduledFutureTask;
import kotlinx.coroutines.CompletableDeferred;
import kotlinx.coroutines.CompletableJob;
import kotlinx.coroutines.Job;
import org.jetbrains.annotations.ApiStatus.Internal;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import static kotlinx.coroutines.CompletableDeferredKt.CompletableDeferred;
import static kotlinx.coroutines.JobKt.Job;

@Internal
public final class Propagation {

  private static class Holder {
    private static boolean propagateThreadContext = Registry.is("ide.propagate.context");
    private static boolean propagateThreadCancellation = Registry.is("ide.propagate.cancellation");
  }

  @TestOnly
  static void runWithContextPropagationEnabled(@NotNull Runnable runnable) {
    boolean propagateThreadContext = Holder.propagateThreadContext;
    Holder.propagateThreadContext = true;
    try {
      runnable.run();
    }
    finally {
      Holder.propagateThreadContext = propagateThreadContext;
    }
  }

  @TestOnly
  static void runWithCancellationPropagationEnabled(@NotNull Runnable runnable) {
    boolean propagateThreadCancellation = Holder.propagateThreadCancellation;
    Holder.propagateThreadCancellation = true;
    try {
      runnable.run();
    }
    finally {
      Holder.propagateThreadCancellation = propagateThreadCancellation;
    }
  }

  private Propagation() { }

  static boolean isPropagateThreadContext() {
    return Holder.propagateThreadContext;
  }

  static boolean isPropagateCancellation() {
    return Holder.propagateThreadCancellation;
  }

  static @NotNull Runnable capturePropagationAndCancellationContext(@NotNull Runnable command) {
    if (isPropagateCancellation()) {
      //noinspection TestOnlyProblems
      Job currentJob = Cancellation.currentJob();
      CompletableJob childJob = Job(currentJob);
      command = new CancellationRunnable(childJob, command);
    }
    return capturePropagationContext(command);
  }

  public static @NotNull Pair<Runnable, Condition<?>> capturePropagationAndCancellationContext(
    @NotNull Runnable command,
    @NotNull Condition<?> expired
  ) {
    if (isPropagateCancellation()) {
      //noinspection TestOnlyProblems
      Job currentJob = Cancellation.currentJob();
      CompletableJob childJob = Job(currentJob);
      expired = cancelIfExpired(expired, childJob);
      command = new CancellationRunnable(childJob, command);
    }
    return Pair.create(capturePropagationContext(command), expired);
  }

  private static <T> @NotNull Condition<T> cancelIfExpired(@NotNull Condition<? super T> expiredCondition, @NotNull Job childJob) {
    return t -> {
      boolean expired = expiredCondition.value(t);
      if (expired) {
        // Cancel to avoid a hanging child job which will prevent completion of the parent one.
        childJob.cancel(null);
        return true;
      }
      else {
        // Treat runnable as expired if its job was already cancelled.
        return childJob.isCancelled();
      }
    };
  }

  private static @NotNull Runnable capturePropagationContext(@NotNull Runnable runnable) {
    if (isPropagateThreadContext()) {
      return ThreadContext.captureThreadContext(runnable);
    }
    return runnable;
  }

  static <V> @NotNull FutureTask<V> capturePropagationAndCancellationContext(@NotNull Callable<V> callable) {
    if (isPropagateCancellation()) {
      //noinspection TestOnlyProblems
      Job currentJob = Cancellation.currentJob();
      CompletableDeferred<V> childDeferred = CompletableDeferred(currentJob);
      CancellationCallable<V> cancellationCallable = new CancellationCallable<>(childDeferred, callable);
      return new CancellationFutureTask<>(childDeferred, capturePropagationContext(cancellationCallable));
    }
    return new FutureTask<>(capturePropagationContext(callable));
  }

  static <V> @NotNull MyScheduledFutureTask<V> capturePropagationAndCancellationContext(
    @NotNull SchedulingWrapper wrapper,
    @NotNull Callable<V> callable,
    long ns
  ) {
    if (isPropagateCancellation()) {
      //noinspection TestOnlyProblems
      Job currentJob = Cancellation.currentJob();
      CompletableDeferred<V> childDeferred = CompletableDeferred(currentJob);
      CancellationCallable<V> cancellationCallable = new CancellationCallable<>(childDeferred, callable);
      return new CancellationScheduledFutureTask<>(wrapper, childDeferred, capturePropagationContext(cancellationCallable), ns);
    }
    return wrapper.new MyScheduledFutureTask<>(capturePropagationContext(callable), ns);
  }

  private static <V> @NotNull Callable<V> capturePropagationContext(@NotNull Callable<V> callable) {
    if (isPropagateThreadContext()) {
      return new ContextCallable<>(false, callable);
    }
    return callable;
  }

  static @NotNull MyScheduledFutureTask<?> capturePropagationAndCancellationContext(
    @NotNull SchedulingWrapper wrapper,
    @NotNull Runnable runnable,
    long ns,
    long period
  ) {
    if (isPropagateCancellation()) {
      //noinspection TestOnlyProblems
      Job currentJob = Cancellation.currentJob();
      CompletableJob childJob = Job(currentJob);
      PeriodicCancellationRunnable cancellationRunnable = new PeriodicCancellationRunnable(childJob, runnable);
      return new CancellationScheduledFutureTask<>(wrapper, childJob, wrapWithPropagationContext(cancellationRunnable), ns, period);
    }
    return wrapper.new MyScheduledFutureTask<Void>(wrapWithPropagationContext(runnable), null, ns, period);
  }

  private static @NotNull Runnable wrapWithPropagationContext(@NotNull Runnable runnable) {
    if (isPropagateThreadContext()) {
      return new ContextRunnable(false, runnable);
    }
    return runnable;
  }

  private static final class CancellationScheduledFutureTask<V> extends SchedulingWrapper.MyScheduledFutureTask<V> {
    private final @NotNull Job myJob;

    CancellationScheduledFutureTask(@NotNull SchedulingWrapper self, @NotNull Job job, @NotNull Callable<V> callable, long ns) {
      self.super(callable, ns);
      myJob = job;
    }

    CancellationScheduledFutureTask(@NotNull SchedulingWrapper self, @NotNull Job job, @NotNull Runnable r, long ns, long period) {
      self.super(r, null, ns, period);
      myJob = job;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
      boolean result = super.cancel(mayInterruptIfRunning);
      myJob.cancel(null);
      return result;
    }
  }
}


text:
package com.normalexception.app.rx8club.cache.impl;

import java.util.List;

import android.content.Context;

import com.normalexception.app.rx8club.cache.ObjectCache;

public class ViewListCache<T> extends ObjectCache< List<T> > {

	/**
	 * To help increase the speed of the app, we are going to go ahead
	 * and cache the view list.  The cache expires each day, so if
	 * the forums update it wont take long for the app to get the
	 * updates
	 * @param ctx		The source context
	 * @param filename	The name of the cache file
	 */
	public ViewListCache(Context ctx, String filename) {
		super(ctx);
		this.CACHEFILENAME = filename;
		this.cacheDir = getExternalCache();
		this.setCacheDays(1);
	}
}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.grid.internal;

import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.internal.HttpClientFactory;

public abstract class BaseGridRegistry implements GridRegistry {
  protected final HttpClientFactory httpClientFactory;
  @Deprecated
  protected GridHubConfiguration configuration;

  // The following needs to be volatile because we expose a public setters
  protected volatile Hub hub;

  public BaseGridRegistry(Hub hub) {
    this.httpClientFactory = new HttpClientFactory();
    this.hub = hub;

    this.configuration = (hub != null) ?
       hub.getConfiguration() : new GridHubConfiguration();
  }

  /**
   * @see GridRegistry#getConfiguration()
   */
  @Deprecated
  public GridHubConfiguration getConfiguration() {
    return (hub != null) ? hub.getConfiguration() :
           (configuration != null) ? configuration : new GridHubConfiguration();
  }

  /**
   * @see GridRegistry#getHub()
   */
  public Hub getHub() {
    return hub;
  }

  /**
   * @see GridRegistry#setHub(Hub)
   */
  public void setHub(Hub hub) {
    this.hub = hub;
    if (hub != null) {
      this.configuration = hub.getConfiguration();
    }
  }

  /**
   * @see GridRegistry#getHttpClientFactory()
   */
  public HttpClientFactory getHttpClientFactory() {
    return httpClientFactory;
  }

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018 Couchbase, Inc.
 *
 *   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.
 */

#pragma once

#include <cbsasl/context.h>
#include <cbsasl/domain.h>
#include <cbsasl/error.h>

#include <functional>
#include <memory>
#include <utility>

namespace cb {
namespace sasl {
namespace server {

/**
 * Initializes the sasl server
 *
 * This function initializes the server by loading passwords from the cbsasl
 * password file. This function should only be called once.
 */
void initialize();

/**
 * close and release allocated resources
 */
void shutdown();

/**
 * List all of the mechanisms available in cbsasl
 */
std::string listmech();

/**
 * Refresh the internal data (this may result in loading password
 * databases etc)
 */
cb::sasl::Error refresh();

/**
 * Set the HMAC interation count to use.
 */
void set_hmac_iteration_count(int count);

/**
 * Set the salt to use for unknown users trying to log in. We dont' want
 * to reveal that the user doesn't exist by always returning a random
 * salt. Instead we're using a HMAC of the username and this salt as
 * the salt we're reporting back to the user.
 */
void set_scramsha_fallback_salt(const std::string& salt);

class ServerContext;

class MechanismBackend {
public:
    explicit MechanismBackend(ServerContext& ctx)
        : context(ctx), domain(Domain::Local) {
    }
    virtual ~MechanismBackend() = default;
    virtual std::pair<cb::sasl::Error, std::string_view> start(
            std::string_view input) = 0;
    virtual std::pair<cb::sasl::Error, std::string_view> step(
            std::string_view input) = 0;
    virtual std::string getName() const = 0;

    void setUsername(std::string username) {
        MechanismBackend::username = std::move(username);
    }

    const std::string& getUsername() const {
        return username;
    }

    void setDomain(Domain domain) {
        MechanismBackend::domain = domain;
    }

    Domain getDomain() const {
        return domain;
    }

protected:
    ServerContext& context;
    std::string username;
    Domain domain;
};

class ServerContext : public Context {
public:
    const std::string getName() const {
        return backend->getName();
    }

    const std::string& getUsername() const {
        return backend->getUsername();
    }

    void setDomain(Domain domain) {
        backend->setDomain(domain);
    }

    Domain getDomain() const {
        return backend->getDomain();
    }

    bool isInitialized() {
        return backend.get() != nullptr;
    }

    std::pair<cb::sasl::Error, std::string_view> start(
            const std::string& mech,
            const std::string& available,
            std::string_view input);

    std::pair<cb::sasl::Error, std::string_view> step(std::string_view input) {
        return backend->step(input);
    }

    void reset() {
        backend.reset();
        uuid.clear();
    }

protected:
    std::unique_ptr<MechanismBackend> backend;
    std::string uuid;
};

} // namespace server
} // namespace sasl
} // namespace cb


text:
/* global test expect */

import { Duration } from "../../src/luxon";

const dur = Duration.fromObject({
    years: 1,
    quarters: 2,
    months: 2,
    days: 3,
    hours: 4,
    minutes: 5,
    seconds: 6,
    milliseconds: 7,
    weeks: 8,
  }),
  inv = Duration.invalid("because i say so");

//------
// years/months/days/hours/minutes/seconds/milliseconds
//------

test("Duration#years returns the years", () => {
  expect(dur.years).toBe(1);
  expect(inv.years).toBeFalsy();
});

test("Duration#quarters returns the quarters", () => {
  expect(dur.quarters).toBe(2);
  expect(inv.quarters).toBeFalsy();
});

test("Duration#months returns the (1-indexed) months", () => {
  expect(dur.months).toBe(2);
  expect(inv.months).toBeFalsy();
});

test("Duration#days returns the days", () => {
  expect(dur.days).toBe(3);
  expect(inv.days).toBeFalsy();
});

test("Duration#hours returns the hours", () => {
  expect(dur.hours).toBe(4);
  expect(inv.hours).toBeFalsy();
});

test("Duration#hours returns the fractional hours", () => {
  const localDur = Duration.fromObject({
      years: 1,
      quarters: 2,
      months: 2,
      days: 3,
      hours: 4.5,
      minutes: 5,
      seconds: 6,
      milliseconds: 7,
      weeks: 8,
    }),
    localInv = Duration.invalid("because i say so");

  expect(localDur.hours).toBe(4.5);
  expect(localInv.hours).toBeFalsy();
});

test("Duration#minutes returns the minutes", () => {
  expect(dur.minutes).toBe(5);
  expect(inv.minutes).toBeFalsy();
});

test("Duration#seconds returns the seconds", () => {
  expect(dur.seconds).toBe(6);
  expect(inv.seconds).toBeFalsy();
});

test("Duration#milliseconds returns the milliseconds", () => {
  expect(dur.milliseconds).toBe(7);
  expect(inv.milliseconds).toBeFalsy();
});

test("Duration#weeks returns the weeks", () => {
  expect(dur.weeks).toBe(8);
  expect(inv.weeks).toBeFalsy();
});


text:
#ifndef TEMPERATURE_SENSOR_DEVICE_H
#define TEMPERATURE_SENSOR_DEVICE_H

#include "../../../common/sensor/temperature/temperature.h"

#include "../../../device/deviceDescriptor.h"

/**
 * Returns a descriptor on the TemperatureSensor device.
 * @param temperature a wrapper on temperature device
 */
DeviceDescriptor* getTemperatureSensorDeviceDescriptor(Temperature* temperature);

#endif


text:
package io.algobox.microservice.container;

import io.algobox.microservice.container.context.AppContext;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;

import javax.inject.Singleton;

import static com.google.common.base.Preconditions.checkNotNull;

public class ContainerModule extends AbstractBinder {
  private final Factory<AppContext> appContextFactory;

  public ContainerModule(AppContext appContext) {
    this.appContextFactory = new ApplicationContextFactory(appContext);
  }

  @Override
  protected void configure() {
    bindFactory(appContextFactory).to(AppContext.class).in(Singleton.class);
  }

  private class ApplicationContextFactory implements Factory<AppContext> {
    private final AppContext appContext;

    public ApplicationContextFactory(AppContext appContext) {
      this.appContext = checkNotNull(appContext);
    }

    @Override
    public AppContext provide() {
      return appContext;
    }

    @Override
    public void dispose(AppContext instance) {
      // Intentionally empty.
    }
  }
}


text:
import nglview
import tempfile
import os
import mdtraj as md
import numpy as np
import tempfile
from rdkit import Chem
from rdkit.Chem import Draw
from itertools import islice
from IPython.display import Image, HTML, display

def combine_mdtraj(protein, ligand):
  chain = protein.topology.add_chain()
  residue = protein.topology.add_residue("LIG", chain, resSeq=1)
  for atom in ligand.topology.atoms:
      protein.topology.add_atom(atom.name, atom.element, residue)
  protein.xyz = np.hstack([protein.xyz, ligand.xyz])
  protein.topology.create_standard_bonds()
  return protein

def visualize_complex(complex_mdtraj):
  ligand_atoms = [a.index for a in complex_mdtraj.topology.atoms if "LIG" in str(a.residue)]
  binding_pocket_atoms = md.compute_neighbors(complex_mdtraj, 0.5, ligand_atoms)[0]
  binding_pocket_residues = list(set([complex_mdtraj.topology.atom(a).residue.resSeq for a in binding_pocket_atoms]))
  binding_pocket_residues = [str(r) for r in binding_pocket_residues]
  binding_pocket_residues = " or ".join(binding_pocket_residues)

  traj = nglview.MDTrajTrajectory( complex_mdtraj ) # load file from RCSB PDB
  ngltraj = nglview.NGLWidget( traj )
  ngltraj.representations = [
  { "type": "cartoon", "params": {
  "sele": "protein", "color": "residueindex"
  } },
  { "type": "licorice", "params": {
  "sele": "(not hydrogen) and (%s)" %  binding_pocket_residues
  } },
  { "type": "ball+stick", "params": {
  "sele": "LIG"
  } }
  ]
  return ngltraj

def visualize_ligand(ligand_mdtraj):
  traj = nglview.MDTrajTrajectory( ligand_mdtraj ) # load file from RCSB PDB
  ngltraj = nglview.NGLWidget( traj )
  ngltraj.representations = [
    { "type": "ball+stick", "params": {"sele": "all" } } ]
  return ngltraj

def convert_lines_to_mdtraj(molecule_lines):
  tempdir = tempfile.mkdtemp()
  molecule_file = os.path.join(tempdir, "molecule.pdb")
  with open(molecule_file, "wb") as f:
    f.writelines(molecule_lines)
  molecule_mdtraj = md.load(molecule_file)
  return molecule_mdtraj

def display_images(filenames):
    """Helper to pretty-print images."""
    imagesList=''.join(
        ["<img style='width: 140px; margin: 0px; float: left; border: 1px solid black;' src='%s' />"
         % str(s) for s in sorted(filenames)])
    display(HTML(imagesList))

def mols_to_pngs(mols, basename="test"):
    """Helper to write RDKit mols to png files."""
    filenames = []
    for i, mol in enumerate(mols):
        filename = "%s%d.png" % (basename, i)
        Draw.MolToFile(mol, filename)
        filenames.append(filename)
    return filenames


text:
module Terrain.Tiles {

    export class Tile {

        public static HalfGridSize: number;

        private north: number;
        private west: number;
        private name: string;
        private tileSize: number;
        private gridSize: number;
        private sideSize: number;
        private maxMinHeight: number;

        private maxX: number;
        private minX: number;
        private maxZ: number;
        private minZ: number;

        private isCenteredTile: boolean;

        private countDownEvent: Terrain.Utilities.CountDownEvent;

        private surroundedTiles: Array<Terrain.Tiles.Tile>;
        public models: Terrain.Utilities.Dictionary<Terrain.Models.PositionedElementedResourcedInstanceModel>;
        private requestedModels: Utilities.Dictionary<BABYLON.Vector3>;

        private mesh: BABYLON.GroundMesh;

        public GetNorthLatitude(): number {
            return this.north;
        }

        public GetWestLongitude(): number {
            return this.west;
        }

        public GetName(): string {
            return this.name;
        }

        public GetPosition(): BABYLON.Vector3 {
            return this.mesh.position;
        }

        public GetMaxZ(): number {
            return this.maxZ;
        }

        public GetMinZ(): number {
            return this.minZ;
        }

        public GetMaxX(): number {
            return this.maxX;
        }

        public GetMinX(): number {
            return this.minX;
        }

        public IsSameMesh(otherMesh: BABYLON.AbstractMesh): boolean {
            return this.mesh == otherMesh;
        }

        public Show(): void {
            for (var i = 0; i < this.models.length(); i++) {
                this.models.getByIndex(i).Show();
            }
            this.mesh.isVisible = true;
        }

        public Hide(): void {
            for (var i = 0; i < this.models.length(); i++) {
                this.models.getByIndex(i).Hide();
            }
            this.mesh.isVisible = false;
        }

        public GetIsCenteredTile(): boolean {
            return this.isCenteredTile;
        }

        public SetIsCenteredTile(value: boolean): void {
            this.isCenteredTile = value;

            this.mesh.isPickable = this.isCenteredTile;
        }

        public SetSurroundedTiles(surroundedTiles: Array<Terrain.Tiles.Tile>): void {
            this.surroundedTiles = surroundedTiles;
        }

        constructor(north: number, west: number, name: string, tileSize: number, gridSize: number, maxMinHeight: number, mesh: BABYLON.GroundMesh) {
            this.mesh = mesh;

            this.north = north;
            this.west = west;
            this.tileSize = tileSize;
            this.gridSize = gridSize;
            this.maxMinHeight = maxMinHeight;
            this.setPositionZNorth(tileSize, gridSize);
            this.setPositionXWest(tileSize, gridSize);
            this.isCenteredTile = false;

            this.maxX = this.mesh.position.x + Tile.HalfGridSize;
            this.minX = this.mesh.position.x - Tile.HalfGridSize;
            this.maxZ = this.mesh.position.z + Tile.HalfGridSize;
            this.minZ = this.mesh.position.z - Tile.HalfGridSize;

            this.models = new Terrain.Utilities.Dictionary<Terrain.Models.PositionedElementedResourcedInstanceModel>();
            this.requestedModels = new Utilities.Dictionary<BABYLON.Vector3>();

            if (name) {
                this.name = name;
            }
        }

        public static LoadCenteredTile(tile: Tile): void {
            tile.LoadTile(null);
        }

        public LoadTile(countDownEvent: Terrain.Utilities.CountDownEvent): void {

            this.countDownEvent = countDownEvent;

            if (this.mesh.isReady()) {
                if (this.countDownEvent != null) {
                    this.countDownEvent.Signal();
                }
            } else {
                console.log("Requesting a new tile: North: " + this.north + " - West: " + this.west + " - GridSize : " + this.gridSize + " - TileSize : " + this.tileSize);

                var systemHttpClient = Terrain.HttpClients.SystemHttpClient.GetInstance();
                systemHttpClient.GetTileData({ NorthLalitude: this.north, WestLongitude: this.west }, TilesManager.GetInstance().OntileLoaded);
            }
        }

        public IsEqualTo(other: Tile): boolean {
            return (this.north == other.north && this.west == other.west);
        }

        public IsPositionIntoTile(position: BABYLON.Vector2): boolean {
            return ((position.x > this.minX && position.x < this.maxX)
                && (position.y > this.minZ && position.y < this.maxZ));
        }

        public GetPositonHeight(position: BABYLON.Vector2): number {
            return this.mesh.getHeightAtCoordinates(position.x, position.y);
        }

        public TileLoaded(data: any): void {
            if (data) {

                var dataParsed = null;
                if (Object.prototype.toString.call(data) === '[object Array]') {
                    dataParsed = data;
                } else {
                    dataParsed = <Array<ITileCell>>jQuery.parseJSON(data);
                }

                this.mesh._setReady(false);

                this.LoadBasicHeightMapFromCellGrid(this.mesh, dataParsed, this.maxMinHeight, false);
            }
        }

        public GetModelByPosition(names: Array<string>): Terrain.Models.PositionedElementedResourcedInstanceModel {
            for (var i = 0; i < names.length; i++) {
                var result = this.GetModelExact(names[i]);
                if (result) {
                    return result;
                }
            }
            return null;
        }

        public RequestPositionedModelCreation(position: BABYLON.Vector3, finishMapElementType: MapElement.MapElementType): boolean {
            var index = this.CalculateIndex(position);

            //console.log("RequestPositionedModelCreation, Position: X : " + position.x + " - Y : " + position.y + " - Z : " + position.z);

            if (this.requestedModels.getByKey(index.toString())) {
                console.log("RequestPositionedModelCreation, requested the creation of a model on a position that has been already requested: X: " + position.x + " Z: " + position.z);
                return false;
            }

            if (!this.CanPositionedModelOn(position, index, finishMapElementType)) {
                console.log("RequestPositionedModelCreation, requested the creation of a model on a position that is not feasible for this type of resource: X: " + position.x + " Z: " + position.z + " map element: " + finishMapElementType.toString());
                return false;
            }

            var result = Models.PositionedElementedResourcedInstanceModel.RequestCreation(this.north, this.west, index, finishMapElementType);

            if (result) {
                this.requestedModels.add(index.toString(), position);
            }

            return result;
        }

        public UpdateCell(cell: ICell): void {
            var model = this.GetModelByIndex(cell.Index);

            if (model == null && cell.FinishMapElementType == MapElement.MapElementType.empty) {
                console.log("UpdateCell, requested to remove a model but there is no model to be removed, map elment type: " + cell.InitialMapElementType.toString());
            }

            if (model != null && cell.FinishMapElementType != model.GetMapElementType()) {
                this.RemoveModelByIndex(cell.Index);
            }

            this.AddRequestedModel(cell.Index, cell.FinishMapElementType);
        }

        private AddRequestedModel(index: number, mapElementType: number): void {

            if (mapElementType != MapElement.MapElementType.empty) {
                var position = this.requestedModels.getByKey(index.toString());

                if (!position) {
                    console.log("AddRequestedModel, index not found: " + index);
                    return;
                }

                this.requestedModels.remove(index.toString());

                this.AddModel(index, position, mapElementType, true);
            }
        }

        private RemoveModelByIndex(index: number): void {
            var result = this.GetModelByIndex(index);
            if (result != null) {
                result.LaunchParticles();
                setTimeout(() => { result.Dispose(); }, 1000);
                this.models.remove(name);
            }
        }

        private GetModelExact(name: string): Terrain.Models.PositionedElementedResourcedInstanceModel {
            return this.models.getByKey(name);
        }

        private GetModelByIndex(index: number): Terrain.Models.PositionedElementedResourcedInstanceModel {
            var result = this.models.getValues().filter((positionedModel) => positionedModel.GetIndex() == index);

            if (result.length > 0) {
                return result[0];
            }
        }

        private setPositionXWest(tileSize: number, gridSize: number): void {
            this.mesh.position.x = CoordinateSystemHelps.CalculateWestEastOffSet(this.west, tileSize, gridSize);
        }

        private setPositionZNorth(tileSize: number, gridSize: number): void {
            this.mesh.position.z = CoordinateSystemHelps.CalculateNorthSouthOffSet(this.north, tileSize, gridSize);
        }

        private LoadBasicHeightMapFromCellGrid(destinyMesh: BABYLON.GroundMesh, cellGrid: Array<ITileCell>, maxMinHeight: number, updatable: boolean): void {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var types = [];
            var row, col;

            this.sideSize = Math.sqrt(cellGrid.length);
            var subdivisions = this.sideSize;
            var width = subdivisions;
            var height = subdivisions;

            //La primera fila duplica la segunda y el primero elementos de las filas sucesivas duplica el segundo elemento
            for (row = 0; row <= subdivisions; row++) {
                for (col = 0; col <= subdivisions; col++) {
                    //First one should be: position.x: -subdivision/2 / position.z: +subdivision/2 / position 0
                    var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
                    var pos = this.CalculateIndex(position, width, height);

                    position.y = maxMinHeight * cellGrid[pos].a; //altitud

                    positions.push(position.x, position.y, position.z);
                    normals.push(0, 0, 0);
                    uvs.push(col / subdivisions, 1.0 - row / subdivisions);
                    types.push(cellGrid[pos].t);

                    this.AddModel(pos, new BABYLON.Vector3(position.x + destinyMesh.position.x, position.y, position.z + destinyMesh.position.z), cellGrid[pos].c);
                }
            }

            for (row = 0; row < subdivisions; row++) {
                for (col = 0; col < subdivisions; col++) {
                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
                    indices.push(col + 1 + row * (subdivisions + 1));
                    indices.push(col + row * (subdivisions + 1));

                    indices.push(col + (row + 1) * (subdivisions + 1));
                    indices.push(col + 1 + (row + 1) * (subdivisions + 1));
                    indices.push(col + row * (subdivisions + 1));
                }
            }

            BABYLON.VertexData.ComputeNormals(positions, indices, normals);

            var vertexData = new BABYLON.VertexData();

            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;

            vertexData.applyToMesh(destinyMesh, updatable);

            destinyMesh.setVerticesData("type", types, updatable, 1); //Set the type of the vertice

            destinyMesh.computeWorldMatrix(true);

            console.log('Loaded Tile North: ' + this.north + ' - West : ' + this.west + ' located in (center point)  X: ' + destinyMesh.position.x + ' - Z: ' + destinyMesh.position.z);

            destinyMesh._setReady(true);

            if (this.countDownEvent != null) {
                this.countDownEvent.Signal();
            }
        }

        private AddModel(index: number, position: BABYLON.Vector3, mapElementType: MapElement.MapElementType, launchParticles: boolean = false): void {
            if (mapElementType != MapElement.MapElementType.empty) {
                var positionedModel = Models.MasterModelsContainer.GetInstance().GetPositionedElementedResourcedInstanceModel(this.north, this.west, index, position, mapElementType);

                if (positionedModel != null) {
                    this.models.add(positionedModel.GetName(), positionedModel);

                    if (launchParticles) {
                        positionedModel.LaunchParticles();
                    }
                } else {
                    console.log("AddModel, Error creation positioned model with map element type " + mapElementType);
                }
            }
        }

        private CalculateIndex(position: BABYLON.Vector3, width: number = -1, height: number = -1): number {
            width = width < 0 ? this.sideSize : width;
            height = height < 0 ? this.sideSize : height;

            var heightMapX = (((position.x + width / 2) / width) * (width - 1)) | 0;
            var heightMapY = ((1.0 - (position.z + height / 2) / height) * (height - 1)) | 0;

            return (heightMapX + heightMapY * height);
        }

        private CanPositionedModelOn(position: BABYLON.Vector3, index: number, mapElementType: MapElement.MapElementType): boolean {
            // TODO: implement this!
            // If already in used NO
            // Basic rules. more to be enforced in server side???????

            // If under water NO
            if (this.GetPositonHeight(new BABYLON.Vector2(position.x, position.z)) < 0) {
                return false;
            }

            var cellType = this.mesh.getVerticesData("type", false)[index];
            console.log("cell type from vertices data: " + cellType);

            // If sloopy terain NO
            if (cellType % 10 == 1.0) {
                return false;
            }

            return true;
        }

        //TODO: move to better location
        private RandonIntegerNumber(min: number, max: number): number {
            if (min === max) {
                return (min);
            }

            var random = Math.random();

            return Math.round((random * (max - min)) + min);
        }

    }
}


text:
import * as React from 'react';
import { connect } from 'react-redux';
import { fetchEventStartAction } from './actions/fetchEvent';
import { EventViewPage } from './page';

const mapStateToProps = (state, ownProps) => ({
    eventId: Number(ownProps.params.id) || 0,
    event: state.event.view.event,
    eventErrors: state.event.view.eventErrors,
});

const mapDispatchToProps = (dispatch) => ({
    fetchEventById: (id) => dispatch(fetchEventStartAction(id)),
});

export const EventViewContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(EventViewPage);


text:
using System;
using System.Collections.Generic;
using System.Reflection;

using OpenMetaverse;

namespace OpenSim.Framework
{
    public class EstateBan
    {
        private uint m_estateID = 1;
        /// <summary>
        /// ID of the estate this ban limits access to.
        /// </summary>
        public uint EstateID
        {
            get
            {
                return m_estateID;
            }
            set
            {
                m_estateID = value;
            }
        }

        private UUID m_bannedUserID = UUID.Zero;
        /// <summary>
        /// ID of the banned user.
        /// </summary>
        public UUID BannedUserID
        {
            get
            {
                return m_bannedUserID;
            }
            set
            {
                m_bannedUserID = value;
            }
        }

        private string m_bannedHostAddress = string.Empty;
        /// <summary>
        /// IP address or domain name of the banned client.
        /// </summary>
        public string BannedHostAddress
        {
            get
            {
                return m_bannedHostAddress;
            }
            set
            {
                m_bannedHostAddress = value;
            }
        }

        private string m_bannedHostIPMask = string.Empty;
        /// <summary>
        /// IP address mask for banning group of client hosts.
        /// </summary>
        public string BannedHostIPMask
        {
           get
            {
                return m_bannedHostIPMask;
            }
            set
            {
                m_bannedHostIPMask = value;
            }
        }

        private string m_bannedHostNameMask = string.Empty;
        /// <summary>
        /// Domain name mask for banning group of client hosts.
        /// </summary>
        public string BannedHostNameMask
        {
            get
            {
                return m_bannedHostNameMask;
            }
            set
            {
                m_bannedHostNameMask = value;
            }
        }

        public EstateBan() { }

        public Dictionary<string, object> ToMap()
        {
            Dictionary<string, object> map = new Dictionary<string, object>();
            PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo p in properties)
                map[p.Name] = p.GetValue(this, null);

            return map;
        }

        public EstateBan(Dictionary<string, object> map)
        {
            foreach (KeyValuePair<string, object> kvp in map)
            {
                PropertyInfo p = this.GetType().GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance);
                if (p == null)
                    continue;
                object value = p.GetValue(this, null);
                if (value is String)
                    p.SetValue(this, map[p.Name], null);
                else if (value is UInt32)
                    p.SetValue(this, UInt32.Parse((string)map[p.Name]), null);
                else if (value is Boolean)
                    p.SetValue(this, Boolean.Parse((string)map[p.Name]), null);
                else if (value is UUID)
                    p.SetValue(this, UUID.Parse((string)map[p.Name]), null);
            }
        }

        /// <summary>
        ///  For debugging
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            Dictionary<string, object> map = ToMap();
            string result = string.Empty;
            foreach (KeyValuePair<string, object> kvp in map)
                result += string.Format("{0}: {1} {2}", kvp.Key, kvp.Value, Environment.NewLine);

            return result;
        }
    }
}


text:
<?php namespace Toyotadjakarta\SalesModule\Banner;

use Toyotadjakarta\SalesModule\Banner\Contract\BannerRepositoryInterface;
use Anomaly\Streams\Platform\Entry\EntryRepository;

class BannerRepository extends EntryRepository implements BannerRepositoryInterface
{

    /**
     * The entry model.
     *
     * @var BannerModel
     */
    protected $model;

    /**
     * Create a new BannerRepository instance.
     *
     * @param BannerModel $model
     */
    public function __construct(BannerModel $model)
    {
        $this->model = $model;
    }
}


text:
<?xml version="1.0"?>
<cd:ProductDefinition xmlns:cd="http://www.stcorp.nl/coda/definition/2008/07" id="L2__NO2___" format="hdf5" last-modified="2016-08-12">
</cd:ProductDefinition>


text:
import Immutable from 'immutable';
const initialState = new Immutable.List();

export default function reminders(state = initialState, action) {
  if (action.type === 'SET_REMINDERS') {
    return Immutable.fromJS(action.reminders);
  }
  return state;
}


text:
package com.abiquo.apiclient;

import static com.abiquo.apiclient.domain.ApiPath.DEVICETYPES_URL;
import static com.abiquo.apiclient.domain.ApiPath.HYPERVISORTYPES_URL;
import static com.google.common.base.Preconditions.checkNotNull;

import com.abiquo.server.core.cloud.DeviceTypeDto;
import com.abiquo.server.core.cloud.DeviceTypesDto;
import com.abiquo.server.core.cloud.HypervisorTypeDto;
import com.abiquo.server.core.cloud.HypervisorTypesDto;

public class ConfigApi
{
    private final RestClient client;

    // Package private constructor to be used only by the ApiClient
    ConfigApi(final RestClient client)
    {
        this.client = checkNotNull(client, "client cannot be null");
    }

    public HypervisorTypeDto getHypervisorType(final String type)
    {
        return client.get(String.format("%s/%s", HYPERVISORTYPES_URL, type),
            HypervisorTypeDto.MEDIA_TYPE, HypervisorTypeDto.class);
    }

    public Iterable<HypervisorTypeDto> getHypervisorTypes()
    {
        return client.list(HYPERVISORTYPES_URL, HypervisorTypesDto.MEDIA_TYPE,
            HypervisorTypesDto.class);
    }

    public DeviceTypeDto getDeviceType(final String type)
    {
        return client.get(String.format("%s/%s", DEVICETYPES_URL, type),
            DeviceTypeDto.MEDIA_TYPE, DeviceTypeDto.class);
    }

    public Iterable<DeviceTypeDto> getDeviceTypes()
    {
        return client.list(DEVICETYPES_URL, DeviceTypesDto.MEDIA_TYPE,
            DeviceTypesDto.class);
    }
}


text:
/**
 * string serialization
 */
tabaga.historyMaster = (function() {

	function splitStr(str) {
		return str.split('/');//decodeURIComponent(str).split(';');
	}

	function joinParts(parts) {
		return parts.join('/');
	}

	function parsePart(part) {
		var keyValueSplitIndex = part.indexOf(">");
		if (keyValueSplitIndex<1) {
			// key not found
			return null;
		}
		return {
			key: part.substring(0, keyValueSplitIndex),
			value: part.substring(keyValueSplitIndex+1, part.length)
		};
	}

	function toPart(entry) {
		return entry.key + ">" + entry.value;
	}

	return {

		getValue : function(key, str) {
			var parts = splitStr(str);
			for (var i = 0; i < parts.length; i++) {
				var part = parts[i];
				var entry = parsePart(part);
				if (entry && entry.key==key) {
					return entry.value;
				}
			}
			return null;
		},

		putValue : function(key, value, str) {
			//if(str.length==0) {
				//return toPart({key: key, value: value});
			//}

			var parts = splitStr(str);

			for (var i = 0; i < parts.length; i++) {
				var part = parts[i];
				var entry = parsePart(part);
				if (entry && entry.key==key) {
					// update
					entry.value = value;
					parts[i] = toPart(entry);
					return joinParts(parts);
				}
			}

			// put new
			parts.push(toPart({key: key, value: value}));
			return joinParts(parts);
		},

		removeValue : function(key, str) {
			var parts = splitStr(str);
			for (var i = 0; i < parts.length; i++) {
				var part = parts[i];
				var entry = parsePart(part);
				if (entry && entry.key==key) {
					// remove
					parts.splice(i, 1);
					return joinParts(parts);
				}
			}
			return str;
		}
	};
}());


text:
package com.wingjay.jayandroid.fastblur;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.wingjay.jayandroid.BaseActivity;
import com.wingjay.jayandroid.R;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by jay on 11/7/15.
 */
public class FastBlurActivity extends BaseActivity {

    @Bind(R.id.blur_factor)
    EditText blurFactorEditText;

    @Bind(R.id.fast_blur_btn)
    Button fastBlurBtn;

    @Bind(R.id.fast_blur_image)
    ImageView fastBlurImageView;

    @Bind(R.id.blur_image_view)
    BlurImageView blurImageView;

    @Bind(R.id.full_blur_image_view)
    BlurImageView fullBlurImageView;

    boolean alreadyCompelete = false;

    int[] mediumSmRes = {
            R.drawable.medium_sm_1,
            R.drawable.medium_sm_2,
            R.drawable.medium_sm_3,
            R.drawable.medium_sm_4
    };

    int[] mediumNmRes = {
            R.drawable.medium_nm_1,
            R.drawable.medium_nm_2,
            R.drawable.medium_nm_3,
            R.drawable.medium_nm_4
    };

    String[] mediumSmUrl = {
            "https://cdn-images-1.medium.com/freeze/max/60/1*cDmQ2XlMGowTZNIf4oOHjw.jpeg?q=20",
            "https://cdn-images-1.medium.com/freeze/max/60/1*hBp9i_LZHGwKfq7plvjWxQ.jpeg?q=20",
            "https://cdn-images-1.medium.com/freeze/max/30/1*yd_YDN3dVyrSp_o7YHOKPg.jpeg?q=20",
            "https://cdn-images-1.medium.com/freeze/max/60/1*hMQ9_nBW3LOHCk3rQSRSbw.jpeg?q=20"
    };

    String[] mediumNmUrl = {
            "https://cdn-images-1.medium.com/max/1600/1*cDmQ2XlMGowTZNIf4oOHjw.jpeg",
            "https://cdn-images-1.medium.com/max/2000/1*hBp9i_LZHGwKfq7plvjWxQ.jpeg",
            "https://cdn-images-1.medium.com/max/2000/1*yd_YDN3dVyrSp_o7YHOKPg.jpeg",
            "https://cdn-images-1.medium.com/max/2000/1*hMQ9_nBW3LOHCk3rQSRSbw.jpeg"
    };

    int currentIndex = 0;
    int getResIndex() {
        if (currentIndex > 3) {
            currentIndex = currentIndex - 4;
        }
        return currentIndex;
    }

    private Target blurTarget = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            startBlur(bitmap);
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fast_blur);

        // Go to layoutBlurActivity
        //startActivity(new Intent(this, LayoutBlurActivity.class));
    }

    @OnClick(R.id.fast_blur_btn)
    void doFastBlur() {
        if (!alreadyCompelete) {
            int blurFactor = getBlurFactor();
            fullBlurImageView.setBlurFactor(blurFactor);
            fullBlurImageView.setFullImageByUrl(mediumSmUrl[getResIndex()], mediumNmUrl[getResIndex()]);

            blurImageView.setBlurFactor(blurFactor);
            blurImageView.setBlurImageByUrl(mediumSmUrl[getResIndex()]);
            //Picasso.with(this).load(mediumSmUrl[getResIndex()]).into(blurTarget);
            alreadyCompelete = true;
        } else {
            //fastBlurImageView.setImageBitmap(null);
            blurImageView.clear();
            fullBlurImageView.clear();
            currentIndex++;
            alreadyCompelete = false;
        }
    }

    void startBlur(Bitmap needBlurBitmap) {
        fastBlurImageView.setImageBitmap(getBlurBitmap(needBlurBitmap));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadOriginImage();
            }
        }, 1000);
    }

    Bitmap getBlurBitmap(Bitmap loadedBitmap) {
        // make this bitmap mutable
        loadedBitmap = loadedBitmap.copy(loadedBitmap.getConfig(), true);
        return FastBlurUtil.doBlur(loadedBitmap, getBlurFactor(), true);
    }

    void loadOriginImage() {
        Picasso.with(FastBlurActivity.this).load(mediumNmUrl[getResIndex()]).placeholder(fastBlurImageView.getDrawable()).into(fastBlurImageView);
        currentIndex++;
        alreadyCompelete = true;
    }

    int getBlurFactor() {
        if (TextUtils.isEmpty(blurFactorEditText.getText())) {
            return 8;
        }
        return Integer.parseInt(blurFactorEditText.getText().toString());
    }

    @Override
    protected void onDestroy() {
        //Picasso.with(this).cancelRequest(blurTarget);
        blurImageView.cancelImageLoadForSafty();
        fullBlurImageView.cancelImageLoadForSafty();
        super.onDestroy();
    }
}