text:
// <copyright file="ContainsComparer.cs">
//    Copyright © 2013 Dan Piessens  All rights reserved.
// </copyright>

namespace SpecBind.Validation
{
    using SpecBind.Pages;

    /// <summary>
    /// A string comparison class for a contains comparison
    /// </summary>
    public class ContainsComparer : ValidationComparerBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ContainsComparer"/> class.
        /// </summary>
        public ContainsComparer()
            : base("contains")
        {
        }

        /// <summary>
        /// Compares the values using the specified property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="expectedValue">The expected value.</param>
        /// <param name="actualValue">The actual value.</param>
        /// <returns><c>true</c> if the comparison passes, <c>false</c> otherwise.</returns>
        public override bool Compare(IPropertyData property, string expectedValue, string actualValue)
        {
            return (actualValue != null) && actualValue.Contains(expectedValue);
        }
    }
}


text:
<!DOCTYPE html>
<html>
	<head>
		<title>StreetView</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
		<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
		<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
	</head>
	<body>
		<div id="map-canvas">
			Placeholder for awesome streetview
		</div>
		<script type="text/javascript">
			var map, panorama, streetviewservice;
			function createPanorama(posi) {
				streetviewservice.getPanoramaByLocation(new google.maps.LatLng(posi.lat, posi.lng), 1000, function(data, status) {
					if (status == google.maps.StreetViewStatus.OK) {

						panorama.setPov({
							heading : 10,
							pitch : 0,
							zoom : 1.6
						});

						var height = isNaN(window.innerHeight) ? window.clientHeight : window.innerHeight;
						document.getElementById("map-canvas").style.height = height + 'px';
						setTimeout(function() {
							panorama.setPano(data.location.pano);
							panorama.setVisible(true);
						}, 200);
					} else
						alert('For this place we have no streetview panorama.');
				});
			}

			google.maps.event.addDomListener(window, 'load', function() {
				streetviewservice = new google.maps.StreetViewService();
				panorama = new google.maps.StreetViewPanorama(document.getElementById("map-canvas"), {
					navigationControl : false,
					linksControl : false,
					enableCloseButton : false,
				});
			});
		</script>
	</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
const React = require('react')
const ConsolePanel = require('./console-panel')

const noop = () => {}
const defaultOptions = {
  hotkey: 192,    // KeyCode for '~'
  welcome: '',    // welcome message
  onShow: noop,   // on show callback
  onHide: noop,   // on hide callback
  defaultHandler: noop,   // fallback handler
  caseSensitive: false,   // whether case sensitive
  autoComplete: true      // press `tab` to auto complete
}

// Console constructor
function Console (options = {}, handlers) {
  this.config = Object.assign({}, defaultOptions, options)
  this.history = []
  this.handlers = {}

  this.log(this.config.welcome)

  if (handlers) {
    for (let cmd in handlers) {
      this.register(cmd, handlers[cmd], handlers[cmd].config)
    }
  }

  this._render()

  return this
}

Console.prototype._render = function () {
  const panelProps = {
    config: this.config,
    history: this.history,
    dispatch: this.dispatch.bind(this),
    autoCompleteFn: this.autoComplete.bind(this)
  }
  const panel = <ConsolePanel ref={p => (this.panel = p)} {...panelProps} />
  this.element = React.render(panel, document.body, this.element)
  return this
}

Console.prototype.toggle = function (visibility) {
  this.panel.toggle(visibility)
}

Console.prototype.log = function (message, instruction) {
  this.history.push({
    ins: instruction,
    msg: message
  })
  this._render()
}

Console.prototype.clear = function () {
  while (this.history.length) {
    this.history.shift()
  }
  this._render()
}

Console.prototype.register = function (cmd, handler, config) {
  if (typeof cmd === 'function') {
    this.config.defaultHandler = cmd
  } else if (typeof cmd === 'string' && typeof handler === 'function') {
    !this.config.caseSensitive && (cmd = cmd.toLowerCase())

    this.handlers[cmd] = {
      cmd: cmd,
      fn: handler,
      cfg: config
    }
  }
  return this
}

Console.prototype.autoComplete = function (prefix) {
  if (typeof this.config.autoComplete === 'function') {
    return this.config.autoComplete(prefix)
  }

  if (this.config.autoComplete) {
    const cmds = Object.keys(this.handlers)
    const matched = cmds.filter(cmd => cmd.indexOf(prefix) === 0)
    if (matched.length === 1) {
      return matched[0]
    } else {
      this.log(prefix)
      this.log(matched.map(n => '  ' + n).join('\n'))
      return prefix
    }
  }
}

Console.prototype.dispatch = function (instruction) {
  let [cmd, ...args] = instruction.split(' ')
  cmd = this.config.caseSensitive ? cmd : cmd.toLowerCase()
  args = args.join(' ')

  let result
  const handler = this.handlers[cmd]
  if (typeof handler === 'object' && typeof handler.fn === 'function') {
    result = handler.fn(args)
  } else if (this.config.defaultHandler) {
    result = this.config.defaultHandler(args)
  }

  this.log(result, instruction)
  this._render()
}

Console.prototype.destroy = function () {
  React.render('', document.body, this.element)
  this.element = null
}

module.exports = Console


text:
namespace gpu {
namespace gles2 {

class MailboxManagerTest : public testing::Test {
 public:
  MailboxManagerTest() : manager_(new MailboxManager()) {}
  virtual ~MailboxManagerTest() {}

 protected:
  Texture* CreateTexture() {
    return new Texture(0);
  }

  void DestroyTexture(Texture* texture) {
    delete texture;
  }

  scoped_refptr<MailboxManager> manager_;

 private:
  DISALLOW_COPY_AND_ASSIGN(MailboxManagerTest);
};

// Tests basic produce/consume behavior.
TEST_F(MailboxManagerTest, Basic) {
  Texture* texture = CreateTexture();

  Mailbox name = Mailbox::Generate();
  manager_->ProduceTexture(0, name, texture);
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name));

  // We can consume multiple times.
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name));

  // Wrong target should fail the consume.
  EXPECT_EQ(NULL, manager_->ConsumeTexture(1, name));

  // Destroy should cleanup the mailbox.
  DestroyTexture(texture);
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name));
}

// Tests behavior with multiple produce on the same texture.
TEST_F(MailboxManagerTest, ProduceMultipleMailbox) {
  Texture* texture = CreateTexture();

  Mailbox name1 = Mailbox::Generate();

  manager_->ProduceTexture(0, name1, texture);
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name1));

  // Can produce a second time with the same mailbox.
  manager_->ProduceTexture(0, name1, texture);
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name1));

  // Can produce again, with a different mailbox.
  Mailbox name2 = Mailbox::Generate();
  manager_->ProduceTexture(0, name2, texture);

  // Still available under all mailboxes.
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name1));
  EXPECT_EQ(texture, manager_->ConsumeTexture(0, name2));

  // Destroy should cleanup all mailboxes.
  DestroyTexture(texture);
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name1));
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name2));
}

// Tests behavior with multiple produce on the same mailbox with different
// textures.
TEST_F(MailboxManagerTest, ProduceMultipleTexture) {
  Texture* texture1 = CreateTexture();
  Texture* texture2 = CreateTexture();

  Mailbox name = Mailbox::Generate();

  manager_->ProduceTexture(0, name, texture1);
  EXPECT_EQ(texture1, manager_->ConsumeTexture(0, name));

  // Can produce a second time with the same mailbox, but different texture.
  manager_->ProduceTexture(0, name, texture2);
  EXPECT_EQ(texture2, manager_->ConsumeTexture(0, name));

  // Destroying the texture that's under no mailbox shouldn't have an effect.
  DestroyTexture(texture1);
  EXPECT_EQ(texture2, manager_->ConsumeTexture(0, name));

  // Destroying the texture that's bound should clean up.
  DestroyTexture(texture2);
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name));
}

TEST_F(MailboxManagerTest, ProduceMultipleTextureMailbox) {
  Texture* texture1 = CreateTexture();
  Texture* texture2 = CreateTexture();
  Mailbox name1 = Mailbox::Generate();
  Mailbox name2 = Mailbox::Generate();

  // Put texture1 on name1 and name2.
  manager_->ProduceTexture(0, name1, texture1);
  manager_->ProduceTexture(0, name2, texture1);
  EXPECT_EQ(texture1, manager_->ConsumeTexture(0, name1));
  EXPECT_EQ(texture1, manager_->ConsumeTexture(0, name2));

  // Put texture2 on name2.
  manager_->ProduceTexture(0, name2, texture2);
  EXPECT_EQ(texture1, manager_->ConsumeTexture(0, name1));
  EXPECT_EQ(texture2, manager_->ConsumeTexture(0, name2));

  // Destroy texture1, shouldn't affect name2.
  DestroyTexture(texture1);
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name1));
  EXPECT_EQ(texture2, manager_->ConsumeTexture(0, name2));

  DestroyTexture(texture2);
  EXPECT_EQ(NULL, manager_->ConsumeTexture(0, name2));
}

}  // namespace gles2
}  // namespace gpu


text:
require 'rolify/adapters/base'

module Rolify
  module Adapter
    class RoleAdapter < RoleAdapterBase
      def where(relation, *args)
        conditions = build_conditions(relation, args)
        relation.any_of(*conditions)
      end

      def find_or_create_by(role_name, resource_type = nil, resource_id = nil)
        self.role_class.find_or_create_by(:name => role_name,
                                          :resource_type => resource_type,
                                          :resource_id => resource_id)
      end

      def add(relation, role)
        relation.roles << role
      end

      def remove(relation, role_name, resource = nil)
        #roles = { :name => role_name }
        #roles.merge!({:resource_type => (resource.is_a?(Class) ? resource.to_s : resource.class.name)}) if resource
        #roles.merge!({ :resource_id => resource.id }) if resource && !resource.is_a?(Class)
        #roles_to_remove = relation.roles.where(roles)
        #roles_to_remove.each do |role|
        #  # Deletion in n-n relations is unreliable. Sometimes it works, sometimes not.
        #  # So, this does not work all the time: `relation.roles.delete(role)`
        #  # @see http://stackoverflow.com/questions/9132596/rails3-mongoid-many-to-many-relation-and-delete-operation
        #  # We instead remove ids from the Role object and the relation object.
        #  relation.role_ids.delete(role.id)
        #  role.send((user_class.to_s.underscore + '_ids').to_sym).delete(relation.id)
        #
        #  role.destroy if role.send(user_class.to_s.tableize.to_sym).empty?
        #end
        cond = { :name => role_name }
        cond[:resource_type] = (resource.is_a?(Class) ? resource.to_s : resource.class.name) if resource
        cond[:resource_id] = resource.id if resource && !resource.is_a?(Class)
        roles = relation.roles.where(cond)
        roles.each do |role|
          relation.roles.delete(role)
          role.send(ActiveSupport::Inflector.demodulize(user_class).tableize.to_sym).delete(relation)
          if Rolify.remove_role_if_empty && role.send(ActiveSupport::Inflector.demodulize(user_class).tableize.to_sym).empty?
            role.destroy
          end
        end if roles
        roles
      end

      def exists?(relation, column)
        relation.where(column.to_sym.ne => nil)
      end

      def scope(relation, conditions)
        roles = where(role_class, conditions).map { |role| role.id }
        return [] if roles.size.zero?
        query = relation.any_in(:role_ids => roles)
        query
      end

      def all_except(user, excluded_obj)
        user.not_in(_id: excluded_obj.to_a)
      end

      private

      def build_conditions(relation, args)
        conditions = []
        args.each do |arg|
          if arg.is_a? Hash
            query = build_query(arg[:name], arg[:resource])
          elsif arg.is_a?(String) || arg.is_a?(Symbol)
            query = build_query(arg)
          else
            raise ArgumentError, "Invalid argument type: only hash or string or symbol allowed"
          end
          conditions += query
        end
        conditions
      end

      def build_query(role, resource = nil)
        return [{ :name => role }] if resource == :any
        query = [{ :name => role, :resource_type => nil, :resource_id => nil }]
        if resource
          query << { :name => role, :resource_type => (resource.is_a?(Class) ? resource.to_s : resource.class.name), :resource_id => nil }
          if !resource.is_a? Class
            query << { :name => role, :resource_type => resource.class.name, :resource_id => resource.id }
          end
        end
        query
      end
    end
  end
