text:
Configuration is done via ENV variables:
* `ETCD_SOURCE` - URL of source Etcd server (defaults to `http://127.0.0.1:2379`)
* `ETCD_DESTINATION` - URL of destination Etcd server (defaults to `http://127.0.0.1:2379`)
* `KEY` - starting point from which to sync (defaults to `/`)

## Running in Docker
A prebuild image is provided in the Docker Hub: [olivinelabs/etcd-sync](https://hub.docker.com/r/olivinelabs/etcd-sync/)
```
docker run -d \
  -e ETCD_SOURCE="http://<source>:2379" \
  -e ETCD_DESTINATION="http://<dest>:2379" \
  olivinelabs/etcd-sync
```

## Running locally
You need lua 5.1 and luarocks
```
luarocks make
ETCD_SOURCE="<source>" ETCD_DESTINATION="<dest>" KEY="/" lua etcd-sync/init.lua
```


text:
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::thread;
use std::sync::mpsc::channel;

/// Compute the frequency of each letter (technically of each unicode codepoint) using the given
/// number of worker threads.
pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap<char, usize> {
    assert!(num_workers > 0);
    let part_size_floor = texts.len() / num_workers;
    let rem = texts.len() % num_workers;
    let part_size = if rem > 0 { part_size_floor + 1 } else { part_size_floor };
    let mut parts: Vec<Vec<String>> = Vec::with_capacity(part_size);
    for _ in 0 .. num_workers {
        parts.push(Vec::with_capacity(part_size));
    }
    let mut i = 0;
    for line in texts.iter() {
        // We'll need to clone those strings in order to satisfy some lifetime guarantees. Basically
        // it's hard for the system to be sure that the threads spawned don't outlive the strings.
        parts[i].push(line.to_string());
        i = (i + 1) % num_workers;
    }

    let (tx, rx) = channel();

    for part in parts {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send(count(part)).unwrap();
        });
    }

    let mut results: HashMap<char, usize> = HashMap::new();
    for _ in 0..num_workers {
        let part_results = rx.recv().unwrap();
        for (c, n) in part_results.into_iter() {
            match results.entry(c) {
                Entry::Vacant(view) => { view.insert(n); },
                Entry::Occupied(mut view) => {
                    *view.get_mut() += n;
                }
            }
        }
    }
    results
}

fn count(lines: Vec<String>) -> HashMap<char, usize> {
    let mut results: HashMap<char, usize> = HashMap::new();
    for line in lines.iter() {
        for c in line.chars() {
            if c.is_alphabetic() {
                match results.entry(c.to_lowercase().next().unwrap()) {
                    Entry::Vacant(view) => { view.insert(1); },
                    Entry::Occupied(mut view) => {
                        *view.get_mut() += 1;
                    }
                }
            }
        }
    }
    results
}

redpajama_set_name: RedPajamaGithub


text:
function MaterialComponentsSnippets() {
  'use strict';

  // Find all code snippet buttons.
  this.snippetButtons = document.querySelectorAll(
    '.snippet-caption .copy-to-clipboard-button');
  this.init();
}

/**
 * Initializes the MaterialComponentsSnippets components.
 */
MaterialComponentsSnippets.prototype.init = function() {
  'use strict';
  [].slice.call(this.snippetButtons).forEach(function(snippetButton) {
    snippetButton.addEventListener('mouseover',
      this.onMouseOverHandler(snippetButton));
    snippetButton.addEventListener('mouseout',
      this.onMouseOutHandler(snippetButton));
    snippetButton.addEventListener('mouseup',
      this.onMouseDownHandler(snippetButton));
    var clippy = snippetButton.querySelectorAll('.clippy');
    if (clippy.length > 0) {
      clippy[0].addEventListener('mouseover',
        this.onMouseOverHandler(snippetButton));
      clippy[0].addEventListener('mouseout',
        this.onMouseOutHandler(snippetButton));
      clippy[0].addEventListener('mouseup',
        this.onMouseDownHandler(snippetButton));
    }
  }, this);
};

/**
 * Store strings for class names defined by this component that are used in
 * JavaScript. This allows us to simply change it in one place should we
 * decide to modify at a later date.
 * @enum {string}
 * @private
 */
MaterialComponentsSnippets.prototype.CssClasses_ = {
  HIGHLIGHTED: 'highlighted',
  COPIED: 'copied'
};

/**
 * Gets the <code> element that is referenced but the given button.
 * @param  {HTMLElement} button The snippet copy button
 * @return {HTMLElement} the code element referenced by the button
 */
MaterialComponentsSnippets.prototype.getCodeElement = function(button) {
  'use strict';

  var href = button.getAttribute('href');
  if (href && href.indexOf('#') >= 0) {
    return document.getElementById(href.split('#')[1]);
  }
  return null;
};

/**
 * Returns a mouseDownHandler for a snippet copy button.
 * @param  {HTMLElement} button the snippet copy button
 * @return {function} the click handler
 */
MaterialComponentsSnippets.prototype.onMouseDownHandler = function(button) {
  'use strict';

  var ctx = this;
  return function() {
    var code = ctx.getCodeElement(button);
    if (code) {
      code.classList.add(ctx.CssClasses_.COPIED);
    }
  };
};

/**
 * Returns a mouseOverHandler for a snippet copy button.
 * @param  {HTMLElement} button the snippet copy button
 * @return {function} the click handler
 */
MaterialComponentsSnippets.prototype.onMouseOverHandler = function(button) {
  'use strict';

  var ctx = this;
  return function() {
    var code = ctx.getCodeElement(button);
    if (code) {
      code.classList.add(ctx.CssClasses_.HIGHLIGHTED);
    }
  };
};

/**
 * Returns a mouseOutHandler for a snippet copy button.
 * @param  {HTMLElement} button the snippet copy button
 * @return {function} the click handler
 */
MaterialComponentsSnippets.prototype.onMouseOutHandler = function(button) {
  'use strict';

  var ctx = this;
  return function() {
    var code = ctx.getCodeElement(button);
    if (code) {
      code.classList.remove(ctx.CssClasses_.HIGHLIGHTED);
      code.classList.remove(ctx.CssClasses_.COPIED);
    }
  };
};

window.addEventListener('load', function() {
  'use strict';

  // Handle the case where Flash is not available.
  if (swfobject && !swfobject.hasFlashPlayerVersion('9.0.0')) {
    document.body.classList.add('no-flash');
  }
  new MaterialComponentsSnippets();
});


text:
module ActionView
  # This class defines the interface for a renderer. Each class that
  # subclasses +AbstractRenderer+ is used by the base +Renderer+ class to
  # render a specific type of object.
  #
  # The base +Renderer+ class uses its +render+ method to delegate to the
  # renderers. These currently consist of
  #
  #   PartialRenderer - Used for rendering partials
  #   TemplateRenderer - Used for rendering other types of templates
  #   StreamingTemplateRenderer - Used for streaming
  #
  # Whenever the +render+ method is called on the base +Renderer+ class, a new
  # renderer object of the correct type is created, and the +render+ method on
  # that new object is called in turn. This abstracts the setup and rendering
  # into a separate classes for partials and templates.
  class AbstractRenderer #:nodoc:
    delegate :find_template, :template_exists?, :with_fallbacks, :with_layout_format, :formats, :to => :@lookup_context

    def initialize(lookup_context)
      @lookup_context = lookup_context
    end

    def render
      raise NotImplementedError
    end

    protected

    def extract_details(options)
      @lookup_context.registered_details.each_with_object({}) do |key, details|
        next unless value = options[key]
        details[key] = Array(value)
      end
    end

    def instrument(name, options={})
      ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
    end

    def prepend_formats(formats)
      formats = Array(formats)
      return if formats.empty? || @lookup_context.html_fallback_for_js
      @lookup_context.formats = formats | @lookup_context.formats
    end
  end
end


text:
<?php
/**
 * Configuration File for BridgeMon
 *
 * This file has the following configurations:
 *
 *  Oracle SQL Connection info
 *  Debug Mode
 *
 */

 // ** Oracle SQL settings ********** //

 /** Oracle SQL Connection Info */
 define('DB_CONNECTION', 'localhost/orcl');

 /** Oracle SQL Database Username */
 define('DB_USER', 'USER');

 /** Oracle SQL Database Password */
 define('DB_PASSWORD', 'PASSWORD');

 // ** Debugging Settings ********** //

 /** Set Debug mode */
 define('DEBUG_MODE', true);

 /* That's all you need to edit ... stop editing beyond this point! */

 /** Absolute path for the site */
 if ( !defined('ABS_PATH') )
     define('ABS_PATH', dirname(__FILE__) . '/');


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor

Interface Summary

Interface
Description

Initializor<T>

Class Summary

Class
Description

AbstractCollectionInitializor<T>

ArrayCollectionInitializor

BasicCollectionInitializor<T extends Collection>

ListCollectionInitializor

MapCollectionInitializor<T extends Map>

SortedMapCollectionInitializor

SortedSetCollectionInitializor

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
<?php

Yii::import('booster.widgets.TbWidget');
/**
 * Bootstrap button widget.
 *
 * @see http://getbootstrap.com/css/#buttons
 *
 * @package booster.widgets.forms.buttons
 */
class TbButton extends TbWidget {

	// Button callback types.
	const BUTTON_LINK = 'link';
	const BUTTON_BUTTON = 'button';
	const BUTTON_SUBMIT = 'submit';
	const BUTTON_SUBMITLINK = 'submitLink';
	const BUTTON_RESET = 'reset';
	const BUTTON_AJAXLINK = 'ajaxLink';
	const BUTTON_AJAXBUTTON = 'ajaxButton';
	const BUTTON_AJAXSUBMIT = 'ajaxSubmit';
	const BUTTON_INPUTBUTTON = 'inputButton';
	const BUTTON_INPUTSUBMIT = 'inputSubmit';
	const BUTTON_TOGGLE_RADIO = 'radio';
	const BUTTON_TOGGLE_CHECKBOX = 'checkbox';