end


text:
<?php

namespace app\framework\Component\Image\Bridge\Filter\Basic;

use app\framework\Component\Image\Bridge\Filter\FilterInterface;
use app\framework\Component\Image\Bridge\Image\Fill\FillInterface;
use app\framework\Component\Image\Bridge\Image\ImageInterface;

/**
 * A fill filter
 */
class Fill implements FilterInterface
{
    /**
     * @var FillInterface
     */
    private $fill;

    /**
     * @param FillInterface $fill
     */
    public function __construct(FillInterface $fill)
    {
        $this->fill = $fill;
    }

    /**
     * {@inheritdoc}
     */
    public function apply(ImageInterface $image)
    {
        return $image->fill($this->fill);
    }
}


text:
OpenFarm::Application.routes.draw do

  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'

  devise_for :users, controllers: {
      registrations: "registrations",
      confirmations: "confirmations"
    }

  scope '(:locale)', locale: /en|nl/ do
    root to: 'homes#show'
    post '(:locale)/crop_search' => 'crop_searches#search',
         as: :crop_search_via_post
    get '(:locale)/crop_search' => 'crop_searches#search',
        as: :crop_search_via_get

    devise_scope :users do
      get 'users/gardens' => 'users#gardens'
      get 'users/finish' => 'users#finish'
      get 'users/edit' => 'users#edit'
      put 'users' => 'users#update'
    end
    resources :users
    resources :crops
    resources :guides
    resources :stages
    resources :requirements
    resources :gardens
  end

  get 'announcements/hide', to: 'announcements#hide'

  namespace :api, defaults: {format: 'json'} do
    get '/aws/s3_access_token' => 'aws#s3_access_token'
    post '/local/upload_file' => 'file_upload#upload_file'

    namespace :v1 do
      get '/progress/pictures/:obj_type/:obj_id' => 'progress_job#show'

      resources :crops, only: [:create, :index, :show, :update] do
        resources :pictures, only: [:index, :show]
      end
      resources :tags, only: :index do
        collection do
          get '/:query', action: :index
        end
      end
      resources :guides, only: [:create, :show, :update, :destroy]
      resources :users, only: [:show, :update] do
        resources :gardens, only: [:index]
        resources :compatibility_score, only: [:show]
      end
      resources :gardens, only: [:create, :show, :update, :destroy] do
        resources :garden_crops, only: [:index,
                                        :show,
                                        :create,
                                        :update,
                                        :destroy]
      end
      resources :detail_options, only: [:index]
      resources :stage_options, only: [:index]
      resources :stage_action_options, only: [:index]
      resources :stages, only: [:create, :show, :update, :destroy] do
        resources :pictures,
                  only: [:index],
                  controller: 'stages',
                  action: 'pictures'
        resources :stage_actions,
                  only: [:index, :destroy]
                  # controller: 'stages',
                  # action: 'stage_actions'
      end

      resources :tokens, path: 'token', only: [:create] do
        collection do
          delete :destroy
        end
      end
    end
  end

  get '/:locale' => 'homes#show'
end


text:
namespace mojo {

// static
bool StructTraits<viz::mojom::FrameDeadlineDataView, viz::FrameDeadline>::Read(
    viz::mojom::FrameDeadlineDataView data,
    viz::FrameDeadline* out) {
  base::TimeTicks frame_start_time;
  base::TimeDelta frame_interval;
  if (!data.ReadFrameStartTime(&frame_start_time) ||
      !data.ReadFrameInterval(&frame_interval)) {
    return false;
  }
  *out = viz::FrameDeadline(frame_start_time, data.deadline_in_frames(),
                            frame_interval,
                            data.use_default_lower_bound_deadline());
  return true;
}

}  // namespace mojo


text:
import * as dom from 'vs/base/browser/dom';
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IDataSource, ITreeNode, ITreeRenderer, ITreeSorter } from 'vs/base/browser/ui/tree/tree';
import { values } from 'vs/base/common/collections';
import { createMatches, FuzzyScore } from 'vs/base/common/filters';
import 'vs/css!./media/outlineTree';
import 'vs/css!./media/symbol-icons';
import { Range } from 'vs/editor/common/core/range';
import { SymbolKind, symbolKindToCssClass } from 'vs/editor/common/modes';
import { OutlineElement, OutlineGroup, OutlineModel, TreeElement } from 'vs/editor/contrib/documentSymbols/outlineModel';
import { localize } from 'vs/nls';
import { IconLabel } from 'vs/base/browser/ui/iconLabel/iconLabel';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { OutlineConfigKeys } from 'vs/editor/contrib/documentSymbols/outline';
import { MarkerSeverity } from 'vs/platform/markers/common/markers';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { listErrorForeground, listWarningForeground } from 'vs/platform/theme/common/colorRegistry';
import { IdleValue } from 'vs/base/common/async';

export type OutlineItem = OutlineGroup | OutlineElement;

export class OutlineNavigationLabelProvider implements IKeyboardNavigationLabelProvider<OutlineItem> {

	getKeyboardNavigationLabel(element: OutlineItem): { toString(): string; } {
		if (element instanceof OutlineGroup) {
			return element.provider.displayName || element.id;
		} else {
			return element.symbol.name;
		}
	}
}

export class OutlineIdentityProvider implements IIdentityProvider<OutlineItem> {
	getId(element: TreeElement): { toString(): string; } {
		return element.id;
	}
}

export class OutlineGroupTemplate {
	static id = 'OutlineGroupTemplate';

	labelContainer: HTMLElement;
	label: HighlightedLabel;
}

export class OutlineElementTemplate {
	static id = 'OutlineElementTemplate';
	container: HTMLElement;
	iconLabel: IconLabel;
	decoration: HTMLElement;
}

export class OutlineVirtualDelegate implements IListVirtualDelegate<OutlineItem> {

	getHeight(_element: OutlineItem): number {
		return 22;
	}

	getTemplateId(element: OutlineItem): string {
		if (element instanceof OutlineGroup) {
			return OutlineGroupTemplate.id;
		} else {
			return OutlineElementTemplate.id;
		}
	}
}

export class OutlineGroupRenderer implements ITreeRenderer<OutlineGroup, FuzzyScore, OutlineGroupTemplate> {

	readonly templateId: string = OutlineGroupTemplate.id;

	renderTemplate(container: HTMLElement): OutlineGroupTemplate {
		const labelContainer = dom.$('.outline-element-label');
		dom.addClass(container, 'outline-element');
		dom.append(container, labelContainer);
		return { labelContainer, label: new HighlightedLabel(labelContainer, true) };
	}

	renderElement(node: ITreeNode<OutlineGroup, FuzzyScore>, index: number, template: OutlineGroupTemplate): void {
		template.label.set(
			node.element.provider.displayName || localize('provider', "Outline Provider"),
			createMatches(node.filterData)
		);
	}

	disposeTemplate(_template: OutlineGroupTemplate): void {
		// nothing
	}
}

export class OutlineElementRenderer implements ITreeRenderer<OutlineElement, FuzzyScore, OutlineElementTemplate> {

	readonly templateId: string = OutlineElementTemplate.id;

	constructor(
		@IConfigurationService private readonly _configurationService: IConfigurationService,
		@IThemeService private readonly _themeService: IThemeService,
	) { }

	renderTemplate(container: HTMLElement): OutlineElementTemplate {
		dom.addClass(container, 'outline-element');
		const iconLabel = new IconLabel(container, { supportHighlights: true });
		const decoration = dom.$('.outline-element-decoration');
		container.appendChild(decoration);
		return { container, iconLabel, decoration };
	}

	renderElement(node: ITreeNode<OutlineElement, FuzzyScore>, index: number, template: OutlineElementTemplate): void {
		const { element } = node;
		const options = {
			matches: createMatches(node.filterData),
			labelEscapeNewLines: true,
			extraClasses: <string[]>[],
			title: localize('title.template', "{0} ({1})", element.symbol.name, OutlineElementRenderer._symbolKindNames[element.symbol.kind])
		};
		if (this._configurationService.getValue(OutlineConfigKeys.icons)) {
			// add styles for the icons
			options.extraClasses.push(`outline-element-icon ${symbolKindToCssClass(element.symbol.kind, true)}`);
		}
		template.iconLabel.setLabel(element.symbol.name, element.symbol.detail, options);
		this._renderMarkerInfo(element, template);
	}

	private _renderMarkerInfo(element: OutlineElement, template: OutlineElementTemplate): void {

		if (!element.marker) {
			dom.hide(template.decoration);
			template.container.style.removeProperty('--outline-element-color');
			return;
		}

		const { count, topSev } = element.marker;
		const color = this._themeService.getTheme().getColor(topSev === MarkerSeverity.Error ? listErrorForeground : listWarningForeground);
		const cssColor = color ? color.toString() : 'inherit';

		// color of the label
		if (this._configurationService.getValue(OutlineConfigKeys.problemsColors)) {
			template.container.style.setProperty('--outline-element-color', cssColor);
		} else {
			template.container.style.removeProperty('--outline-element-color');
		}

		// badge with color/rollup
		if (!this._configurationService.getValue(OutlineConfigKeys.problemsBadges)) {
			dom.hide(template.decoration);

		} else if (count > 0) {
			dom.show(template.decoration);
			dom.removeClass(template.decoration, 'bubble');
			template.decoration.innerText = count < 10 ? count.toString() : '+9';
			template.decoration.title = count === 1 ? localize('1.problem', "1 problem in this element") : localize('N.problem', "{0} problems in this element", count);
			template.decoration.style.setProperty('--outline-element-color', cssColor);

		} else {
			dom.show(template.decoration);
			dom.addClass(template.decoration, 'bubble');
			template.decoration.innerText = '\uf052';
			template.decoration.title = localize('deep.problem', "Contains elements with problems");
			template.decoration.style.setProperty('--outline-element-color', cssColor);
		}
	}

	private static _symbolKindNames: { [symbol: number]: string } = {
		[SymbolKind.Array]: localize('Array', "array"),
		[SymbolKind.Boolean]: localize('Boolean', "boolean"),
		[SymbolKind.Class]: localize('Class', "class"),
		[SymbolKind.Constant]: localize('Constant', "constant"),
		[SymbolKind.Constructor]: localize('Constructor', "constructor"),
		[SymbolKind.Enum]: localize('Enum', "enumeration"),
		[SymbolKind.EnumMember]: localize('EnumMember', "enumeration member"),
		[SymbolKind.Event]: localize('Event', "event"),
		[SymbolKind.Field]: localize('Field', "field"),
		[SymbolKind.File]: localize('File', "file"),
		[SymbolKind.Function]: localize('Function', "function"),
		[SymbolKind.Interface]: localize('Interface', "interface"),
		[SymbolKind.Key]: localize('Key', "key"),
		[SymbolKind.Method]: localize('Method', "method"),
		[SymbolKind.Module]: localize('Module', "module"),
		[SymbolKind.Namespace]: localize('Namespace', "namespace"),
		[SymbolKind.Null]: localize('Null', "null"),
		[SymbolKind.Number]: localize('Number', "number"),
		[SymbolKind.Object]: localize('Object', "object"),
		[SymbolKind.Operator]: localize('Operator', "operator"),
		[SymbolKind.Package]: localize('Package', "package"),
		[SymbolKind.Property]: localize('Property', "property"),
		[SymbolKind.String]: localize('String', "string"),
		[SymbolKind.Struct]: localize('Struct', "struct"),
		[SymbolKind.TypeParameter]: localize('TypeParameter', "type parameter"),
		[SymbolKind.Variable]: localize('Variable', "variable"),
	};

	disposeTemplate(_template: OutlineElementTemplate): void {
		_template.iconLabel.dispose();
	}
}

export const enum OutlineSortOrder {
	ByPosition,
	ByName,
	ByKind
}

export class OutlineItemComparator implements ITreeSorter<OutlineItem> {

	private readonly _collator = new IdleValue<Intl.Collator>(() => new Intl.Collator(undefined, { numeric: true }));

	constructor(
		public type: OutlineSortOrder = OutlineSortOrder.ByPosition
	) { }

	compare(a: OutlineItem, b: OutlineItem): number {
		if (a instanceof OutlineGroup && b instanceof OutlineGroup) {
			return a.providerIndex - b.providerIndex;

		} else if (a instanceof OutlineElement && b instanceof OutlineElement) {
			if (this.type === OutlineSortOrder.ByKind) {
				return a.symbol.kind - b.symbol.kind || this._collator.getValue().compare(a.symbol.name, b.symbol.name);
			} else if (this.type === OutlineSortOrder.ByName) {
				return this._collator.getValue().compare(a.symbol.name, b.symbol.name) || Range.compareRangesUsingStarts(a.symbol.range, b.symbol.range);
			} else if (this.type === OutlineSortOrder.ByPosition) {
				return Range.compareRangesUsingStarts(a.symbol.range, b.symbol.range) || this._collator.getValue().compare(a.symbol.name, b.symbol.name);
			}
		}
		return 0;
	}
}

export class OutlineDataSource implements IDataSource<OutlineModel, OutlineItem> {

	getChildren(element: undefined | OutlineModel | OutlineGroup | OutlineElement): OutlineItem[] {
		if (!element) {
			return [];
		}
		return values(element.children);
	}
}


text:
package reactor.netty.http.server.logging;

import io.netty.channel.ChannelDuplexHandler;
import reactor.util.annotation.Nullable;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.function.Function;

import static reactor.netty.http.server.logging.AbstractAccessLogArgProvider.MISSING;

/**
 * @author limaoning
 */
class BaseAccessLogHandler extends ChannelDuplexHandler {

	static final String DEFAULT_LOG_FORMAT =
			"{} - {} [{}] \"{} {} {}\" {} {} {}";

	@SuppressWarnings("deprecation")
	static final Function<AccessLogArgProvider, AccessLog> DEFAULT_ACCESS_LOG =
			args -> AccessLog.create(DEFAULT_LOG_FORMAT, applyAddress(args.remoteAddress()), args.user(),
					args.zonedDateTime(), args.method(), args.uri(), args.protocol(), args.status(),
					args.contentLength() > -1 ? args.contentLength() : MISSING, args.duration());

	final Function<AccessLogArgProvider, AccessLog> accessLog;

	BaseAccessLogHandler(@Nullable Function<AccessLogArgProvider, AccessLog> accessLog) {
		this.accessLog = accessLog == null ? DEFAULT_ACCESS_LOG : accessLog;
	}

	static String applyAddress(@Nullable SocketAddress socketAddress) {
		return socketAddress instanceof InetSocketAddress ? ((InetSocketAddress) socketAddress).getHostString() : MISSING;
	}

}


text:
package com.unsis.calificaciones.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;

import com.fasterxml.jackson.annotation.JsonView;

/**
 * Modelo para la planeación de la aplicación, con sus atributos y métodos
 * getter y setter
 *
 */
@Entity
@Table(name = "planeacion", schema = "calificaciones")
public class Planeacion implements Serializable {

	private static final long serialVersionUID = 5734234042169487936L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	@JsonView(DataTablesOutput.View.class)
	private int id;

	@OneToOne
	@JoinColumn(name = "practica")
	@JsonView(DataTablesOutput.View.class)
	private Practica practica;

	@OneToOne
	@JoinColumn(name = "sede")
	@JsonView(DataTablesOutput.View.class)
	private Sede sede;

	@NotNull(message = "Por favor ingrese un ciclo escolar")
	@Column(name = "ciclo_escolar", length = 40)
	@JsonView(DataTablesOutput.View.class)
	private String cicloEscolar;

	@NotNull(message = "Por favor ingrese un periodo escolar")
	@Column(name = "periodo_escolar", length = 40)
	@JsonView(DataTablesOutput.View.class)
	private String periodoEscolar;

	@Column(name = "fecha_inicio", length = 40)
	@JsonView(DataTablesOutput.View.class)
	private String fechaInicio;

	@Column(name = "fecha_fin", length = 40)
	@JsonView(DataTablesOutput.View.class)
	private String fechaFin;

	public Planeacion() {

	}

	public Planeacion(Practica practica, Sede sede, String cicloEscolar, String periodoEscolar,
			String fechaInicio, String fechaFin) {
		super();
		this.practica = practica;
		this.sede = sede;
		this.cicloEscolar = cicloEscolar;
		this.periodoEscolar = periodoEscolar;
		this.fechaInicio = fechaInicio;
		this.fechaFin = fechaFin;
	}

	@Override
	public String toString() {
		return "INFORMACION DEL Planeacion \n [id=" + id + "\n practica=" + practica + "\n sede=" + sede
				+ "\n cicloEscolar=" + cicloEscolar + "\n periodoEscolar=" + periodoEscolar + "\n fechaInicio="
				+  fechaInicio + "\n fechaFin="+ fechaFin+"]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Practica getPractica() {
		return practica;
	}

	public void setPractica(Practica practica) {
		this.practica = practica;
	}

	public Sede getSede() {
		return sede;
	}

	public void setSede(Sede sede) {
		this.sede = sede;
	}

	public String getCicloEscolar() {
		return cicloEscolar;
	}

	public void setCicloEscolar(String cicloEscolar) {
		this.cicloEscolar = cicloEscolar;
	}

	public String getPeriodoEscolar() {
		return periodoEscolar;
	}

	public void setPeriodoEscolar(String periodoEscolar) {
		this.periodoEscolar = periodoEscolar;
	}

	public String getFechaInicio() {
		return fechaInicio;
	}

	public void setFechaInicio(String fechaInicio) {
		this.fechaInicio = fechaInicio;
	}

	public String getFechaFin() {
		return fechaFin;
	}

	public void setFechaFin(String fechaFin) {
		this.fechaFin = fechaFin;
	}

}


text:
module Mongoid
  module Textile
    VERSION = '1.0.0'
  end
end


text:
def catalyst_pmid_request(first, middle, last, email, debug=False):
    """
    Give an author name at the University of Florida, return the PMIDs of
    papers that are likely to be the works of the author.  The Harvard
    Catalyst GETPMIDS service is called.

    Uses HTTP XML Post request, by www.forceflow.be
    """
    request = tempita.Template("""
        <?xml version="1.0"?>
        <FindPMIDs>
            <Name>
                <First>{{first}}</First>
                <Middle>{{middle}}</Middle>
                <Last>{{last}}</Last>
                <Suffix/>
            </Name>
            <EmailList>
                <email>{{email}}</email>
            </EmailList>
            <AffiliationList>
                <Affiliation>%university of florida%</Affiliation>
                <Affiliation>%@ufl.edu%</Affiliation>
            </AffiliationList>
            <LocalDuplicateNames>1</LocalDuplicateNames>
            <RequireFirstName>false</RequireFirstName>
            <MatchThreshold>0.98</MatchThreshold>
        </FindPMIDs>""")
    HOST = "profiles.catalyst.harvard.edu"
    API_URL = "/services/GETPMIDs/default.asp"
    request = request.substitute(first=first, middle=middle, last=last, \
        email=email)
    webservice = httplib.HTTP(HOST)
    webservice.putrequest("POST", API_URL)
    webservice.putheader("Host", HOST)
    webservice.putheader("User-Agent", "Python post")
    webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
    webservice.putheader("Content-length", "%d" % len(request))
    webservice.endheaders()
    webservice.send(request)
    statuscode, statusmessage, header = webservice.getreply()
    result = webservice.getfile().read()
    if debug:
        print "Request", request
        print "StatusCode, Messgage,header", statuscode, statusmessage, header
        print "result", result
    return result


text:
package org.apache.flink.runtime.io.network.netty;

import org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf;

import org.junit.After;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/** Tests for the {@link NettyBufferPool} wrapper. */
public class NettyBufferPoolTest {

    private final List<ByteBuf> needReleasing = new ArrayList<>();

    @After
    public void tearDown() {
        try {
            // Release all of the buffers.
            for (ByteBuf buf : needReleasing) {
                buf.release();
            }

            // Checks in a separate loop in case we have sliced buffers.
            for (ByteBuf buf : needReleasing) {
                assertEquals(0, buf.refCnt());
            }
        } finally {
            needReleasing.clear();
        }
    }