	const CTX_LINK = 'link';
	const CTX_LINK_CLASS = 'link';

	// Button sizes.
	const SIZE_LARGE = 'large';
	const SIZE_DEFAULT = 'default';
	const SIZE_SMALL = 'small';
	const SIZE_EXTRA_SMALL = 'extra_small';

	protected static $sizeClasses = array(
		self::SIZE_LARGE => 'btn-lg',
		self::SIZE_DEFAULT => '',
		self::SIZE_SMALL => 'btn-sm',
		self::SIZE_EXTRA_SMALL => 'btn-xs',
	);

	/**
	 * @var string the button callback types.
	 * Valid values are 'link', 'button', 'submit', 'submitLink', 'reset', 'ajaxLink', 'ajaxButton' and 'ajaxSubmit'.
	 */
	public $buttonType = self::BUTTON_BUTTON;

	/**
	 * @var string the button size.
	 * Valid values are 'large', 'small' and 'mini'.
	 */
	public $size;

	/**
	 * @var string the button icon, e.g. 'ok' or 'remove white'.
	 */
	public $icon;

	/**
	 * @var string the button label.
	 */
	public $label;

	/**
	 * @var string the button URL.
	 */
	public $url;

	/**
	 * @var boolean indicates whether the button should span the full width of the a parent.
	 */
	public $block = false;

	/**
	 * @var boolean indicates whether the button is active.
	 */
	public $active = false;

	/**
	 * @var boolean indicates whether the button is disabled.
	 */
	public $disabled = false;

	/**
	 * @var boolean indicates whether to encode the label.
	 */
	public $encodeLabel = true;

	/**
	 * @var boolean indicates whether to enable toggle.
	 */
	public $toggle;

	/**
	 * @var string the loading text.
	 */
	public $loadingText;

	/**
	 * @var string the complete text.
	 */
	public $completeText;

	/**
	 * @var array the dropdown button items.
	 */
	public $items;

	/**
	 * @var array the HTML attributes for the widget container.
	 */
	public $htmlOptions = array();

	/**
	 * @var array the button ajax options (used by 'ajaxLink' and 'ajaxButton').
	 */
	public $ajaxOptions = array();

	/**
	 * @var array the HTML attributes for the dropdown menu.
	 * @since 0.9.11
	 */
	public $dropdownOptions = array();

	/**
	 * @var bool whether the button is visible or not
	 * @since 0.9.11
	 */
	public $visible = true;

    /**
     * Tooltip for button
     * @var bool
     * @since 2.1.0
     */
    public $tooltip = false;

    /**
     * Tooltip options
     * @var array
     * @since 2.1.0
     */
    public $tooltipOptions = array();

	/**
	 *### .init()
	 *
	 * Initializes the widget.
	 */
	public function init() {

		if (false === $this->visible) {
			return;
		}

		$classes = array('btn');

		if ($this->isValidContext()) {
			$classes[] = 'btn-' . $this->getContextClass();
		}

		if($this->buttonType == self::BUTTON_LINK) {
			$classes[] = 'btn-link';
		}

		$validSizes = array(
			self::SIZE_LARGE,
			self::SIZE_DEFAULT,
			self::SIZE_SMALL,
			self::SIZE_EXTRA_SMALL
		);

		if (isset($this->size) && in_array($this->size, $validSizes)) {
			$classes[] = self::$sizeClasses[$this->size];
		}

		if ($this->block) {
			$classes[] = 'btn-block';
		}

		if ($this->active) {
			$classes[] = 'active';
		}

		if ($this->disabled) {
			$disableTypes = array(
				self::BUTTON_BUTTON,
				self::BUTTON_SUBMIT,
				self::BUTTON_RESET,
				self::BUTTON_AJAXBUTTON,
				self::BUTTON_AJAXSUBMIT,
				self::BUTTON_INPUTBUTTON,
				self::BUTTON_INPUTSUBMIT
			);

			if (in_array($this->buttonType, $disableTypes)) {
				$this->htmlOptions['disabled'] = 'disabled';
			}

			$classes[] = 'disabled';
		}

		if (!isset($this->url) && isset($this->htmlOptions['href'])) {
			$this->url = $this->htmlOptions['href'];
			unset($this->htmlOptions['href']);
		}

		if ($this->encodeLabel) {
			$this->label = CHtml::encode($this->label);
		}

		if ($this->hasDropdown()) {
			if (!isset($this->url)) {
				$this->url = '#';
			}

			$classes[] = 'dropdown-toggle';
			$this->label .= ' ';
			$this->htmlOptions['data-toggle'] = 'dropdown';
		}

		if (!empty($classes)) {
			$classes = implode(' ', $classes);
			if (isset($this->htmlOptions['class'])) {
				$this->htmlOptions['class'] .= ' ' . $classes;
			} else {
				$this->htmlOptions['class'] = $classes;
			}
		}

		if (isset($this->icon)) { // no need for implode as newglyphicon only supports one icon
			if (strpos($this->icon, 'icon') === false && strpos($this->icon, 'fa') === false) {
				$this->icon = 'glyphicon glyphicon-' . $this->icon;
				$this->label = 'icon . '"> ' . $this->label;
			} else { // to support font awesome icons
				$this->label = 'icon . '"> ' . $this->label;
			}
		}

		if (!isset($this->htmlOptions['id'])) {
			$this->htmlOptions['id'] = $this->getId();
		}

		if (isset($this->toggle)) {
			$this->htmlOptions['data-toggle'] = 'button';
		}

		if (isset($this->loadingText)) {
			$this->htmlOptions['data-loading-text'] = $this->loadingText;
		}

		if (isset($this->completeText)) {
			$this->htmlOptions['data-complete-text'] = $this->completeText;
		}

        if (!empty($this->tooltip) && !$this->toggle) {
            if (!is_array($this->tooltipOptions)) {
                $this->tooltipOptions = array();
            }

            $this->htmlOptions['data-toggle'] = 'tooltip';
            foreach ($this->tooltipOptions as $key => $value) {
                $this->htmlOptions['data-' . $key] = $value;
            }

            /**
             * Encode delay option
             * @link http://getbootstrap.com/2.3.2/javascript.html#tooltips
             */
            if (isset($this->htmlOptions['data-delay']) && is_array($this->htmlOptions['data-delay'])) {
                $this->htmlOptions['data-delay'] = CJSON::encode($this->htmlOptions['data-delay']);
            }
        }
	}

	/**
	 *### .run()
	 *
	 * Runs the widget.
	 */
	public function run() {
		if (false === $this->visible) {
			return;
		}

		// TODO: I think we have to drop this -allowing button to has items- it is the same as TbButtonGroup with bugs!
		if ($this->hasDropdown()) {
			echo '
';
			echo $this->createButton();

			$this->controller->widget(
				'booster.widgets.TbDropdown',
				array(
					'encodeLabel' => $this->encodeLabel,
					'items' => $this->items,
					'htmlOptions' => $this->dropdownOptions,
					'id' => isset($this->dropdownOptions['id']) ? $this->dropdownOptions['id'] : null,
				)
			);
			echo '
';
		} else {
			echo $this->createButton();
		}
	}

	/**
	 *### .createButton()
	 *
	 * Creates the button element.
	 *
	 * @return string the created button.
	 */
	protected function createButton() {

		switch ($this->buttonType) {
			case self::BUTTON_LINK:
				return CHtml::link($this->label, $this->url, $this->htmlOptions);

			case self::BUTTON_SUBMIT:
				$this->htmlOptions['type'] = 'submit';
				return CHtml::htmlButton($this->label, $this->htmlOptions);

			case self::BUTTON_RESET:
				$this->htmlOptions['type'] = 'reset';
				return CHtml::htmlButton($this->label, $this->htmlOptions);

			case self::BUTTON_SUBMITLINK:
				return CHtml::linkButton($this->label, $this->htmlOptions);

			case self::BUTTON_AJAXLINK:
				return CHtml::ajaxLink($this->label, $this->url, $this->ajaxOptions, $this->htmlOptions);

			case self::BUTTON_AJAXBUTTON:
				$this->ajaxOptions['url'] = $this->url;
				$this->htmlOptions['ajax'] = $this->ajaxOptions;
				return CHtml::htmlButton($this->label, $this->htmlOptions);

			case self::BUTTON_AJAXSUBMIT:
				$this->ajaxOptions['type'] = isset($this->ajaxOptions['type']) ? $this->ajaxOptions['type'] : 'POST';
				$this->ajaxOptions['url'] = $this->url;
				$this->htmlOptions['type'] = 'submit';
				$this->htmlOptions['ajax'] = $this->ajaxOptions;
				return CHtml::htmlButton($this->label, $this->htmlOptions);

			case self::BUTTON_INPUTBUTTON:
				return CHtml::button($this->label, $this->htmlOptions);

			case self::BUTTON_INPUTSUBMIT:
				$this->htmlOptions['type'] = 'submit';
				return CHtml::button($this->label, $this->htmlOptions);

			case self::BUTTON_TOGGLE_RADIO:
				return $this->createToggleButton('radio');

			case self::BUTTON_TOGGLE_CHECKBOX:
				return $this->createToggleButton('checkbox');

			default:
				return CHtml::htmlButton($this->label, $this->htmlOptions);
		}
	}

	/**
	 * @param string $toggleType
	 */
	protected function createToggleButton($toggleType) {

		$html = '';
		$html .= CHtml::openTag('label', $this->htmlOptions);
		$html .= "<input type='{$toggleType}' name='{$this->id}_options' id='option_{$this->id}'> {$this->label}";
		$html .= CHtml::closeTag('label');

		return $html;
	}