    @Test
    public void testNoHeapAllocations() throws Exception {
        final NettyBufferPool nettyBufferPool = new NettyBufferPool(1);

        // Buffers should prefer to be direct
        assertTrue(releaseLater(nettyBufferPool.buffer()).isDirect());
        assertTrue(releaseLater(nettyBufferPool.buffer(128)).isDirect());
        assertTrue(releaseLater(nettyBufferPool.buffer(128, 256)).isDirect());

        // IO buffers should prefer to be direct
        assertTrue(releaseLater(nettyBufferPool.ioBuffer()).isDirect());
        assertTrue(releaseLater(nettyBufferPool.ioBuffer(128)).isDirect());
        assertTrue(releaseLater(nettyBufferPool.ioBuffer(128, 256)).isDirect());

        // Currently we fakes the heap buffer allocation with direct buffers
        assertTrue(releaseLater(nettyBufferPool.heapBuffer()).isDirect());
        assertTrue(releaseLater(nettyBufferPool.heapBuffer(128)).isDirect());
        assertTrue(releaseLater(nettyBufferPool.heapBuffer(128, 256)).isDirect());

        // Composite buffers allocates the corresponding type of buffers when extending its capacity
        assertTrue(releaseLater(nettyBufferPool.compositeHeapBuffer()).capacity(1024).isDirect());
        assertTrue(releaseLater(nettyBufferPool.compositeHeapBuffer(10)).capacity(1024).isDirect());

        // Is direct buffer pooled!
        assertTrue(nettyBufferPool.isDirectBufferPooled());
    }

    @Test
    public void testAllocationsStatistics() throws Exception {
        NettyBufferPool nettyBufferPool = new NettyBufferPool(1);
        int chunkSize = nettyBufferPool.getChunkSize();

        {
            // Single large buffer allocates one chunk
            releaseLater(nettyBufferPool.directBuffer(chunkSize - 64));
            long allocated = nettyBufferPool.getNumberOfAllocatedBytes().get();
            assertEquals(chunkSize, allocated);
        }

        {
            // Allocate a little more (one more chunk required)
            releaseLater(nettyBufferPool.directBuffer(128));
            long allocated = nettyBufferPool.getNumberOfAllocatedBytes().get();
            assertEquals(2 * chunkSize, allocated);
        }
    }

    private ByteBuf releaseLater(ByteBuf buf) {
        needReleasing.add(buf);
        return buf;
    }
}


text:
package org.apache.aiaravata.application.catalog.data.resources;

import org.airavata.appcatalog.cpi.AppCatalogException;
import org.apache.aiaravata.application.catalog.data.model.Workflow;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogJPAUtils;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogQueryGenerator;
import org.apache.aiaravata.application.catalog.data.util.AppCatalogResourceType;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class WorkflowResource extends AbstractResource {
    private final static Logger logger = LoggerFactory.getLogger(WorkflowResource.class);
    private String wfName;
    private String createdUser;
    private String graph;
    private String wfTemplateId;
    private Timestamp createdTime;
    private Timestamp updatedTime;
    private String image;

    public Timestamp getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Timestamp createdTime) {
        this.createdTime = createdTime;
    }

    public Timestamp getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(Timestamp updatedTime) {
        this.updatedTime = updatedTime;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public void remove(Object identifier) throws AppCatalogException {
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            generator.setParameter(WorkflowConstants.WF_TEMPLATE_ID, identifier);
            Query q = generator.deleteQuery(em);
            q.executeUpdate();
            em.getTransaction().commit();
            em.close();
        } catch (ApplicationSettingsException e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
    }

    @Override
    public Resource get(Object identifier) throws AppCatalogException {
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            generator.setParameter(WorkflowConstants.WF_TEMPLATE_ID, identifier);
            Query q = generator.selectQuery(em);
            Workflow workflow = (Workflow) q.getSingleResult();
            WorkflowResource workflowResource = (WorkflowResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.WORKFLOW, workflow);
            em.getTransaction().commit();
            em.close();
            return workflowResource;
        } catch (ApplicationSettingsException e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
    }

    @Override
    public List<Resource> get(String fieldName, Object value) throws AppCatalogException {
        List<Resource> workflowResources = new ArrayList<Resource>();
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            Query q;
            if ((fieldName.equals(WorkflowConstants.WF_NAME)) || (fieldName.equals(WorkflowConstants.CREATED_USER)) || (fieldName.equals(WorkflowConstants.GRAPH)) || (fieldName.equals(WorkflowConstants.WF_TEMPLATE_ID))) {
                generator.setParameter(fieldName, value);
                q = generator.selectQuery(em);
                List<?> results = q.getResultList();
                for (Object result : results) {
                    Workflow workflow = (Workflow) result;
                    WorkflowResource workflowResource = (WorkflowResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.WORKFLOW, workflow);
                    workflowResources.add(workflowResource);
                }
            } else {
                em.getTransaction().commit();
                em.close();
                logger.error("Unsupported field name for Workflow Resource.", new IllegalArgumentException());
                throw new IllegalArgumentException("Unsupported field name for Workflow Resource.");
            }
            em.getTransaction().commit();
            em.close();
        } catch (ApplicationSettingsException e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
        return workflowResources;
    }

    @Override
    public List<Resource> getAll() throws AppCatalogException {
        List<Resource> workflows = new ArrayList<Resource>();
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            Query q = generator.selectQuery(em);
            List results = q.getResultList();
            if (results.size() != 0) {
                for (Object result : results) {
                    Workflow workflow = (Workflow) result;
                    WorkflowResource wfResource =
                            (WorkflowResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.WORKFLOW, workflow);
                    workflows.add(wfResource);
                }
            }
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
        return workflows;
    }

    @Override
    public List<String> getAllIds() throws AppCatalogException {
        List<String> workflowIds = new ArrayList<String>();
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            Query q = generator.selectQuery(em);
            List results = q.getResultList();
            if (results.size() != 0) {
                for (Object result : results) {
                    Workflow workflow = (Workflow) result;
                    workflowIds.add(workflow.getWfTemplateId());
                }
            }
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
        return workflowIds;
    }

    @Override
    public List<String> getIds(String fieldName, Object value) throws AppCatalogException {
        List<String> workflowResourceIDs = new ArrayList<String>();
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            AppCatalogQueryGenerator generator = new AppCatalogQueryGenerator(WORKFLOW);
            Query q;
            if ((fieldName.equals(WorkflowConstants.WF_NAME)) || (fieldName.equals(WorkflowConstants.CREATED_USER)) || (fieldName.equals(WorkflowConstants.GRAPH)) || (fieldName.equals(WorkflowConstants.WF_TEMPLATE_ID))) {
                generator.setParameter(fieldName, value);
                q = generator.selectQuery(em);
                List<?> results = q.getResultList();
                for (Object result : results) {
                    Workflow workflow = (Workflow) result;
                    WorkflowResource workflowResource = (WorkflowResource) AppCatalogJPAUtils.getResource(AppCatalogResourceType.WORKFLOW, workflow);
                    workflowResourceIDs.add(workflowResource.getWfTemplateId());
                }
            } else {
                em.getTransaction().commit();
                em.close();
                logger.error("Unsupported field name for Workflow Resource.", new IllegalArgumentException());
                throw new IllegalArgumentException("Unsupported field name for Workflow Resource.");
            }
            em.getTransaction().commit();
            em.close();
        } catch (ApplicationSettingsException e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
        return workflowResourceIDs;
    }

    @Override
    public void save() throws AppCatalogException {
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            Workflow existingWorkflow = em.find(Workflow.class, wfTemplateId);
            em.close();
            Workflow workflow;
            em = AppCatalogJPAUtils.getEntityManager();
            em.getTransaction().begin();
            if (existingWorkflow == null) {
                workflow = new Workflow();
                workflow.setCreationTime(AiravataUtils.getCurrentTimestamp());
            } else {
                workflow = existingWorkflow;
                workflow.setUpdateTime(AiravataUtils.getCurrentTimestamp());
            }
            workflow.setWfName(getWfName());
            workflow.setCreatedUser(getCreatedUser());
            if (getGraph() != null){
                workflow.setGraph(getGraph().toCharArray());
            }
            if (image != null){
                workflow.setImage(image.getBytes());
            }
            workflow.setWfTemplateId(getWfTemplateId());
            if (existingWorkflow == null) {
                em.persist(workflow);
            } else {
                em.merge(workflow);
            }
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
    }

    @Override
    public boolean isExists(Object identifier) throws AppCatalogException {
        EntityManager em = null;
        try {
            em = AppCatalogJPAUtils.getEntityManager();
            Workflow workflow = em.find(Workflow.class, identifier);
            em.close();
            return workflow != null;
        } catch (ApplicationSettingsException e) {
            logger.error(e.getMessage(), e);
            throw new AppCatalogException(e);
        } finally {
            if (em != null && em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                em.close();
            }
        }
    }

    public String getWfName() {
        return wfName;
    }

    public String getCreatedUser() {
        return createdUser;
    }

    public String getGraph() {
        return graph;
    }

    public String getWfTemplateId() {
        return wfTemplateId;
    }

    public void setWfName(String wfName) {
        this.wfName=wfName;
    }

    public void setCreatedUser(String createdUser) {
        this.createdUser=createdUser;
    }

    public void setGraph(String graph) {
        this.graph=graph;
    }

    public void setWfTemplateId(String wfTemplateId) {
        this.wfTemplateId=wfTemplateId;
    }
}


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

namespace MyLightbulb
{
    public class LightbulbInterface
    {
        const byte ReadLightSwitchState = (byte)'R';
        const byte WriteLightSwitchState = (byte)'W';
        const byte ByteTrue = (byte)'T';
        const byte ByteFalse = (byte)'F';

        public string NetduinoIp { get; private set; }

        public int Port { get; set; }

        public LightbulbInterface(string netduinoIp, int port)
        {
            NetduinoIp = netduinoIp;
            Port = port;
        }

        public async Task SetLightSwitchStatus(bool on)
        {
            using (var s = new Sockets.Plugin.TcpSocketClient())
            {
                await s.ConnectAsync(NetduinoIp, Port);
                byte[] data = new byte[2];
                data[0] = WriteLightSwitchState;
                data[1] = (byte)(on ? ByteTrue : ByteFalse);
                s.WriteStream.Write(data, 0, 2);
            }
        }

        public async Task<bool> GetLightSwitchStatus()
        {
            using (var s = new Sockets.Plugin.TcpSocketClient())
            {
                await s.ConnectAsync(NetduinoIp, Port);
                byte[] data = new byte[2];
                data[0] = ReadLightSwitchState;
                data[1] = ReadLightSwitchState;
                s.WriteStream.Write(data, 0, 2);
                s.ReadStream.Read(data, 0, 1);
                return data[0] == ByteTrue;
            }
        }
    }
}


text:
package de.escidocng.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import de.escidocng.model.Settings;
import de.escidocng.model.security.annotation.Permission;
import de.escidocng.model.security.annotation.PreAuth;
import de.escidocng.model.security.role.Role.RoleName;
import de.escidocng.service.RepositoryService;
import de.escidocng.service.backend.BackendBlobstoreService;
import de.escidocng.service.backend.BackendEntityService;

/**
 * Web Controller responsible for Settings views.
 */