	/**
	 *### .hasDropdown()
	 *
	 * Returns whether the button has a dropdown.
	 *
	 * @return bool the result.
	 */
	protected function hasDropdown() {

		return isset($this->items) && !empty($this->items);
	}
}


text:
import botocore.exceptions

class Boto3OutputStore(object):
    def __init__(self, contexts, pretty_printer):
        self._contexts = contexts
        self._outputs = dict()
        self._ppt = pretty_printer

    def collect_stack_outputs(self, *attributes):
        for attribute in attributes:
            try:
                qualified_name, attribute_name = attribute.rsplit('.', 1)
            except Exception as e:
                self._ppt.secho(
                    'Invalid Config Reference %s' % attribute,
                    color='yellow')
                raise e

            for context in self._contexts:
                if context.stack_key != qualified_name:
                    continue

                try:
                    cfn = context.session.resource('cloudformation')

                    stack_name = context.parameters['StackName']
                    stack = cfn.Stack(stack_name)

                    stack.load()
                    status = stack.stack_status
                    if status not in (
                            'CREATE_COMPLETE',
                            'ROLLBACK_COMPLETE',
                            'UPDATE_COMPLETE',
                            'UPDATE_ROLLBACK_COMPLETE'):
                        continue
                except Exception as e:
                    self._ppt.secho(
                        'Collect Outputs: Unable to access outputs from %s' % qualified_name,
                        color='yellow')
                    raise e

                if stack.outputs:
                    outputs = dict(
                        map(lambda o: (
                            '.'.join((context.stack_key, o['OutputKey'])),
                            o['OutputValue']),
                            stack.outputs))
                    if attribute not in outputs:
                        raise RuntimeError('Collect Outputs: Attribute %s not found' % attribute)

                    self._ppt.secho(
                        'Collected outputs from %s' % qualified_name, color='yellow')
                    self._outputs.update(outputs)

    def get_outputs(self):
        return self._outputs


text:
(function($){

    window.Edgar = window.Edgar || {};
    Edgar.YearSlider = function(options) {
        //options
        options = $.extend({
            containerElem: null,        // REQUIRED: the element that contains all the options
            loadingContainerElem: null, // REQUIRED: a sibling element to containerElem that contains a loading screen
            sliderElem: null,           // REQUIRED: empty div that will be converted into a slider
            scenarioElemName: null,     // REQUIRED: name of <radio> elements for selecting an emission scenario
            map: null,                  // REQUIRED: the open layers map object
            loadingBar: null,           // Will turn this empty div into a progress bar for loading
            yearLabelElem: null,        // Will change the inner text of this elem when the year changes
            defaultYear: 2015
        }, options);

        this.MIN_YEAR = 2015;
        this.MAX_YEAR = 2085;

        //member vars (private)
        this._year = parseInt(options.defaultYear);
        this._layersByYear = {};
        this._map = options.map;
        this._speciesId = null;
        this._$container = $(options.containerElem);
        this._$loadingContainer = $(options.loadingContainerElem);
        this._$slider = $(options.sliderElem);
        this._$scenarios = $('input[name=' + options.scenarioElemName + ']');
        this._$loadingBar = (options.loadingBar === null ? null : $(options.loadingBar));
        this._$yearLabel = (options.yearLabelElem === null ? null : $(options.yearLabelElem));
        this._numReloadSuspensions = 0;
        this._needsReload = false;
        var self = this;

        //initial setup (runs once upon object creation)
        this._init = function(){
            self._map.events.register('movestart', this, function(){
                self._suspendReloadOfLayers();
            });
            self._map.events.register('moveend', this, function(){
                //reload layers after a delay to stop uneccessary requests to the map server
                setTimeout(function(){
                    self._resumeReloadOfLayers();
                    self._reloadLayers();
                }, 2000);
            });

            //init slider
            self._$slider.slider({
                min: self.MIN_YEAR,
                max: self.MAX_YEAR,
                value: self._year,
                step: 10,
                change: function(event, ui){
                    self.setYear(ui.value);
                },
                slide: function(event, ui){
                    self.setYear(ui.value);
                }
            });

            //init loading bar
            if(self._$loadingBar) self._$loadingBar.progressbar({value:0});

            //init year label
            if(self._$yearLabel) {
                var year = self._year;
                self._year = undefined;
                self.setYear(year);
            }

            //init scenarios
            self._$scenarios.change(function(){
                self._reloadLayers();
            });
        };

        this.setYear = function(year){
            year = parseInt(year);
            if(this._year == year) return;

            this._year = year;
            this._$slider.slider("value", this._year);

            if(this._year > 2050){
                //TODO: change site logo to cyborg raven
            }

            if(this._$yearLabel){
                this._$yearLabel.text(''+this._year);

                var $thumb = this._$slider.slider("widget").find('a');
                var left = $thumb.position().left + this._$slider.position().left - ($thumb.width() / 2) - this._$yearLabel.width();
                this._$yearLabel.css('left', left + "px");
            }

            this._setLayerOpacities();
        }

        /*!
        *  Disable by setting species id to null
        */
        this.setSpeciesId = function(speciesId){
            if(speciesId !== null)
                speciesId = parseInt(speciesId);

            if(this._speciesId === speciesId) return;

            this._speciesId = speciesId;
            this._reloadLayers();
        }

        this.playAnimation = function(){
            var self = this;

            // switch the step to 1 to get smooth transitions between years
            self._$slider.slider('option', 'step', 1);

            var dummyElem = $('

').css('height', this.MIN_YEAR);
            dummyElem.animate({height: this.MAX_YEAR}, {
                duration: 5000,
                easing: 'linear',
                step: function(year){
                    self.setYear(year);
                },
                complete: function() {
                    self._$slider.slider('option', 'step', 10);
                }
            });
        }

        this._reloadLayers = function(){
            //check if reload is suspended
            if(this._numReloadSuspensions > 0){
                this._needsReload = true;
                return;
            } else {
                this._needsReload = false;
            }

            this._removeAllLayers();

            if(this._speciesId){
                this._beginLoading();
                this._addLayerForYear(2015);
                this._addLayerForYear(2025);
                this._addLayerForYear(2035);
                this._addLayerForYear(2045);
                this._addLayerForYear(2055);
                this._addLayerForYear(2065);
                this._addLayerForYear(2075);
                this._addLayerForYear(2085);
            }
        }

        this._suspendReloadOfLayers = function(){
            this._numReloadSuspensions += 1;
        }

        this._resumeReloadOfLayers = function(){
            this._numReloadSuspensions -= 1;
        }

        this._addLayerForYear = function(year){
            scenario = '' + self._$scenarios.filter(':checked').val();
            var mapPath = Edgar.util.mappath(this._speciesId, year, scenario);

            var layer = new OpenLayers.Layer.WMS(
                "Climate Suitability in " + year,
                mapToolBaseUrl + 'wms_with_auto_determined_threshold.php',
                {
                    MODE: 'map',
                    MAP: 'edgar_master.map',
                    DATA: mapPath,
                    SPECIESID: this._speciesId,
                    REASPECT: 'true',
                    TRANSPARENT: 'true'
                },
                {
                    isBaseLayer: false,
                    transitionEffect: 'resize',
                    displayInLayerSwitcher: false,
                    singleTile: true,
                    ratio: 1.5
                }
            );

            layer.events.register('loadend', this, this._layerDidLoad);
            layer.setOpacity(0);

            this._layersByYear[year] = layer;
            this._map.addLayer(layer);
        }

        this._removeAllLayers = function(){
            var self = this;
            $.each(this._layersByYear, function(year, layer){
                layer.events.unregister('loadend', self, self._layerDidLoad);
                self._map.removeLayer(layer);
            });
            this._layersByYear = {};
        }

        this._layerDidLoad = function(event){
            var numLoaded = 0;
            var numTotal = 0;
            $.each(this._layersByYear, function(year, layer){
                numTotal += 1;
                if(layer.numLoadingTiles == 0) numLoaded += 1;
            });

            this._updateLoading(numLoaded/numTotal);

            if(numLoaded == numTotal)
                this._endLoading();
        }

        this._beginLoading = function(){
            this._updateLoading(0.05);

            var self = this;
            this._$container.stop().slideUp('fast', function(){
                self._$loadingContainer.stop().slideDown('fast');
            });
        }

        this._updateLoading = function(percentDone){
            this._$loadingBar.progressbar('value', percentDone*100);
        }

        this._endLoading = function(){
            this._setLayerOpacities();
            this.setYear(options.defaultYear);

            var self = this;
            this._$loadingContainer.stop().slideUp('fast', function(){
                self._$container.stop().slideDown('fast').effect('hilight', 'slow');
            });
        }

        this._setLayerOpacities = function(){
            if(!this._speciesId) return;

            var currentYear = this._year;
            var sortedYears = $.map(this._layersByYear, function(layer, year){ return parseInt(year); });
            sortedYears.sort();

            //find two closest years to interpolate between
            var lowerYear = sortedYears[0];
            var upperYear = null;
            $.each(sortedYears, function(idx, year){
                if(year >= currentYear){
                    upperYear = year;
                    return false; //stops iteration
                } else {
                    lowerYear = year;
                }
            });

            //if exactly on a year, no interpolation necessary
            if(upperYear == currentYear){
                $.each(this._layersByYear, function(year, layer){
                    layer.setOpacity((year == currentYear ? 1 : 0));
                });
            } else {
                //else, interpolate
                $.each(this._layersByYear, function(year, layer){
                    var interp = (currentYear - lowerYear) / (upperYear - lowerYear);
                    var opacity = 0;
                    if(year == upperYear){
                        opacity = interp;
                    } else if(year == lowerYear){
                        opacity = 1 - interp;
                    }
                    layer.setOpacity(opacity);
                });
            }
        }

        //do init last
        $(document).ready(function(){ self._init(); })
    };

})(jQuery);


text:
package com.pineone.icbms.sda.sch.comm;

import java.sql.SQLNonTransientConnectionException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.pineone.icbms.sda.comm.sch.dto.SchDTO;
import com.pineone.icbms.sda.comm.util.Utils;
import com.pineone.icbms.sda.sch.service.SchService;

/**
 * 스케줄러 서비스의 메인 클래스
 */
@Service
public class SchedulerMainService implements ApplicationContextAware {
	private static ApplicationContext context;
	private SchedulerFactory schedulerFactory = null;
	private Scheduler scheduler = null;
	private JobDetail jobDetail = null;
	private CronTrigger trigger = null;
	private SchDTO[] schDTO;

	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 스케줄러 초기화
	 * @throws Exception
	 * @return void
	 */
	public void JobInit() throws Exception {
		try {
			if (scheduler != null && scheduler.isStarted())
				return;

			schedulerFactory = new StdSchedulerFactory();
			scheduler = schedulerFactory.getScheduler();
			scheduler.start();
			JobRegist();
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 스케줄러 인스턴스 얻기
	 * @throws Exception
	 * @return Scheduler
	 */
	public Scheduler getScheduler() throws Exception {

		if (scheduler == null) {
			schedulerFactory = new StdSchedulerFactory();
			scheduler = schedulerFactory.getScheduler();
		}
		return scheduler;
	}

	/**
	 * 스케줄러 Job등록
	 * @throws Exception
	 * @return void
	 */
	public void JobRegist() throws Exception {
		Class<?> c = null;
		// 등록할 스케줄 정보 설정
		setSchList();

		for (int j = 0; j < schDTO.length; j++) {
			try {
				c = Class.forName(schDTO[j].getTask_class());

				jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c);
				trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());

				trigger.setCronExpression(schDTO[j].getTask_expression());
				scheduler.scheduleJob(jobDetail, trigger);
			} catch (Exception e) {
				throw e;
			}
		}
	}

	/**
	 * 스케줄러 목록
	 * @throws Exception
	 * @return void
	 */
	public void statusSchList() throws Exception {
		setSchList();
		StringBuffer sb = new StringBuffer();
		for (int j = 0; j < schDTO.length; j++) {
			sb.append("trigger[");
			sb.append(j);
			sb.append("](group_id:");
			sb.append(schDTO[j].getTask_group_id());
			sb.append(",");
			sb.append(" task_id:");
			sb.append(schDTO[j].getTask_id());
			sb.append(") : ");
			sb.append(scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()));
			sb.append(" (not initiated:-1, running/standby:0, paused:1)");
			sb.append(Utils.NEW_LINE);
		}

		log.debug(sb.toString());
	}

	/**
	 * 스케줄러 상태값 목록
	 * @throws Exception
	 * @return String
	 */
	public String getStatusList() throws Exception {
		StringBuffer sb = new StringBuffer();
		setSchList();

		for (int j = 0; j < schDTO.length; j++) {
			sb.append("trigger[");
			sb.append(j);
			sb.append("](group_id:");
			sb.append(schDTO[j].getTask_group_id());
			sb.append(",");
			sb.append(" task_id:");
			sb.append(schDTO[j].getTask_id());
			sb.append(") : ");
			sb.append(scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()));
			sb.append(" (not initiated:-1, running/standby:0, paused:1)");
			if ((j + 1) != schDTO.length) {
				sb.append("<br>");
			}
		}
		return sb.toString();
	}

	/**
	 * 스케줄 pause
	 * @throws Exception
	 * @return void
	 */
	public void pauseSch() throws Exception {
		setSchList();
		for (int j = 0; j < schDTO.length; j++) {
			scheduler.pauseJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
			log.debug("[" + j + "] paused......");
		}
	}

	// resume
	public void resumeSch() throws Exception {
		setSchList();
		for (int j = 0; j < schDTO.length; j++) {
			scheduler.resumeJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
			log.debug("[" + j + "] resumed......");
		}
	}

	/**
	 * 스케줄러 standby상태로 전환
	 * @throws Exception
	 * @return void
	 */
	public void standbySch() throws Exception {
		setSchList();
		scheduler.standby();
		log.debug("scheduler is in state of standby ......");
	}

	/**
	 * 스케줄러 시작
	 * @throws Exception
	 * @return void
	 */
	public void startSch() throws Exception {
		setSchList();
		scheduler.start();
		log.debug("scheduler is in state of start ......");
	}

	/**
	 * 스케줄러 멈춤
	 * @throws Exception
	 * @return void
	 */
	public void shutdown() throws Exception {
		scheduler.shutdown();
	}

	/**
	 * 스케줄 목록 설정
	 * @throws Exception
	 * @return void
	 */
	private void setSchList() throws Exception {
		if (schDTO != null)
			return;

		// 스케줄정보 가져오기
		List<SchDTO> schList = new ArrayList<SchDTO>();

		try {
			SchService schService = getContext().getBean(SchService.class);
			schList = schService.selectList();
		} catch (SQLNonTransientConnectionException e) {
			System.gc();
		} catch (Exception e) {
			throw e;
		}

		schDTO = new SchDTO[schList.size()];

		for (int i = 0; i < schList.size(); i++) {
			schDTO[i] = schList.get(i);
			log.debug("schDTO[" + i + "] in SchedulerMainService================>" + schDTO[i].toString());
		}
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	public static ApplicationContext getContext() {
		return context;
	}

}