@RequestMapping("/settings")
@Controller
public class SettingsController extends AbstractEscidocngController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BackendBlobstoreService blobstoreService;

    @Autowired
    private BackendEntityService entityService;

    @Autowired
    private Environment environment;

    /**
     * Controller method for retrieval of a JSON representation of the
     * {@link de.escidocng.model.Settings}.
     * Settings contain all configuration-parameters of the system.
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @PreAuth(permissions = {
            @Permission(rolename = RoleName.ROLE_ADMIN) })
    public Settings retrieve() throws IOException {
        return this.createSettings();
    }

    /**
     * Create Settings-Object.
     *
     * @return Settings settings
     * @throws IOException
     */
    private Settings createSettings() throws IOException {
        final Settings settings = new Settings();
        settings.setEscidocngState(this.repositoryService.status());
        settings.setDescribe(this.repositoryService.describe());
        settings.setIndexState(this.entityService.status());
        settings.setBlobstoreState(this.blobstoreService.status());
        settings.setEscidocngClusterName(environment.getProperty("escidocng.cluster.name"));
        settings.setEscidocngVersion(environment.getProperty("escidocng.version"));
        settings.setEscidocngExportEnabled(
                Boolean.parseBoolean(environment.getProperty("escidocng.export.auto")));
        settings.setEscidocngExportPath(environment.getProperty("escidocng.export.path"));
        settings.setEscidocngCsrfProtectionEnabled(
                Boolean.parseBoolean(environment.getProperty("escidocng.security.csrf.enabled")));
        settings.setEscidocngMessagingEnabled(
                Boolean.parseBoolean(environment.getProperty("escidocng.messaging.enabled")));
        settings.setEscidocngMessagingBrokerUri(environment.getProperty("escidocng.messaging.broker.uri"));
        settings.setEscidocngMessagingBrokerPath(environment.getProperty("escidocng.messaging.path.data"));
        settings.setEscidocngMailEnabled(
                Boolean.parseBoolean(environment.getProperty("escidocng.mail.enabled")));
        settings.setEscidocngMailFrom(environment.getProperty("escidocng.mail.from"));
        settings.setEscidocngMailSmtpHost(environment.getProperty("escidocng.mail.smtp.host"));
        settings.setEscidocngMailSmtpPort(
                Integer.parseInt(environment.getProperty("escidocng.mail.smtp.port")));
        settings.setEscidocngMailSmtpUser(environment.getProperty("escidocng.mail.smtp.user"));
        settings.setEscidocngMailSmtpPass(environment.getProperty("escidocng.mail.smtp.pass"));
        settings.setElasticSearchClusterName(environment.getProperty("elasticsearch.escidocng.cluster.name"));
        settings.setElasticSearchLogPath(environment.getProperty("elasticsearch.path.logs"));
        settings.setElasticSearchDataPath(environment.getProperty("elasticsearch.path.data"));
        settings.setElasticSearchBootstrapMlockAll(
                environment.getProperty("elasticsearch.bootstrap.mlockall"));
        settings.setElasticSearchBindHost(
                environment.getProperty("elasticsearch.network.bind.host"));
        settings.setElasticSearchExpectedNodes(
                Integer.parseInt(environment.getProperty("elasticsearch.gateway.expected_nodes")));
        settings.setElasticSearchHttpPort(
                Integer.parseInt(environment.getProperty("elasticsearch.http.port")));
        settings.setElasticSearchHttpEnabled(
                Boolean.parseBoolean(environment.getProperty("elasticsearch.http.enabled")));
        settings.setElasticSearchGatewayType(environment.getProperty("elasticsearch.gateway.type"));
        settings.setElasticSearchConfigPath(environment.getProperty("elasticsearch.config.path"));
        settings.setSpringActiveProfile(environment.getProperty("spring.profiles.active"));
        settings.setSpringShowBanner(environment.getProperty("spring.main.show-banner"));
        settings.setEscidocngLogPath(environment.getProperty("logging.path"));
        settings.setEscidocngLogFile(environment.getProperty("logging.file"));
        settings.setEscidocngServerPort(Integer.parseInt(environment.getProperty("server.port")));
        settings.setTomcatAccessLogEnabled(
                Boolean.parseBoolean(environment.getProperty("server.tomcat.access-log-enabled")));
        settings.setJsonPrettyPrintEnabled(
                Boolean.parseBoolean(environment.getProperty("http.mappers.json-pretty-print")));
        settings.setSpringJmxEnabled(
                Boolean.parseBoolean(environment.getProperty("spring.jmx.enabled")));
        settings.setSpringEndpointAutoconfigEnabled(
                Boolean.parseBoolean(environment.getProperty("endpoints.autoconfig.enabled")));
        settings.setSpringEndpointBeansEnabled(
                Boolean.parseBoolean(environment.getProperty("endpoints.beans.enabled")));
        settings.setSpringEndpointConfigPropsEnabled(
                Boolean.parseBoolean(environment.getProperty("endpoints.configprops.enabled")));
        settings.setSpringEndpointDumpEnabled(
                Boolean.parseBoolean(environment.getProperty("endpoints.dump.enabled")));
        settings.setSpringEndpointEnvEnabled(
                Boolean.parseBoolean(environment.getProperty("endpoints.env.enabled")));
        settings.setSpringEndpointHealthEnabled(Boolean.parseBoolean(environment
                .getProperty("endpoints.health.enabled")));
        settings.setSpringEndpointInfoEnabled(Boolean.parseBoolean(environment.getProperty("endpoints.info.enabled")));
        settings.setSpringEndpointMetricsEnabled(Boolean.parseBoolean(environment
                .getProperty("endpoints.metrics.enabled")));
        settings.setSpringEndpointShutdownEnabled(Boolean.parseBoolean(environment
                .getProperty("endpoints.shutdown.enabled")));
        settings.setSpringEndpointTraceEnabled(Boolean.parseBoolean(environment
                .getProperty("endpoints.trace.enabled")));
        settings.setSpringEndpointJolokiaEnabled(Boolean.parseBoolean(environment
                .getProperty("endpoints.jolokia.enabled")));
        settings.setSpringEndpointJMXEnabled(Boolean.parseBoolean(environment.getProperty("endpoints.jmx.enabled")));
        settings.setSpringShellEnabled(Boolean.parseBoolean(environment.getProperty("shell.ssh.enabled")));
        settings.setSpringShellPathPatterns(environment.getProperty("shell.commandPathPatterns"));
        return settings;
    }
}


text:
require.config({
    baseUrl: "scripts",
    paths: {
        "container": "../../../minified/container"
    }
});
require(["container"], function( ContainerJS ) {

    var container = new ContainerJS.Container( function( binder ){

        binder.bind("app.View").withProperties({
            elementId : "console"
        }).onInitialize("initialize")
        .inScope(ContainerJS.Scope.EAGER_SINGLETON);

        binder.bind("app.Model");

    });
    container.onEagerSingletonConponentsInitialized.then(function() {
        container.get("app.Model").then(function( model ){
            model.initialize();
        }, function( error ) {
            alert( error.toString() );
        });
    });

});


text:
package ingress

import (
	"context"
	"flag"
	"fmt"
	"log"
	"time"

	"code.cloudfoundry.org/go-loggregator"
	"code.cloudfoundry.org/go-loggregator/rpc/loggregator_v2"
	"github.com/apoydence/loggr/internal/commands"
)

type logs struct {
	fs       *flag.FlagSet
	addr     string
	caCert   string
	cert     string
	key      string
	number   uint64
	sourceId string
}

func NewLogs() commands.Command {
	l := &logs{
		fs: flag.NewFlagSet("logs", flag.ExitOnError),
	}

	l.fs.StringVar(&l.addr, "addr", "", "Loggregator's egress address (REQUIRED)")
	l.fs.StringVar(&l.caCert, "ca-cert", "", "CA Cert file path (REQUIRED)")
	l.fs.StringVar(&l.cert, "cert", "", "Cert file path (REQUIRED)")
	l.fs.StringVar(&l.key, "key", "", "Key file path (REQUIRED)")

	l.fs.Uint64Var(&l.number, "number", 0, "The number of lines to read")
	l.fs.Uint64Var(&l.number, "n", 0, "The number of lines to read")
	l.fs.StringVar(&l.sourceId, "source-id", "", "The source ID to filter upon")

	return l
}

func (l *logs) Run(args []string, _ *log.Logger) {
	l.fs.Parse(args)

	if l.sourceId == "" || l.addr == "" || l.caCert == "" || l.cert == "" || l.key == "" {
		log.Fatalf("source-id, addr, ca-cert, cert and key are required")
	}

	tlsConfig, err := loggregator.NewEgressTLSConfig(
		l.caCert,
		l.cert,
		l.key,
	)
	if err != nil {
		log.Fatal("Could not create TLS config", err)
	}

	client, closer, err := loggregator.NewEgressClient(l.addr, tlsConfig)
	if err != nil {
		log.Fatal(err)
	}
	defer closer.Close()

	rx, err := client.Receiver(context.Background(), &loggregator_v2.EgressRequest{
		Filter: &loggregator_v2.Filter{
			SourceId: l.sourceId,
			Message: &loggregator_v2.Filter_Log{
				Log: &loggregator_v2.LogFilter{},
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	defer rx.CloseSend()

	for j := uint64(0); j < l.number || l.number == 0; j++ {
		e, err := rx.Recv()
		if err != nil {
			log.Fatal(err)
		}

		if e.GetLog() == nil {
			continue
		}

		fmt.Printf("%v [%s] %s\n",
			time.Unix(0, e.Timestamp),
			l.logType(e.GetLog().GetType()),
			e.GetLog().GetPayload(),
		)
	}
}

func (l *logs) Usage() string {
	return `usage: ingress logs command [args...]`
}

func (l *logs) logType(t loggregator_v2.Log_Type) string {
	if t == loggregator_v2.Log_OUT {
		return "STDOUT"
	}

	return "STDERR"
}


text:
/*
 *******************************************************************************
 * (C) Copyright IBM Corp. 1996-2005 - All Rights Reserved                     *
 *                                                                             *
 * The original version of this source code and documentation is copyrighted   *
 * and owned by IBM, These materials are provided under terms of a License     *
 * Agreement between IBM and Sun. This technology is protected by multiple     *
 * US and International patents. This notice and attribution to IBM may not    *
 * to removed.                                                                 *
 *******************************************************************************
 */

package sun.text.normalizer;

import java.util.Iterator;

/**
 * UnicodeSetIterator iterates over the contents of a UnicodeSet.  It
 * iterates over either code points or code point ranges.  After all
 * code points or ranges have been returned, it returns the
 * multicharacter strings of the UnicodSet, if any.
 *
 *
To iterate over code points, use a loop like this:
 *

 * UnicodeSetIterator it(set);
 * while (set.next()) {
 *   if (set.codepoint != UnicodeSetIterator::IS_STRING) {
 *     processCodepoint(set.codepoint);
 *   } else {
 *     processString(set.string);
 *   }
 * }
 *

 *
 *
To iterate over code point ranges, use a loop like this:
 *

 * UnicodeSetIterator it(set);
 * while (set.nextRange()) {
 *   if (set.codepoint != UnicodeSetIterator::IS_STRING) {
 *     processCodepointRange(set.codepoint, set.codepointEnd);
 *   } else {
 *     processString(set.string);
 *   }
 * }
 *

 * @author M. Davis
 * @stable ICU 2.0
 */
public class UnicodeSetIterator {

    /**
     * Value of <tt>codepoint</tt> if the iterator points to a string.
     * If <tt>codepoint == IS_STRING</tt>, then examine
     * <tt>string</tt> for the current iteration result.
     * @stable ICU 2.0
     */
    public static int IS_STRING = -1;

    /**
     * Current code point, or the special value <tt>IS_STRING</tt>, if
     * the iterator points to a string.
     * @stable ICU 2.0
     */
    public int codepoint;

    /**
     * When iterating over ranges using <tt>nextRange()</tt>,
     * <tt>codepointEnd</tt> contains the inclusive end of the
     * iteration range, if <tt>codepoint != IS_STRING</tt>.  If
     * iterating over code points using <tt>next()</tt>, or if
     * <tt>codepoint == IS_STRING</tt>, then the value of
     * <tt>codepointEnd</tt> is undefined.
     * @stable ICU 2.0
     */
    public int codepointEnd;

    /**
     * If <tt>codepoint == IS_STRING</tt>, then <tt>string</tt> points
     * to the current string.  If <tt>codepoint != IS_STRING</tt>, the
     * value of <tt>string</tt> is undefined.
     * @stable ICU 2.0
     */
    public String string;

    /**
     * Create an iterator over the given set.
     * @param set set to iterate over
     * @stable ICU 2.0
     */
    public UnicodeSetIterator(UnicodeSet set) {
        reset(set);
    }

    /**
     * Returns the next element in the set, either a code point range
     * or a string.  If there are no more elements in the set, return
     * false.  If <tt>codepoint == IS_STRING</tt>, the value is a
     * string in the <tt>string</tt> field.  Otherwise the value is a
     * range of one or more code points from <tt>codepoint</tt> to
     * <tt>codepointeEnd</tt> inclusive.
     *
     *
The order of iteration is all code points ranges in sorted
     * order, followed by all strings sorted order.  Ranges are
     * disjoint and non-contiguous.  <tt>string</tt> is undefined
     * unless <tt>codepoint == IS_STRING</tt>.  Do not mix calls to
     * <tt>next()</tt> and <tt>nextRange()</tt> without calling
     * <tt>reset()</tt> between them.  The results of doing so are
     * undefined.
     *
     * @return true if there was another element in the set and this
     * object contains the element.
     * @stable ICU 2.0
     */
    public boolean nextRange() {
        if (nextElement <= endElement) {
            codepointEnd = endElement;
            codepoint = nextElement;
            nextElement = endElement+1;
            return true;
        }
        if (range < endRange) {
            loadRange(++range);
            codepointEnd = endElement;
            codepoint = nextElement;
            nextElement = endElement+1;
            return true;
        }

        // stringIterator == null iff there are no string elements remaining

        if (stringIterator == null) return false;
        codepoint = IS_STRING; // signal that value is actually a string
        string = (String)stringIterator.next();
        if (!stringIterator.hasNext()) stringIterator = null;
        return true;
    }

    /**
     * Sets this iterator to visit the elements of the given set and
     * resets it to the start of that set.  The iterator is valid only
     * so long as <tt>set</tt> is valid.
     * @param set the set to iterate over.
     * @stable ICU 2.0
     */
    public void reset(UnicodeSet set) {
        this.set = set;
        reset();
    }

    /**
     * Resets this iterator to the start of the set.
     * @stable ICU 2.0
     */
    public void reset() {
        endRange = set.getRangeCount() - 1;
        range = 0;
        endElement = -1;
        nextElement = 0;
        if (endRange >= 0) {
            loadRange(range);
        }
        stringIterator = null;
        if (set.strings != null) {
            stringIterator = set.strings.iterator();
            if (!stringIterator.hasNext()) stringIterator = null;
        }
    }

    // ======================= PRIVATES ===========================

    private UnicodeSet set;
    private int endRange = 0;
    private int range = 0;
    /**
     * @internal
     */
    protected int endElement;
    /**
     * @internal
     */
    protected int nextElement;
    private Iterator stringIterator = null;

    /**
     * Invariant: stringIterator is null when there are no (more) strings remaining
     */

    /**
     * @internal
     */
    protected void loadRange(int range) {
        nextElement = set.getRangeStart(range);
        endElement = set.getRangeEnd(range);
    }
}


text:
package com.androlua;

import android.content.*;
import android.content.res.*;
import android.graphics.*;
import java.io.*;
import java.net.*;

public class LuaBitmap
{
	public static Bitmap getLoacalBitmap(String url) throws FileNotFoundException, IOException
	{

		FileInputStream fis = new FileInputStream(url);
		Bitmap bitmap= BitmapFactory.decodeStream(fis);
		fis.close();
		return bitmap;
	}

	public static Bitmap getHttpBitmap(String url) throws IOException
	{
		//Log.d(TAG, url);
		URL myFileUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
		//conn.setConnectTimeout(0);
		conn.setDoInput(true);
		conn.connect();
		InputStream is = conn.getInputStream();
		Bitmap bitmap = BitmapFactory.decodeStream(is);
		///Bitmap bitmap =decodeScale(is);
		is.close();
		return bitmap;
	}

	public static Bitmap getAssetBitmap(Context context, String name) throws IOException
	{
		AssetManager am = context.getAssets();
		InputStream is = am.open(name);
		Bitmap bitmap= BitmapFactory.decodeStream(is);
		is.close();
		return bitmap;
	}

	private static Bitmap decodeScale(InputStream fis)
	{
		Bitmap b = null;

		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(fis, null, o);
		int scale = 1;
		int IMAGE_MAX_SIZE = 720;
		if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE)
		{
			scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
		}
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		b = BitmapFactory.decodeStream(fis, null, o2);

		return b;
	}

	public static Bitmap getImageFromPath( String filePath )
	{

		Bitmap bitmap = null;
		BitmapFactory.Options opts = new BitmapFactory.Options( );
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile( filePath,opts );

		//缩放图片,避免内存不足
		opts.inSampleSize = computeSampleSize( opts,-1,250 * 250 );
		opts.inJustDecodeBounds = false;

		try
		{
			bitmap = BitmapFactory.decodeFile( filePath,opts );
		}
		catch (Exception e)
		{
			// TODO: handle exception
		}
		return bitmap;
	}

	//缩放图片算法
	private static int computeSampleSize( BitmapFactory.Options options,int minSideLength,int maxNumOfPixels )
	{
		int initialSize = computeInitialSampleSize( options,minSideLength,maxNumOfPixels );
		int roundedSize;
		if (initialSize <= 8)
		{
			roundedSize = 1;
			while (roundedSize < initialSize)
			{
				roundedSize <<= 1;
			}
		}
		else
		{
			roundedSize = (initialSize + 7) / 8 * 8;
		}
		return roundedSize;
	}

	private static int computeInitialSampleSize( BitmapFactory.Options options,int minSideLength,int maxNumOfPixels )
	{
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil( Math.sqrt( w * h / maxNumOfPixels ) );
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( Math.floor( w / minSideLength ),Math.floor( h / minSideLength ) );
		if (upperBound < lowerBound)
		{
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1))
		{
			return 1;
		}
		else if (minSideLength == -1)
		{
			return lowerBound;
		}
		else
		{
			return upperBound;
		}
	}
}


text:
import test from '@ava/test';

import {fixture} from '../../helpers/exec.js';

test('shared workers are loaded only once', async t => {
	const result = await fixture();
	const logs = result.stats.passed.map(object => result.stats.getLogs(object));
	t.is(logs.length, 2);
	t.deepEqual(logs[0], logs[1]);
});


text:
package com.travelport.schema.air_v29_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://www.travelport.com/schema/air_v29_0}FareNote" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="ChangeOfPlane" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
 *       <attribute name="ChangeOfTerminal" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
 *       <attribute name="ChangeOfAirport" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
 *       <attribute name="StopOver" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
 *       <attribute name="MinConnectionTime" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="Duration" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="SegmentIndex" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="FlightDetailsIndex" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="IncludeStopOverToFareQuote" type="{http://www.travelport.com/schema/air_v29_0}typeIgnoreStopOver" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "fareNote"
})
@XmlRootElement(name = "Connection")
public class Connection {

    @XmlElement(name = "FareNote")
    protected FareNote fareNote;
    @XmlAttribute(name = "ChangeOfPlane")
    protected Boolean changeOfPlane;
    @XmlAttribute(name = "ChangeOfTerminal")
    protected Boolean changeOfTerminal;
    @XmlAttribute(name = "ChangeOfAirport")
    protected Boolean changeOfAirport;
    @XmlAttribute(name = "StopOver")
    protected Boolean stopOver;
    @XmlAttribute(name = "MinConnectionTime")
    protected Integer minConnectionTime;
    @XmlAttribute(name = "Duration")
    protected Integer duration;
    @XmlAttribute(name = "SegmentIndex")
    protected Integer segmentIndex;
    @XmlAttribute(name = "FlightDetailsIndex")
    protected Integer flightDetailsIndex;
    @XmlAttribute(name = "IncludeStopOverToFareQuote")
    protected TypeIgnoreStopOver includeStopOverToFareQuote;

    /**
     * Gets the value of the fareNote property.
     *
     * @return
     *     possible object is
     *     {@link FareNote }
     *
     */
    public FareNote getFareNote() {
        return fareNote;
    }

    /**
     * Sets the value of the fareNote property.
     *
     * @param value
     *     allowed object is
     *     {@link FareNote }
     *
     */
    public void setFareNote(FareNote value) {
        this.fareNote = value;
    }