text:
//===--- SerializeDoc.cpp - Read and write swiftdoc files -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "DocFormat.h"
#include "Serialization.h"

#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/Module.h"
#include "swift/AST/USRGeneration.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/YAMLParser.h"

#include <vector>

using namespace swift;
using namespace swift::serialization;
using namespace llvm::support;
using swift::version::Version;
using llvm::BCBlockRAII;

using FileNameToGroupNameMap = llvm::StringMap<std::string>;
using pFileNameToGroupNameMap = std::unique_ptr<FileNameToGroupNameMap>;

namespace {
class YamlGroupInputParser {
  ASTContext &Ctx;
  StringRef RecordPath;
  static constexpr const char * const Separator = "/";

  // FIXME: This isn't thread-safe.
  static llvm::StringMap<pFileNameToGroupNameMap> AllMaps;

  bool parseRoot(FileNameToGroupNameMap &Map, llvm::yaml::Node *Root,
                 StringRef ParentName) {
    auto *MapNode = dyn_cast<llvm::yaml::MappingNode>(Root);
    if (!MapNode) {
      return true;
    }
    for (auto &Pair : *MapNode) {
      auto *Key = dyn_cast_or_null<llvm::yaml::ScalarNode>(Pair.getKey());
      auto *Value = dyn_cast_or_null<llvm::yaml::SequenceNode>(Pair.getValue());

      if (!Key || !Value) {
        return true;
      }
      llvm::SmallString<16> GroupNameStorage;
      StringRef GroupName = Key->getValue(GroupNameStorage);
      std::string CombinedName;
      if (!ParentName.empty()) {
        CombinedName = (llvm::Twine(ParentName) + Separator + GroupName).str();
      } else {
        CombinedName = GroupName;
      }

      for (llvm::yaml::Node &Entry : *Value) {
        if (auto *FileEntry= dyn_cast<llvm::yaml::ScalarNode>(&Entry)) {
          llvm::SmallString<16> FileNameStorage;
          StringRef FileName = FileEntry->getValue(FileNameStorage);
          llvm::SmallString<32> GroupNameAndFileName;
          GroupNameAndFileName.append(CombinedName);
          GroupNameAndFileName.append(Separator);
          GroupNameAndFileName.append(llvm::sys::path::stem(FileName));
          Map[FileName] = GroupNameAndFileName.str();
        } else if (Entry.getType() == llvm::yaml::Node::NodeKind::NK_Mapping) {
          if (parseRoot(Map, &Entry, CombinedName))
            return true;
        } else
          return true;
      }
    }
    return false;
  }

public:
  YamlGroupInputParser(ASTContext &Ctx, StringRef RecordPath):
    Ctx(Ctx), RecordPath(RecordPath) {}

  FileNameToGroupNameMap* getParsedMap() {
    return AllMaps[RecordPath].get();
  }

  bool diagnoseGroupInfoFile(bool FileMissing = false) {
    Ctx.Diags.diagnose(SourceLoc(),
      FileMissing ? diag::cannot_find_group_info_file:
      diag::cannot_parse_group_info_file, RecordPath);
    return true;
  }

  // Parse the Yaml file that contains the group information.
  // True on failure; false on success.
  bool parse() {
    // If we have already parsed this group info file, return false;
    auto FindMap = AllMaps.find(RecordPath);
    if (FindMap != AllMaps.end())
      return false;

    auto Buffer = llvm::MemoryBuffer::getFile(RecordPath);
    if (!Buffer) {
      return diagnoseGroupInfoFile(/*Missing File*/true);
    }
    llvm::SourceMgr SM;
    llvm::yaml::Stream YAMLStream(Buffer.get()->getMemBufferRef(), SM);
    llvm::yaml::document_iterator I = YAMLStream.begin();
    if (I == YAMLStream.end()) {
      // Cannot parse correctly.
      return diagnoseGroupInfoFile();
    }
    llvm::yaml::Node *Root = I->getRoot();
    if (!Root) {
      // Cannot parse correctly.
      return diagnoseGroupInfoFile();
    }

    // The format is a map of ("group0" : ["file1", "file2"]), meaning all
    // symbols from file1 and file2 belong to "group0".
    auto *Map = dyn_cast<llvm::yaml::MappingNode>(Root);
    if (!Map) {
      return diagnoseGroupInfoFile();
    }
    pFileNameToGroupNameMap pMap(new FileNameToGroupNameMap());
    std::string Empty;
    if (parseRoot(*pMap, Root, Empty))
      return diagnoseGroupInfoFile();

    // Save the parsed map to the owner.
    AllMaps[RecordPath] = std::move(pMap);
    return false;
  }
};

llvm::StringMap<pFileNameToGroupNameMap> YamlGroupInputParser::AllMaps;

class DeclGroupNameContext {
  struct GroupNameCollector {
    static const StringLiteral NullGroupName;
    const bool Enable;
    GroupNameCollector(bool Enable) : Enable(Enable) {}
    virtual ~GroupNameCollector() = default;
    virtual StringRef getGroupNameInternal(const Decl *VD) = 0;
    StringRef getGroupName(const Decl *VD) {
      return Enable ? getGroupNameInternal(VD) : StringRef(NullGroupName);
    };
  };