    /**
     * Gets the value of the changeOfPlane property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public boolean getChangeOfPlane() {
        if (changeOfPlane == null) {
            return false;
        } else {
            return changeOfPlane;
        }
    }

    /**
     * Sets the value of the changeOfPlane property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setChangeOfPlane(Boolean value) {
        this.changeOfPlane = value;
    }

    /**
     * Gets the value of the changeOfTerminal property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public boolean getChangeOfTerminal() {
        if (changeOfTerminal == null) {
            return false;
        } else {
            return changeOfTerminal;
        }
    }

    /**
     * Sets the value of the changeOfTerminal property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setChangeOfTerminal(Boolean value) {
        this.changeOfTerminal = value;
    }

    /**
     * Gets the value of the changeOfAirport property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public boolean getChangeOfAirport() {
        if (changeOfAirport == null) {
            return false;
        } else {
            return changeOfAirport;
        }
    }

    /**
     * Sets the value of the changeOfAirport property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setChangeOfAirport(Boolean value) {
        this.changeOfAirport = value;
    }

    /**
     * Gets the value of the stopOver property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public boolean getStopOver() {
        if (stopOver == null) {
            return false;
        } else {
            return stopOver;
        }
    }

    /**
     * Sets the value of the stopOver property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setStopOver(Boolean value) {
        this.stopOver = value;
    }

    /**
     * Gets the value of the minConnectionTime property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getMinConnectionTime() {
        return minConnectionTime;
    }

    /**
     * Sets the value of the minConnectionTime property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setMinConnectionTime(Integer value) {
        this.minConnectionTime = value;
    }

    /**
     * Gets the value of the duration property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getDuration() {
        return duration;
    }

    /**
     * Sets the value of the duration property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setDuration(Integer value) {
        this.duration = value;
    }

    /**
     * Gets the value of the segmentIndex property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getSegmentIndex() {
        return segmentIndex;
    }

    /**
     * Sets the value of the segmentIndex property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setSegmentIndex(Integer value) {
        this.segmentIndex = value;
    }

    /**
     * Gets the value of the flightDetailsIndex property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getFlightDetailsIndex() {
        return flightDetailsIndex;
    }

    /**
     * Sets the value of the flightDetailsIndex property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setFlightDetailsIndex(Integer value) {
        this.flightDetailsIndex = value;
    }

    /**
     * Gets the value of the includeStopOverToFareQuote property.
     *
     * @return
     *     possible object is
     *     {@link TypeIgnoreStopOver }
     *
     */
    public TypeIgnoreStopOver getIncludeStopOverToFareQuote() {
        return includeStopOverToFareQuote;
    }

    /**
     * Sets the value of the includeStopOverToFareQuote property.
     *
     * @param value
     *     allowed object is
     *     {@link TypeIgnoreStopOver }
     *
     */
    public void setIncludeStopOverToFareQuote(TypeIgnoreStopOver value) {
        this.includeStopOverToFareQuote = value;
    }

}


text:
layout: page_author
author_name: wsb2333
image: /images/userpic.gif
page_path: /authors/wangshubing/
page_tags: 标签
page_type: author
no_content: 暂无
description:
title: wsb2333
---

{% include authors_list.html %}


text:
/*
 * This file is part of the DITA Open Toolkit project.
 * See the accompanying license.txt file for applicable licenses.
 */

/*
 * (c) Copyright IBM Corp. 2005 All Rights Reserved.
 */
package org.dita.dost.exception;

import org.dita.dost.log.MessageBean;

/**
 * Exception class for DITAOT, used to handle exceptions in Java modules.
 *
 * @author Wu, Zhi Qiang
 */
public final class DITAOTException extends Exception {

    /** serial version. */
    private static final long serialVersionUID = -7505646495801170017L;
    /** message bean. */
    private MessageBean messageBean = null;
    /** capture flag. */
    private boolean captured = false;

    /**
     * Constructs a new DITAOTException with {@code null}
     * as its detail message.
     */
    public DITAOTException() {
        this(null, null);
    }

    /**
     * Constructs a new exception with the specified detail message.
     *
     * @param message the detail message
     */
    public DITAOTException(final String message) {
        this(message, null);
    }

    /**
     * Constructs a new exception with the specified detail cause.
     *
     * @param cause the cause
     */
    public DITAOTException(final Throwable cause) {
        this(null, cause);
    }

    /**
     * Constructs a new exception with the specified detail message and
     * cause.
     *
     * @param message the detail message.
     * @param cause the cause
     */
    public DITAOTException(final String message, final Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the detailed messagebean and
     * cause.
     *
     * @param msgBean the bean contains detailed information for log statistic.
     * @param cause the cause
     * @param message the detail message.
     */
    public DITAOTException(final MessageBean msgBean, final Throwable cause, final String message) {
        super(message, cause);
        messageBean = msgBean;
    }
    /**
     * Retrieve the MessageBean.
     *
     * @return MessageBean
     */
    public MessageBean getMessageBean() {
        return messageBean;
    }
    /**
     * To check whether the current exception has already been captured before.
     *
     * @return {@code true} if the exception has already solved, else {@code false}
     */
    public boolean alreadyCaptured() {
        return captured;
    }
    /**
     * To set the exception's status whether it is needed to solve.
     *
     * @param isCaptured boolean
     */
    public void setCaptured(final boolean isCaptured) {
        captured = isCaptured;
    }

}


text:
namespace wgt
{
class ValueExtension : public IModelExtension
{
	Q_OBJECT

	Q_PROPERTY( QQmlListProperty< QString > roles
		READ getRoles )

	Q_CLASSINFO( "DefaultProperty", "roles" )
public:
	ValueExtension();
	virtual ~ValueExtension();

	QHash< int, QByteArray > roleNames() const override;
	QVariant data( const QModelIndex &index, int role ) const override;
	bool setData( const QModelIndex &index,
		const QVariant &value,
		int role ) override;

	void onDataAboutToBeChanged( const QModelIndex &index,
		int role,
		const QVariant &value ) override;
	void onDataChanged( const QModelIndex &index,
		int role,
		const QVariant &value ) override;

private:
	QQmlListProperty< QString > getRoles() const;

	static void appendRole(
		QQmlListProperty< QString > * property,
		QString * value );
	static QString * roleAt(
		QQmlListProperty< QString > * property,
		int index );
	static void clearRoles(
		QQmlListProperty< QString > * property );
	static int countRoles(
		QQmlListProperty< QString > * property );

	QStringList roles_;
};
} // end namespace wgt
#endif // COMPONENT_EXTENSION_HPP


text:
using System;
using System.Collections.Generic;
using Traveller.Commands.Contracts;
using Traveller.Commands.Listing;
using Traveller.Core.Repository;

namespace Traveller.Commands.Creating
{
    public class ListJourneysCommand : ListCommand, ICommand
    {
        public ListJourneysCommand(IDatabase database) : base(database) { }