  class GroupNameCollectorFromJson : public GroupNameCollector {
    StringRef RecordPath;
    FileNameToGroupNameMap* pMap = nullptr;
    ASTContext &Ctx;

  public:
    GroupNameCollectorFromJson(StringRef RecordPath, ASTContext &Ctx) :
      GroupNameCollector(!RecordPath.empty()), RecordPath(RecordPath),
      Ctx(Ctx) {}
    StringRef getGroupNameInternal(const Decl *VD) override {
      // We need the file path, so there has to be a location.
      if (VD->getLoc().isInvalid())
        return NullGroupName;
      auto PathOp = VD->getDeclContext()->getParentSourceFile()->getBufferID();
      if (!PathOp.hasValue())
        return NullGroupName;
      StringRef FullPath =
          Ctx.SourceMgr.getIdentifierForBuffer(PathOp.getValue());
      if (!pMap) {
        YamlGroupInputParser Parser(Ctx, RecordPath);
        if (!Parser.parse()) {

          // Get the file-name to group map if parsing correctly.
          pMap = Parser.getParsedMap();
        }
      }
      if (!pMap)
        return NullGroupName;
      StringRef FileName = llvm::sys::path::filename(FullPath);
      auto Found = pMap->find(FileName);
      if (Found == pMap->end()) {
        Ctx.Diags.diagnose(SourceLoc(), diag::error_no_group_info, FileName);
        return NullGroupName;
      }
      return Found->second;
    }
  };

  llvm::MapVector<StringRef, unsigned> Map;
  std::vector<StringRef> ViewBuffer;
  std::unique_ptr<GroupNameCollector> pNameCollector;

public:
  DeclGroupNameContext(StringRef RecordPath, ASTContext &Ctx) :
    pNameCollector(new GroupNameCollectorFromJson(RecordPath, Ctx)) {}
  uint32_t getGroupSequence(const Decl *VD) {
    return Map.insert(std::make_pair(pNameCollector->getGroupName(VD),
                                     Map.size())).first->second;
  }

  ArrayRef<StringRef> getOrderedGroupNames() {
    ViewBuffer.clear();
    for (auto It = Map.begin(); It != Map.end(); ++ It) {
      ViewBuffer.push_back(It->first);
    }
    return llvm::makeArrayRef(ViewBuffer);
  }

  bool isEnable() {
    return pNameCollector->Enable;
  }
};

const StringLiteral
DeclGroupNameContext::GroupNameCollector::NullGroupName = "";

struct DeclCommentTableData {
  StringRef Brief;
  RawComment Raw;
  uint32_t Group;
  uint32_t Order;
};

class DeclCommentTableInfo {
public:
  using key_type = StringRef;
  using key_type_ref = key_type;
  using data_type = DeclCommentTableData;
  using data_type_ref = const data_type &;
  using hash_value_type = uint32_t;
  using offset_type = unsigned;

  hash_value_type ComputeHash(key_type_ref key) {
    assert(!key.empty());
    // FIXME: DJB seed=0, audit whether the default seed could be used.
    return llvm::djbHash(key, 0);
  }

  std::pair<unsigned, unsigned>
  EmitKeyDataLength(raw_ostream &out, key_type_ref key, data_type_ref data) {
    uint32_t keyLength = key.size();
    const unsigned numLen = 4;

    // Data consists of brief comment length and brief comment text,
    uint32_t dataLength = numLen + data.Brief.size();
    // number of raw comments,
    dataLength += numLen;
    // for each raw comment: column number of the first line, length of each
    // raw comment and its text.
    for (auto C : data.Raw.Comments)
      dataLength += numLen + numLen + C.RawText.size();

    // Group Id.
    dataLength += numLen;

    // Source order.
    dataLength += numLen;
    endian::Writer writer(out, little);
    writer.write<uint32_t>(keyLength);
    writer.write<uint32_t>(dataLength);
    return { keyLength, dataLength };
  }

  void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
    out << key;
  }

  void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
                unsigned len) {
    endian::Writer writer(out, little);
    writer.write<uint32_t>(data.Brief.size());
    out << data.Brief;
    writer.write<uint32_t>(data.Raw.Comments.size());
    for (auto C : data.Raw.Comments) {
      writer.write<uint32_t>(C.StartColumn);
      writer.write<uint32_t>(C.RawText.size());
      out << C.RawText;
    }
    writer.write<uint32_t>(data.Group);
    writer.write<uint32_t>(data.Order);
  }
};

class DocSerializer : public SerializerBase {
public:
  using SerializerBase::SerializerBase;
  using SerializerBase::writeToStream;

  using SerializerBase::Out;
  using SerializerBase::M;
  using SerializerBase::SF;

  /// Writes the BLOCKINFO block for the module documentation file.
  void writeDocBlockInfoBlock() {
    BCBlockRAII restoreBlock(Out, llvm::bitc::BLOCKINFO_BLOCK_ID, 2);

    SmallVector<unsigned char, 64> nameBuffer;
#define BLOCK(X) emitBlockID(X ## _ID, #X, nameBuffer)
#define BLOCK_RECORD(K, X) emitRecordID(K::X, #X, nameBuffer)

    BLOCK(MODULE_DOC_BLOCK);

    BLOCK(CONTROL_BLOCK);
    BLOCK_RECORD(control_block, METADATA);
    BLOCK_RECORD(control_block, MODULE_NAME);
    BLOCK_RECORD(control_block, TARGET);

    BLOCK(COMMENT_BLOCK);
    BLOCK_RECORD(comment_block, DECL_COMMENTS);
    BLOCK_RECORD(comment_block, GROUP_NAMES);

#undef BLOCK
#undef BLOCK_RECORD
  }

  /// Writes the Swift doc module file header and name.
  void writeDocHeader();
};

} // end anonymous namespace

static void writeGroupNames(const comment_block::GroupNamesLayout &GroupNames,
                            ArrayRef<StringRef> Names) {
  llvm::SmallString<32> Blob;
  llvm::raw_svector_ostream BlobStream(Blob);
  endian::Writer Writer(BlobStream, little);
  Writer.write<uint32_t>(Names.size());
  for (auto N : Names) {
    Writer.write<uint32_t>(N.size());
    BlobStream << N;
  }
  SmallVector<uint64_t, 8> Scratch;
  GroupNames.emit(Scratch, BlobStream.str());
}

static void writeDeclCommentTable(
    const comment_block::DeclCommentListLayout &DeclCommentList,
    const SourceFile *SF, const ModuleDecl *M,
    DeclGroupNameContext &GroupContext) {

  struct DeclCommentTableWriter : public ASTWalker {
    llvm::BumpPtrAllocator Arena;
    llvm::SmallString<512> USRBuffer;
    llvm::OnDiskChainedHashTableGenerator<DeclCommentTableInfo> generator;
    DeclGroupNameContext &GroupContext;
    unsigned SourceOrder;

    DeclCommentTableWriter(DeclGroupNameContext &GroupContext) :
      GroupContext(GroupContext) {}

    void resetSourceOrder() {
      SourceOrder = 0;
    }

    StringRef copyString(StringRef String) {
      char *Mem = static_cast<char *>(Arena.Allocate(String.size(), 1));
      std::copy(String.begin(), String.end(), Mem);
      return StringRef(Mem, String.size());
    }

    void writeDocForExtensionDecl(ExtensionDecl *ED) {
      RawComment Raw = ED->getRawComment();
      if (Raw.Comments.empty() && !GroupContext.isEnable())
        return;
      // Compute USR.
      {
        USRBuffer.clear();
        llvm::raw_svector_ostream OS(USRBuffer);
        if (ide::printExtensionUSR(ED, OS))
          return;
      }
      generator.insert(copyString(USRBuffer.str()),
                       { ED->getBriefComment(), Raw,
                         GroupContext.getGroupSequence(ED),
                         SourceOrder++ });
    }

    bool walkToDeclPre(Decl *D) override {
      if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
        writeDocForExtensionDecl(ED);
        return true;
      }

      auto *VD = dyn_cast<ValueDecl>(D);
      if (!VD)
        return true;

      RawComment Raw = VD->getRawComment();
      // When building the stdlib we intend to serialize unusual comments.
      // This situation is represented by GroupContext.isEnable().  In that
      // case, we perform fewer serialization checks.
      if (!GroupContext.isEnable()) {
        // Skip the decl if it cannot have a comment.
        if (!VD->canHaveComment()) {
          return true;
        }

        // Skip the decl if it does not have a comment.
        if (Raw.Comments.empty())
          return true;

        // Skip the decl if it's not visible to clients. The use of
        // getEffectiveAccess is unusual here; we want to take the testability
        // state into account and emit documentation if and only if they are
        // visible to clients (which means public ordinarily, but
        // public+internal when testing enabled).
        if (VD->getEffectiveAccess() < swift::AccessLevel::Public)
          return true;
      }

      // Compute USR.
      {
        USRBuffer.clear();
        llvm::raw_svector_ostream OS(USRBuffer);
        if (ide::printDeclUSR(VD, OS))
          return true;
      }

      generator.insert(copyString(USRBuffer.str()),
                       { VD->getBriefComment(), Raw,
                         GroupContext.getGroupSequence(VD),
                         SourceOrder++ });
      return true;
    }

    std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
      return { false, S };
    }

    std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
      return { false, E };
    }

    bool walkToTypeLocPre(TypeLoc &TL) override { return false; }
    bool walkToTypeReprPre(TypeRepr *T) override { return false; }
    bool walkToParameterListPre(ParameterList *PL) override { return false; }
  };

  DeclCommentTableWriter Writer(GroupContext);

  ArrayRef<const FileUnit *> files;
  SmallVector<const FileUnit *, 1> Scratch;
  if (SF) {
    Scratch.push_back(SF);
    files = llvm::makeArrayRef(Scratch);
  } else {
    files = M->getFiles();
  }
  for (auto nextFile : files) {
    Writer.resetSourceOrder();
    const_cast<FileUnit *>(nextFile)->walk(Writer);
  }
  SmallVector<uint64_t, 8> scratch;
  llvm::SmallString<32> hashTableBlob;
  uint32_t tableOffset;
  {
    llvm::raw_svector_ostream blobStream(hashTableBlob);
    // Make sure that no bucket is at offset 0
    endian::write<uint32_t>(blobStream, 0, little);
    tableOffset = Writer.generator.Emit(blobStream);
  }

  DeclCommentList.emit(scratch, tableOffset, hashTableBlob);
}

void DocSerializer::writeDocHeader() {
  {
    BCBlockRAII restoreBlock(Out, CONTROL_BLOCK_ID, 3);
    control_block::ModuleNameLayout ModuleName(Out);
    control_block::MetadataLayout Metadata(Out);
    control_block::TargetLayout Target(Out);

    auto& LangOpts = M->getASTContext().LangOpts;
    Metadata.emit(ScratchRecord, SWIFTDOC_VERSION_MAJOR, SWIFTDOC_VERSION_MINOR,
                  /*short version string length*/0, /*compatibility length*/0,
                  version::getSwiftFullVersion(
                    LangOpts.EffectiveLanguageVersion));

    ModuleName.emit(ScratchRecord, M->getName().str());
    Target.emit(ScratchRecord, LangOpts.Target.str());
  }
}

void serialization::writeDocToStream(raw_ostream &os, ModuleOrSourceFile DC,
                                     StringRef GroupInfoPath) {
  DocSerializer S{SWIFTDOC_SIGNATURE, DC};
  // FIXME: This is only really needed for debugging. We don't actually use it.
  S.writeDocBlockInfoBlock();

  {
    BCBlockRAII moduleBlock(S.Out, MODULE_DOC_BLOCK_ID, 2);
    S.writeDocHeader();
    {
      BCBlockRAII restoreBlock(S.Out, COMMENT_BLOCK_ID, 4);
      DeclGroupNameContext GroupContext(GroupInfoPath, S.M->getASTContext());
      comment_block::DeclCommentListLayout DeclCommentList(S.Out);
      writeDeclCommentTable(DeclCommentList, S.SF, S.M, GroupContext);
      comment_block::GroupNamesLayout GroupNames(S.Out);

      // FIXME: Multi-file compilation may cause group id collision.
      writeGroupNames(GroupNames, GroupContext.getOrderedGroupNames());
    }
  }

  S.writeToStream(os);
}


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

namespace Ch07Ex01Tracepoints
{
   class Program
   {
      static void Main(string[] args)
      {
         int[] testArray = { 4, 7, 4, 2, 7, 3, 7, 8, 3, 9, 1, 9 };
         int[] maxValIndices;
         int maxVal = Maxima(testArray, out maxValIndices);
         Console.WriteLine("Maximum value {0} found at element indices:",
                           maxVal);
         foreach (int index in maxValIndices)
         {
            Console.WriteLine(index);
         }
         Console.ReadKey();
      }

      static int Maxima(int[] integers, out int[] indices)
      {
         indices = new int[1];
         int maxVal = integers[0];
         indices[0] = 0;
         int count = 1;
         for (int i = 1; i < integers.Length; i++)
         {
            if (integers[i] > maxVal)
            {
               maxVal = integers[i];
               count = 1;
               indices = new int[1];
               indices[0] = i;
            }
            else
            {
               if (integers[i] == maxVal)
               {
                  count++;
                  int[] oldIndices = indices;
                  indices = new int[count];
                  oldIndices.CopyTo(indices, 0);
                  indices[count - 1] = i;
               }
            }
         }
         Trace.WriteLine(string.Format(
            "Maximum value {0} found, with {1} occurrences.", maxVal, count));
         return maxVal;
      }
   }
}


text:
<?php

class VersionTask extends \Phalcon\CLI\Task
{
    public function mainAction()
    {
        $this->logger->info(VERSION);
    }
}


text:
{-# LANGUAGE NamedFieldPuns #-}

import Knapsack

import Data.Foldable (maximumBy)
import Control.Applicative

import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Function (on, (&))

-- let's cheat with Haskell's non-strictness :)
import Data.Array

type NumItems = Int

-- now with branches!
type PartialSolution = (Weight, [[Item]])

selectMergeSolution :: PartialSolution -> PartialSolution -> PartialSolution
selectMergeSolution s1@(w1, xss1) s2@(w2, xss2)
  | w1 == w2 = (w1, xss1 ++ xss2)
  | otherwise = maximumBy (comparing fst) [s1, s2]

compareSolution :: PartialSolution -> PartialSolution -> Ordering
compareSolution = comparing fst

addItemToSolution :: Item -> PartialSolution -> PartialSolution
addItemToSolution item (w, items) = (w + weight item, map (item:) items)

lazyTable :: Weight -> [Item] -> Array (Weight, NumItems) PartialSolution
lazyTable capacity items = arr
  where arr = array bounds' [((c,n), itemAt c n) | c <- [0..capacity], n <- [0..numItems]]
        numItems = length items
        bounds' = ((0,0), (capacity, numItems))
        itemAt _cap 0 = (0, [[]])
        itemAt cap n = let nthItem = items !! (n - 1)
                           prevSolution = arr ! (cap, n - 1)
                           nthItemWeight = weight nthItem
                           weightRemovedSolution = arr ! (cap - nthItemWeight, n - 1)
                           newSolution = addItemToSolution nthItem weightRemovedSolution
                       in if nthItemWeight < cap
                          then selectMergeSolution prevSolution newSolution
                          else prevSolution

dynamicProgramming :: Algorithm
dynamicProgramming prob@Problem { capacity, givenItems } =
  solution prob selectedItems Optimal
  where selectedItems = (snd totalSolution) !! 0
        totalSolution = lazyTable capacity givenItems ! (capacity, length givenItems)

main :: IO ()
main = solveBy dynamicProgramming


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PetsWonderland.Client.PageControls.Account {

    public partial class ChangePasswordControl {

        /// <summary>
        /// Notifier control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::PetsWonderland.Client.PageControls.Notifications.NotificationControl Notifier;

        /// <summary>
        /// CurrentPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox CurrentPassword;

        /// <summary>
        /// NewPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox NewPassword;

        /// <summary>
        /// ConfirmNewPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox ConfirmNewPassword;

        /// <summary>
        /// ChangePasswordButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ChangePasswordButton;
    }
}


text:
/**
 * A client to Google Cloud Pub/Sub API.
 *
 *
The interfaces provided are listed below, along with usage samples.
 *
 *
================ TopicAdminClient ================
 *
 *
Service Description: The service that an application uses to manipulate topics, and to send
 * messages to a topic.
 *
 *
To publish messages to a topic, see the Publisher class.
 *
 *
Sample for TopicAdminClient:
 *
 *

 *
 * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
 *   ProjectTopicName name = ProjectTopicName.of("[PROJECT]", "[TOPIC]");
 *   Topic response = topicAdminClient.createTopic(name);
 * }
 *
 *

 *
 * ======================= SubscriptionAdminClient =======================
 *
 *
Service Description: The service that an application uses to manipulate subscriptions and to
 * consume messages from a subscription via the `Pull` method or by establishing a bi-directional
 * stream using the `StreamingPull` method.
 *
 *
To retrieve messages from a subscription, see the Subscriber class.
 *
 *
Sample for SubscriptionAdminClient:
 *
 *

 *
 * try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
 *   ProjectSubscriptionName name = ProjectSubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]");
 *   ProjectTopicName topic = ProjectTopicName.of("[PROJECT]", "[TOPIC]");
 *   PushConfig pushConfig = PushConfig.newBuilder().build();
 *   int ackDeadlineSeconds = 0;
 *   Subscription response = subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
 * }
 *
 *

 */