        public override string Execute(IList<string> parameters)
        {
            var journeys = base.Database.Journeys;

            if (journeys.Count == 0)
            {
                return "There are no registered journeys.";
            }

            return string.Join(Environment.NewLine + "####################" + Environment.NewLine, journeys);
        }
    }
}


text:
#import "AWSModel.h"

@class NSArray;

@interface AWSEC2VolumeStatusInfo : AWSModel {
	NSArray* _details;
	int _status;
}
@property(retain, nonatomic) NSArray* details;
@property(assign, nonatomic) int status;
+ (id)JSONKeyPathsByPropertyKey;
+ (id)detailsJSONTransformer;
+ (id)statusJSONTransformer;
- (void).cxx_destruct;
@end


text:
def iterPower(base, exp):
    '''
    base: int or float.
    exp: int >= 0

    returns: int or float, base^exp
    '''
    total = 1
    iterator = int(exp)
    while iterator > 0:
        total *= base
        iterator -= 1
    return total


text:
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE QuasiQuotes                #-}

module Data.KeyStore.Types.UTC (UTC(..)) where

import           Data.Aeson
import           Data.API.JSON
import           Data.Time
import           Text.RE.Replace
import           Text.RE.TDFA.String

-- | package time has some variation in the formatting of second fractions
-- in %Q (http://hackage.haskell.org/package/time-1.8.0.2/changelog) so we
-- we will standardise on ".xxx"
newtype UTC = UTC { _UTC :: UTCTime }
  deriving (Eq,Show)

instance ToJSON UTC where
  toJSON = toJSON . formatUTC

instance FromJSON UTC where
  parseJSON = fmap UTC . parseJSON

instance FromJSONWithErrs UTC where
  parseJSONWithErrs = fmap UTC . parseJSONWithErrs

formatUTC :: UTC -> String
formatUTC (UTC u) = cleanup $ formatTime defaultTimeLocale fmt u
  where
    fmt = iso8601DateFormat $ Just "%H:%M:%S%QZ"

cleanup :: String -> String
cleanup s = case (captureTextMaybe [cp|u|] mtch,captureTextMaybe [cp|q|] mtch) of
    (Just u,Nothing) -> u ++ ".000Z"
    (Just u,Just q ) -> u ++ "." ++ rjust q ++ "Z"
    _ -> s
  where
    mtch = s ?=~ [re|^${u}([T0-9:-]+)(.${q}([0-9]*))?Z$|]

    rjust ds = take 3 $ ds ++ "000"


text:
@def myConstant 15px;
@def my_constant 20px;
@def my-constant 25px;

@url myUrl imageName;
@url my_url imageName2;
@url my-url imageName3;

@eval myEval com.foo.bar.foo();
@eval my_eval com.foo.bar.foo();
@eval my-eval com.foo.bar.foo();

.foo {
  width: myConstant;
  height: my-constant;
  top: my_constant;
  left: myEval;

  cursor: myUrl;
}

.bar {
  width: myConstant;
  height: my-constant;
  top: my_constant;
  left: my_eval;

  cursor: my_url;
}

.blop {
  width: myConstant;
  height: my-constant;
  top: my_constant;
  left: my-eval;

  cursor: my-url;
}


text:
package org.engineFRP.Physics;

import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.dynamics.contacts.Contact;
import sodium.StreamSink;
import sodium.Tuple2;

/**
 * Created by TekMaTek on 07/04/2015.
 */
public class JBoxCollisionListener implements ContactListener {

    public static StreamSink<Contact> begin = new StreamSink<>();
    public static StreamSink<Contact> end = new StreamSink<>();
    public static StreamSink<Tuple2<Contact, Manifold>> preSolve = new StreamSink<>();
    public static StreamSink<Tuple2<Contact, ContactImpulse>> postSolve = new StreamSink<>();

    @Override
    public void beginContact(Contact contact) {
        begin.send(contact);
    }

    @Override
    public void endContact(Contact contact) {
        end.send(contact);
    }

    @Override
    public void preSolve(Contact contact, Manifold oldManifold) {
        preSolve.send(new Tuple2<>(contact, oldManifold));
    }

    @Override
    public void postSolve(Contact contact, ContactImpulse impulse) {
        postSolve.send(new Tuple2<>(contact, impulse));
    }
}


text:
import Ember from 'ember';

export default Ember.Component.extend({
  classNames: ['eui-pevent-page-scroll'],
  attributeBindings: ['style'],

  click: null,
  zIndex: 1000000,

  style: Ember.computed('zIndex', function() {
    let zIndex = parseInt(this.get('zIndex'));
    return new Ember.String.htmlSafe(`z-index: ${zIndex}`);
  }),

  setup: Ember.on('didInsertElement', function() {
    this.disablePageScroll();
  }),

  breakdown: Ember.on('willDestroyElement', function() {
    this.enablePageScroll();
  }),

  disablePageScroll: function() {
    let net = this.$().find('.eui-pevent-page-scroll--net');

    net.scrollTop(50000).scrollLeft(50000).addClass('eui-enabled');

    return net.scroll(function() {
      return window.$(this).scrollTop(50000).scrollLeft(50000);
    });
  },

  enablePageScroll: function() {
    return this.$().find('.eui-pevent-page-scroll--net').unbind('scroll');
  }
});


text:
个人Cocoapods资源用法:
1. `git clone git@bitbucket.org:XXXXX/podspec.git`
2. `pod repo add tkpodspec git@bitbucket.org:XXXXX/podspec.git`
3. 在项目Podfile文件里引用我相关的项目名称,如:
    ```
     # 私有库
     pod "TKPhoto",:head                #image基本工具类和部分全局函数
    ```
4. `pod install --verbose` and `pod update`

`例如:`
[https://github.com/nicolastinkl/TKCapture/blob/master/Podfile](https://github.com/nicolastinkl/TKCapture/blob/master/Podfile)


text:
import rpc, logging
import messages_pb2 as msg
import guid as Guid
import mds, config, util
import gevent.server
import Backend
from pytgt.tgt_ctrl import *
import random

class ChunkServer:
	def __init__(self, prefix_vol='lv_softsan_', vgname='VolGroup'):
		self.lvm = Backend.LVM_SOFTSAN()
		self.tgt = Tgt()
		self.prefix_vol = prefix_vol
		self.vgname = vgname

	#  always use lun_index=1.
	def AssembleVolume(self, req):
		self.tgt.reload()
		ret = msg.AssembleVolume_Response()
		str_guid = Guid.toStr(req.volume.guid)
		lv_name = self.prefix_vol+str_guid
		if not self.lvm.haslv(lv_name):
			ret.error = "Chunk {0} does not exist!".format(str_guid)
			return ret
		target_name = "iqn:softsan_"+str_guid
		target_id = self.tgt.target_name2target_id(target_name)
		if target_id != None:
			ret.access_point = target_name
			return ret
		while True:
			target_id = str(random.randint(0,1024*1024))
			if not self.tgt.is_in_targetlist(target_id):
				break
		lun_path = '/dev/'+self.vgname+'/'+lv_name
		if self.tgt.new_target_lun(target_id, target_name, lun_path, 'ALL')!=None:
			ret.error = "Failed to export chunk {0} with tgt".format(str_guid)
			return ret
		ret.access_point = target_name
		return ret

	def DisassembleVolume(self, req):
		self.tgt.reload()
		ret = msg.DisassembleVolume_Response()
		target_name = req.access_point
		target_id = self.tgt.target_name2target_id(target_name)
		if target_id==None:
			ret.error='No such access_point'
			return ret
		if self.tgt.delete_target(target_id)!=None:
			ret.error=('failed to Disassemble Volume'+target_name)
		return ret

	# try to create every requested chunk. however, if some chunk can not be created, fill the ret.error with the output of lvcreate
	def NewChunk(self, req):
		self.lvm.reload()
		ret = msg.NewChunk_Response()
		size = str(req.size)+'M'
		for i in range(req.count):
			a_guid = Guid.generate()
			lv_name = self.prefix_vol+Guid.toStr(a_guid)
			lv_size = size
			output =  self.lvm.lv_create(self.vgname, lv_name, lv_size)
			if output!=None:
				ret.error = str(i) + ':' + output + ' '
				break
			t=ret.guids.add()
			Guid.assign(t, a_guid)
		return ret

	# try to delete every requested chunk. if it can not delete, fill the ret.error with output of lvremove
	def DeleteChunk(self, req):
		self.lvm.reload()
		ret = msg.DeleteChunk_Response()
		print 'ChunkServer:  DeleteChunk'
		for a_guid in req.guids:
			str_guid=Guid.toStr(a_guid)
			lv_name = self.prefix_vol+str_guid
			lv_path = '/dev/'+self.vgname+'/'+lv_name
			output = self.lvm.lv_remove(lv_path)
			if output!=None:
				ret.error = "Unable to delete chunk {0}:\n{1}".format(str_guid, output)
				break
			t=ret.guids.add()
			Guid.assign(t, a_guid)
		return ret

	def doHeartBeat(self, serviceport, stub):
		serviceip=stub.socket.getsockname()[0]
		while True:
			info=msg.ChunkServerInfo()
			info.ServiceAddress=serviceip
			info.ServicePort=serviceport
			self.lvm.reload_softsan_lvs()
			for lv in self.lvm.softsan_lvs:
				chk=info.chunks.add()
				name4guid = lv.name.split(self.prefix_vol)[1]
				Guid.assign(chk.guid, Guid.fromStr(name4guid))
				chk.size = int(lv.get_sizes(lv.total_extents)[2])
			stub.callMethod('ChunkServerInfo', info)
			print 'for test--------------------------------', random.randint(0,100)
			gevent.sleep(1)

	def heartBeat(self, confobj):
		guid=Guid.generate()
		stub=rpc.RpcStub(guid, None, mds.MDS)
		while True:
			try:
				socket=gevent.socket.socket()
				socket.connect((confobj.mdsaddress, int(confobj.mdsport)))
				mdsEndpoint=(confobj.mdsaddress, int(confobj.mdsport))
				socket.connect(mdsEndpoint)
				stub.socket=socket
				self.doHeartBeat(int(confobj.port), stub)
			except KeyboardInterrupt:
				raise
			except:
				logging.debug('An error occured during heart beat, preparing to retry', exc_info=1)
				gevent.sleep(2)

def test_ChunkServer():
	print '     test begin     '.center(100,'-')
	print
	server=ChunkServer()
	logging.basicConfig(level=logging.DEBUG)

	# mock the newchunk request from client
	req_newchunk=msg.NewChunk_Request()
	req_newchunk.size=32
	req_newchunk.count=1
	ret_newchunk = server.NewChunk(req_newchunk)

	# mock the assemblevolume request from client
	req_assemblevolume=msg.AssembleVolume_Request()
	Guid.assign(req_assemblevolume.volume.guid, ret_newchunk.guids[-1])
	req_assemblevolume.volume.size=32
	ret_assemblevolume = server.AssembleVolume(req_assemblevolume)

	# # mock req_disassemblevolume
	req_disassemblevolume = msg.DisassembleVolume_Request()
	req_disassemblevolume.access_point = ret_assemblevolume.access_point
	ret_disassemblevolume = server.DisassembleVolume(req_disassemblevolume)

	# mock the delchunk request from client
	req_delchunk = msg.DeleteChunk_Request()
 	for a_guid in ret_newchunk.guids:
		t=req_delchunk.guids.add()
		Guid.assign(t, a_guid)
	ret_delchunk = server.DeleteChunk(req_delchunk)
	print
	print '     test end     '.center(100,'-')

if __name__=='__main__':
	pass
	# link_test()
	#test_ChunkServer()


text:
import json
from subprocess import Popen

if __name__ == "__main__":
    with open("hyperRand/config.json") as f:
        js = json.load(f)

    for val in xrange(js["host-range"][0], js["host-range"][1] + 1):
        ip = js["host-template"].replace("*", str(val))
        command = "ssh -i {} {}@{} ".format(js["key"], js["user"], ip)
        command += "\"python ~/hyperNN/hyperRand/runnee.py 20\""

        try:
            Popen(args=command, shell=True)
        except Exception as e:
            print("Error on {}: {}".format(ip, e))


text:
/******************************************************************************\
 * This example is a very basic, non-interactive math service implemented     *
 * for both the blocking and the event-based API.                             *
\******************************************************************************/

#include <cstdint>
#include <iostream>

#include "caf/all.hpp"

using std::cout;
using std::endl;
using namespace caf;

// --(rst-cell-begin)--
using cell = typed_actor<
  // 'put' updates the value of the cell.
  result<void>(put_atom, int32_t),
  // 'get' queries the value of the cell.
  result<int32_t>(get_atom)>;

struct cell_state {
  int32_t value = 0;
  static inline const char* name = "example.cell";
};

cell::behavior_type type_checked_cell(cell::stateful_pointer<cell_state> self) {
  return {
    [=](put_atom, int32_t val) { self->state.value = val; },
    [=](get_atom) { return self->state.value; },
  };
}

behavior unchecked_cell(stateful_actor<cell_state>* self) {
  return {
    [=](put_atom, int32_t val) { self->state.value = val; },
    [=](get_atom) { return self->state.value; },
  };
}
// --(rst-cell-end)--

void caf_main(actor_system& system) {
  // --(rst-spawn-cell-begin)--
  // Create one cell for each implementation.
  auto cell1 = system.spawn(type_checked_cell);
  auto cell2 = system.spawn(unchecked_cell);
  // --(rst-spawn-cell-end)--
  auto f = make_function_view(cell1);
  cout << "cell value: " << f(get_atom_v) << endl;
  f(put_atom_v, 20);
  cout << "cell value (after setting to 20): " << f(get_atom_v) << endl;
  // Get an unchecked cell and send it some garbage. Triggers an "unexpected
  // message" error (and terminates cell2!).
  anon_send(cell2, "hello there!");
}

CAF_MAIN()


text:
YellowCreepTwo::YellowCreepTwo(float x, float y, int wave, int levelIndex, int spawnPointIndex, bool isUsingAltPath) : YellowCreep (x, y, 0.60f, 0.60f, World::getHealthAdjustmentForWave(wave, 5), wave / 4 + 3, levelIndex, spawnPointIndex, isUsingAltPath)
{
	// No setup required
}

Creep_Type YellowCreepTwo::getCreepType()
{
	return Creep_Type::YELLOW_CREEP_TWO;
}

void YellowCreepTwo::scatterCreepBodyParts(std::vector<std::unique_ptr<CreepBodyPart>> &creepBodyParts)
{
	addCreepTwoBodyParts(creepBodyParts, 2.5f);
	addCreepBodyPartForCreep(creepBodyParts, Creep_Body_Part_Type::ASS_YELLOW_2, 2.5f, 180);
}


text:
#ifndef TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_WEBGL_H
#define TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_WEBGL_H

#include <stdint.h>

#include <backend/DriverEnums.h>

#include "private/backend/OpenGLPlatform.h"

#include <EGL/egl.h>
#include <EGL/eglext.h>

namespace filament::backend {

class PlatformWebGL final : public OpenGLPlatform {
public:

    Driver* createDriver(void* const sharedGLContext, const Platform::DriverConfig& driverConfig) noexcept override;
    void terminate() noexcept override;

    SwapChain* createSwapChain(void* nativewindow, uint64_t& flags) noexcept final override;
    SwapChain* createSwapChain(uint32_t width, uint32_t height, uint64_t& flags) noexcept final override;
    void destroySwapChain(SwapChain* swapChain) noexcept final override;
    void makeCurrent(SwapChain* drawSwapChain, SwapChain* readSwapChain) noexcept final override;
    void commit(SwapChain* swapChain) noexcept final override;

    Fence* createFence() noexcept final override;
    void destroyFence(Fence* fence) noexcept final override;
    FenceStatus waitFence(Fence* fence, uint64_t timeout) noexcept final override;

    void setPresentationTime(int64_t time) noexcept final override {}

    Stream* createStream(void* nativeStream) noexcept final override { return nullptr; }
    void destroyStream(Stream* stream) noexcept final override {}
    void attach(Stream* stream, intptr_t tname) noexcept final override {}
    void detach(Stream* stream) noexcept final override {}
    void updateTexImage(Stream* stream, int64_t* timestamp) noexcept final override {}

    int getOSVersion() const noexcept final override { return 0; }
};

} // namespace filament::backend

#endif // TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_WEBGL_H