package com.google.cloud.pubsub.v1;


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginTop="60dp"
        android:orientation="vertical" >
        <!--下面的Relativelayout是测试图片-->
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            >
            <ImageView
                android:id="@+id/background_head"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="20dp"
                android:src="@drawable/robotdog"/>
            <TextView
                android:id="@+id/count_name"
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:text="jack"
                android:textSize="20dp"
                android:textColor="#000"
                android:layout_toRightOf="@+id/background_head"
                android:layout_alignTop="@+id/background_head"
                />
            <TextView
                android:id="@+id/sign"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/background_head"
                android:layout_alignBottom="@+id/background_head"
                android:visibility="gone"
                android:text="登录"
                android:textStyle="bold"
                android:textSize="20dp"
                />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/userInfo"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/one"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="50dp"
                android:src="@drawable/img_1" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/one"
                android:text="个人中心"
                android:textColor="@color/pray3"
                android:textSize="20sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/my_pet_set"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/two"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_2" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/two"
                android:text="我的宠物"
                android:textColor="@color/pray3"
                android:textSize="20sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/three"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_3" />

            <TextView
                android:id="@+id/myrelease"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/three"
                android:text="我的发布"
                android:textColor="@color/pray3"
                android:textSize="20sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_myconcern"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <ImageView
                android:id="@+id/four"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/img_4" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@id/four"
                android:text="我的关注"
                android:textColor="@color/pray3"
                android:textSize="20sp" />
        </RelativeLayout>
        <RelativeLayout
            android:id="@+id/mine_set"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/mine_set_icon"
                android:layout_marginLeft="22dp"
                android:layout_marginTop="20dp"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:src="@drawable/mine_set"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="常规设置"
                android:textSize="20dp"
                android:layout_toRightOf="@+id/mine_set_icon"
                android:layout_alignBottom="@+id/mine_set_icon"
                android:textColor="@color/pray3"
                android:layout_marginLeft="20dp"/>
        </RelativeLayout>

        <LinearLayout

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
        <!--<RelativeLayout-->
            <!--android:id="@+id/mine_set"-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content">-->
            <!--<ImageView-->
                <!--android:id="@+id/mine_set_icon"-->
                <!--android:layout_marginLeft="22dp"-->
                <!--android:layout_marginTop="30dp"-->
                <!--android:layout_width="25dp"-->
                <!--android:layout_height="25dp"-->
                <!--android:src="@drawable/mine_set"/>-->
            <!--<TextView-->
                <!--android:layout_width="wrap_content"-->
                <!--android:layout_height="wrap_content"-->
                <!--android:text="设置"-->
                <!--android:layout_toRightOf="@+id/mine_set_icon"-->
                <!--android:layout_alignBottom="@+id/mine_set_icon"-->
                <!--android:layout_marginLeft="5dp"/>-->
        <!--</RelativeLayout>-->

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/mine_night"
                android:layout_marginLeft="100dp"
                android:layout_marginTop="30dp"
                android:layout_width="25dp"
                android:layout_height="25dp"

                android:src="@drawable/place"/>
            <TextView
                android:id="@+id/tv_place"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="北京市(默认)"
                android:layout_toRightOf="@+id/mine_night"
                android:layout_alignBottom="@+id/mine_night"
                android:layout_marginLeft="5dp"/>
        </RelativeLayout>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


text:
package com.jedou.miniweb.pc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jedou.framework.mini.data.HibernateQuery;
import com.jedou.framework.mini.data.PageResult;
import com.jedou.framework.mini.data.QueryTermTuple;
import com.jedou.framework.mini.log.Logger;
import com.jedou.framework.mini.web.MiniActionHelper;
import com.jedou.framework.mini.web.annotation.NotSupported;
import com.jedou.framework.mini.web.annotation.Required;
import com.jedou.model.pc.PcManager;
import com.jedou.model.pc.PojoEntity;

public class sh {
	@NotSupported
	public void a (HttpServletRequest req, HttpServletResponse resp) {
		int a = MiniActionHelper.getIntValue(req, "a");
		req.setAttribute("a", a);
		if (a == 100)
			MiniActionHelper.renderJSP(req, resp, "noteq");
		else
			MiniActionHelper.renderJSON(resp, PageResult.Page(null));
	}
	@Required
	public void b (HttpServletRequest req, HttpServletResponse resp) {
		MiniActionHelper.renderJSP(req, resp, "/pc/sh/c", null);
	}
	public void c (HttpServletRequest req, HttpServletResponse resp) {
		PojoEntity pe = MiniActionHelper.getObject(req, "a", PojoEntity.class);
		int rows = MiniActionHelper.getRowsNumber(req);
		int page = MiniActionHelper.getPageNumber(req);
		HibernateQuery.getSession().save(pe);
		QueryTermTuple[] p = MiniActionHelper.getQueryTermTuple(req);
		req.setAttribute("pr", PcManager.doC(p, page, rows));
		MiniActionHelper.renderJSP(req, resp, "/pc/sh/c", "noteq");
	}
	public void d (HttpServletRequest req, HttpServletResponse resp) {
		int rows = MiniActionHelper.getRowsNumber(req);
		int page = MiniActionHelper.getPageNumber(req);
		QueryTermTuple[] p = MiniActionHelper.getQueryTermTuple(req);
		MiniActionHelper.renderJSON(resp, PcManager.doC(p, page, rows));
		Logger.info("sh!d");
	}
	public void e (HttpServletRequest req, HttpServletResponse resp) {
		QueryTermTuple[] p = MiniActionHelper.getQueryTermTupleFromPathInfo(req);
		MiniActionHelper.renderJSON(resp, p);
	}
	public void f (HttpServletRequest req, HttpServletResponse resp) {
		QueryTermTuple[] p = MiniActionHelper.getQueryTermTupleFromParams(req);
		MiniActionHelper.renderJSON(resp, p);
	}
}


text:
package com.gs.fw.common.mithra.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;

//todo: close doesn't work right when the reader thread is done
//todo: exception handling has to be improved
public class TwoThreadInputStream extends InputStream
{
    private static Logger logger = LoggerFactory.getLogger(TwoThreadInputStream.class.getName());
    private int bufferSize;
    private InputStream in;
    private int currentPos;
    private Throwable exception;
    private Buffer currentBuffer;
    private LinkedBlockingQueue bufferQueue;
    private LinkedBlockingQueue readQueue;
    private static final Object CLOSE = new Object();
    private static final Object FINISHED = new Object();

    public TwoThreadInputStream(InputStream inputStream, int bufferSize)
    {
        this.bufferSize = bufferSize;
        this.in = inputStream;
        bufferQueue = new LinkedBlockingQueue();
        readQueue = new LinkedBlockingQueue();
        for(int i=0;i<4;i++)
        {
            bufferQueue.add(new Buffer(new byte[bufferSize]));
        }
        ExceptionCatchingThread.submitTask(new ExceptionHandlingTask()
        {
            @Override
            public void execute()
            {
                boolean done = false;
                while(!done)
                {
                    try
                    {
                        Object o = bufferQueue.take();
                        if (o == CLOSE)
                        {
                            in.close();
                            break;
                        }
                        Buffer buf = (Buffer) o;
                        int read = in.read(buf.buf);
                        int total = read;
                        while(read >= 0 && total < buf.buf.length)
                        {
                            read = in.read(buf.buf, total, buf.buf.length - total);
                            if (read > 0) total += read;
                        }
                        buf.goodBytes = total;
                        if (total > 0) readQueue.put(buf);
                        if (read < 0)
                        {
                            readQueue.put(FINISHED);
                        }
                    }
                    catch (Throwable e)
                    {
                        logger.error("Error reading stream", e);
                        done = true;
                        exception = e;
                        reallyPut(FINISHED);
                    }
                }
            }

            private void reallyPut(Object o)
            {
                try
                {
                    readQueue.put(o);
                }
                catch (InterruptedException e)
                {
                    // ignore
                }

            }
        });
    }

    @Override
    public int read() throws IOException
    {
        ensureCurrent();
        if (currentPos == -1) return -1;
        return currentBuffer.buf[currentPos++];
    }

    private void ensureCurrent() throws IOException
    {
        if (exception != null)
        {
            if (exception instanceof IOException)
            {
                throw (IOException) exception;
            }
            throwIoException(exception, "Could not read archive");
        }
        if (currentBuffer == null || currentBuffer.goodBytes == currentPos)
        {
            try
            {
                if (currentBuffer != null)
                {
                    bufferQueue.put(currentBuffer);
                }
                Object o = readQueue.take();
                if (o == FINISHED)
                {
                    currentPos = -1;
                }
                else
                {
                    currentBuffer = (Buffer) o;
                    currentPos = 0;
                }
            }
            catch (InterruptedException e)
            {
                throwIoException(e, "how did this get interrupted?");
            }
        }
    }

    private void throwIoException(Throwable e, String msg)
            throws IOException
    {
        IOException exp = new IOException(msg);
        exp.initCause(e);
        throw exp;
    }

    @Override
    public int available() throws IOException
    {
        return currentBuffer.goodBytes - currentPos;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException
    {
        ensureCurrent();
        if (currentPos == -1) return -1;
        int left = currentBuffer.goodBytes - currentPos;
        int toCopy = Math.min(left, len);
        int totalCopied = 0;
        System.arraycopy(currentBuffer.buf, currentPos, b, off, toCopy);
        currentPos += toCopy;
        totalCopied += toCopy;
        while (totalCopied < len)
        {
            ensureCurrent();
            if (currentPos == -1) return totalCopied;
            left = currentBuffer.goodBytes - currentPos;
            toCopy = Math.min(left, len - totalCopied);
            System.arraycopy(currentBuffer.buf, currentPos, b, off + totalCopied, toCopy);
            currentPos += toCopy;
            totalCopied += toCopy;
        }
        return totalCopied;
    }

    @Override
    public void close() throws IOException
    {
        bufferQueue.clear();
        try
        {
            bufferQueue.put(CLOSE);
        }
        catch (InterruptedException e)
        {
            throwIoException(e, "couldn't close");
        }
    }

    private static class Buffer
    {
        private byte[] buf;
        private int goodBytes;

        private Buffer(byte[] buf)
        {
            this.buf = buf;
        }
    }
}


text:
package org.opensmartgridplatform.adapter.ws.smartmetering.application.mapping;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import org.opensmartgridplatform.adapter.ws.schema.smartmetering.adhoc.GetSpecificAttributeValueRequest;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.common.ObisCodeValues;

public class GetSpecificAttributeValueRequestMappingTest {

    private final AdhocMapper mapper = new AdhocMapper();

    @Test
    public void test() {
        final GetSpecificAttributeValueRequest req1 = this.makeRequest();
        final Object obj1 = this.mapper.map(req1,
                org.opensmartgridplatform.domain.core.valueobjects.smartmetering.SpecificAttributeValueRequest.class);
        assertTrue((obj1 != null)
                && (obj1 instanceof org.opensmartgridplatform.domain.core.valueobjects.smartmetering.SpecificAttributeValueRequest));
        final Object obj2 = this.mapper.map(obj1, GetSpecificAttributeValueRequest.class);
        assertTrue((obj2 != null) && (obj2 instanceof GetSpecificAttributeValueRequest));
        final GetSpecificAttributeValueRequest req2 = (GetSpecificAttributeValueRequest) obj2;
        assertTrue(req1.getDeviceIdentification().equals(req2.getDeviceIdentification()));
    }

    private GetSpecificAttributeValueRequest makeRequest() {
        final GetSpecificAttributeValueRequest result = new GetSpecificAttributeValueRequest();
        final ObisCodeValues obiscode = new ObisCodeValues();
        obiscode.setA((short) 1);
        result.setObisCode(obiscode);
        result.setDeviceIdentification("12345");
        return result;
    }

}


text:
/* SUIT method */

.u-clearFix {/* If supporting IE 6/7 */

    zoom: 1;
}

.u-clearFix:before, .u-clearFix:after {

    content: "";

    display: table;
}

.u-clearFix:after {

    clear: both;
}

.mine-SearchForm-textField {

    border: 1px solid #ccc;
}

.mine-SearchForm-textField.is-invalid {

    border: 1px solid red;
}

.mine-SearchForm {

    padding: 0;

    margin: 0;
}

.mine-SearchForm--advanced {

    padding: 1rem;
}

/* BEM method */
.mine-search-form-text-field {

    border: 1px solid #ccc;
}
.mine-search-form {

    padding: 0;

    margin: 0;
}
.mine-search-form--advanced {

    padding: 1rem;
}


text:
package com.dslplatform.client.json.Timestamp;

import com.dslplatform.client.JsonSerialization;
import com.dslplatform.patterns.Bytes;
import java.io.IOException;

public class OneArrayOfOneTimestampsDefaultValueTurtle {
	private static JsonSerialization jsonSerialization;

	@org.junit.BeforeClass
	public static void initializeJsonSerialization() throws IOException {
		jsonSerialization = com.dslplatform.client.StaticJson.getSerialization();
	}

	@org.junit.Test
	public void testDefaultValueEquality() throws IOException {
		final org.joda.time.DateTime[] defaultValue = new org.joda.time.DateTime[0];
		final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
		final org.joda.time.DateTime[] defaultValueJsonDeserialized = jsonSerialization.deserialize(org.joda.time.DateTime[].class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
		com.dslplatform.ocd.javaasserts.TimestampAsserts.assertOneArrayOfOneEquals(defaultValue, defaultValueJsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue1Equality() throws IOException {
		final org.joda.time.DateTime[] borderValue1 = new org.joda.time.DateTime[] { org.joda.time.DateTime.now() };
		final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
		final org.joda.time.DateTime[] borderValue1JsonDeserialized = jsonSerialization.deserialize(org.joda.time.DateTime[].class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.TimestampAsserts.assertOneArrayOfOneEquals(borderValue1, borderValue1JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue2Equality() throws IOException {
		final org.joda.time.DateTime[] borderValue2 = new org.joda.time.DateTime[] { new org.joda.time.DateTime(Integer.MAX_VALUE * 1001L) };
		final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
		final org.joda.time.DateTime[] borderValue2JsonDeserialized = jsonSerialization.deserialize(org.joda.time.DateTime[].class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.TimestampAsserts.assertOneArrayOfOneEquals(borderValue2, borderValue2JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue3Equality() throws IOException {
		final org.joda.time.DateTime[] borderValue3 = new org.joda.time.DateTime[] { org.joda.time.DateTime.now(), new org.joda.time.DateTime(0), new org.joda.time.DateTime(1, 1, 1, 0, 0, org.joda.time.DateTimeZone.UTC), new org.joda.time.DateTime(Integer.MAX_VALUE * 1001L) };
		final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
		final org.joda.time.DateTime[] borderValue3JsonDeserialized = jsonSerialization.deserialize(org.joda.time.DateTime[].class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.TimestampAsserts.assertOneArrayOfOneEquals(borderValue3, borderValue3JsonDeserialized);
	}
}


text:
        <form action="<?php echo BASE_URL;?>org/<?php echo $data['org_id'] ?>/team/add" id="theForm" method="post">

Add New Team to <?php echo $data['org_name']?>

Team Name*

<input type="text" name="team_name" id="team_name" placeholder="Team Name" required minlength="2">

Team Owner's Name*

<input type="text" name="team_owner_name" id="team_owner_name" placeholder="Team Owner's Name" required minlength="2" value="<?php echo Session::name() ?>">

Team Owner's Email*

<input type="email" name="team_owner_email" id="team_owner_email" placeholder="Team Owner's Email" required minlength="4" value="<?php echo Session::email() ?>">

                <?php include_once TEMPLATE_PATH . "org/inc/team_members_textarea.html.php"?>

<a href="<?php echo BASE_URL;?>org/<?php echo $data['org_id'] ?>/team" class="button cancel_button">Cancel

<input type="submit" value="Create" class="button special" />

        </form>
        <?php include_once TEMPLATE_PATH. "inc/jquery_validator.php"; ?>


text:
package com.cloud.ucs.manager;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;

import com.cloud.utils.exception.CloudRuntimeException;

public class UcsHttpClient {
    private static HttpClient client = new HttpClient();
    private static Protocol ucsHttpsProtocol = new org.apache.commons.httpclient.protocol.Protocol("https", new EasySSLProtocolSocketFactory(), 443);
    private final String url;

    public UcsHttpClient(String ip) {
        url = String.format("http://%s/nuova", ip);
        Protocol.registerProtocol("https", ucsHttpsProtocol);
    }

    public String call(String xml) {
        PostMethod post = new PostMethod(url);
        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml");
        //post.setFollowRedirects(true);
        try {
            int result = client.executeMethod(post);
            if (result == 302) {
                // Handle HTTPS redirect
                // Ideal way might be to configure from add manager API
                // for using either HTTP / HTTPS
                // Allow only one level of redirect
                String redirectLocation;
                Header locationHeader = post.getResponseHeader("location");
                if (locationHeader != null) {
                    redirectLocation = locationHeader.getValue();
                } else {
                    throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
                }
                post.setURI(new URI(redirectLocation));
                result = client.executeMethod(post);
            }
            // Check for errors
            if (result != 200) {
                throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
            }
            String res = post.getResponseBodyAsString();
            if (res.contains("errorCode")) {
                String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
                throw new CloudRuntimeException(err);
            }
            return res;
        } catch (Exception e) {
            throw new CloudRuntimeException(e.getMessage(), e);
        } finally {
            post.releaseConnection();
        }
    }
}


text:
SquareRef Square::create(int size)
{
	SquareRef ref = std::shared_ptr<Square>(new Square());
	ref->setup(size);
	return ref;
}

Square::Square()
: mSize(50)
, mColor(ci::Color(ci::CM_HSV, 1, 1, 0.8))
, mHighlightColor(ci::Color(ci::CM_HSV, 1, 1, 1))
, mIsPressed(false)
, mStartPos(ci::vec2())
, mEndPos(ci::vec2())
, mInitialPos(ci::vec2())
, mBoundsColor(ci::Color(1.0f, 1.0f, 1.0f))
{
}

Square::~Square()
{
}

void Square::setup(int size)
{
	mSize = size;

	//	The square shape
	mShape = ShapeView::createRect(mSize, mSize);
	mShape->setAlignment(po::scene::Alignment::CENTER_CENTER);

	//	Change hue based on size
	float hue = ci::lmap<float>(mSize, 0, 300, 0.1, 0.3);
	mColor = ci::Color(ci::CM_HSV, 1 - hue, 1, 0.8);
	mHighlightColor = ci::Color(ci::CM_HSV, 1 - hue, 1, 1);

	mShape->setFillColor(mColor);
	addSubview(mShape);

	//	Connect to mouse events
	getSignal(po::scene::MouseEvent::DOWN_INSIDE).connect(std::bind(&Square::onMouseDown, this, std::placeholders::_1));
	getSignal(po::scene::MouseEvent::DRAG).connect(std::bind(&Square::onMouseDragged, this, std::placeholders::_1));
	getSignal(po::scene::MouseEvent::UP_INSIDE).connect(std::bind(&Square::onMouseUp, this, std::placeholders::_1));
	getSignal(po::scene::MouseEvent::UP).connect(std::bind(&Square::onMouseUp, this, std::placeholders::_1));
}

void Square::onMouseDown(po::scene::MouseEvent &event)
{
	if (!mIsPressed) {
		mIsPressed = true;

		//	Set the initial, start and end positions to the window position in the parent
		mInitialPos = getPosition();
		mStartPos = getSuperview()->windowToLocal(event.getWindowPos());
		mEndPos = getSuperview()->windowToLocal(event.getWindowPos());

		highlight(true);
		highlightChildren(true);
	}
}

void Square::onMouseDragged(po::scene::MouseEvent &event)
{
	if (mIsPressed) {
		//	Update the end position
		mEndPos = getSuperview()->windowToLocal(event.getWindowPos());

		//	Set the nodes position
		ci::vec2 newPosition = mInitialPos + (mEndPos - mStartPos);
		setPosition(newPosition);
	}
}

void Square::onMouseUp(po::scene::MouseEvent &event)
{
	if (mIsPressed) {
		mIsPressed = false;

		highlight(false);
		highlightChildren(false);
	}
}

void Square::highlight(bool isHighlighted)
{
	if (isHighlighted) {
		mShape->setFillColor(mHighlightColor);
	} else {
		mShape->setFillColor(mColor);
	}
}

void Square::highlightChildren(bool isHighlighted)
{
	//	Get all the nodes children
	std::deque<ViewRef> children = getSubviews();

	if (isHighlighted) {
		for (auto &child : children) {
			child->setBoundsColor(mBoundsColor);
			child->setDrawBounds(true);
		}
	} else {
		for (auto &child : children) {
			child->setDrawBounds(false);
		}
	}
}