text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Layouting
{
	using System;
	using System.Collections.Generic;
	using Fusion.Utils;
	using Fusion.Layouting.Data;

	internal class Group : Element, IGroup
	{
		private class Features
		{
			private Group _group;
			private Width _width;
			private Height _height;
			private Alignment _alignment;
			private Borders _borders;
			private Spacings _spacings;
			private Paddings _paddings;
			private Background _background;
			private Foreground _foreground;
			private bool? _stretch;
			private Visibility? _visibility;

			public Features(Group group)
			{
				_group = group;
			}

			public Width Width
			{
				get
				{
					if (_width == null)
						_width = (Width)_group.GetFeature(Element.Feature.Width);

					return _width;
				}
			}

			public Height Height
			{
				get
				{
					if (_height == null)
						_height = (Height)_group.GetFeature(Element.Feature.Height);

					return _height;
				}
			}

			public Alignment Alignment
			{
				get
				{
					if (_alignment == null)
						_alignment = (Alignment)_group.GetFeature(Element.Feature.Alignment);

					return _alignment;
				}
			}

			public Borders Borders
			{
				get
				{
					if (_borders == null)
						_borders = (Borders)_group.GetFeature(Element.Feature.Borders);

					return _borders;
				}
			}

			public Spacings Spacings
			{
				get
				{
					if (_spacings == null)
						_spacings = (Spacings)_group.GetFeature(Element.Feature.Spacings);

					return _spacings;
				}
			}

			public Paddings Paddings
			{
				get
				{
					if (_paddings == null)
						_paddings = (Paddings)_group.GetFeature(Element.Feature.Paddings);

					return _paddings;
				}
			}

			public Background Background
			{
				get
				{
					if (_background == null)
						_background = (Background)_group.GetFeature(Element.Feature.Background);

					return _background;
				}
			}

			public Foreground Foreground
			{
				get
				{
					if (_foreground == null)
						_foreground = (Foreground)_group.GetFeature(Element.Feature.Foreground);

					return _foreground;
				}
			}

			public bool Stretch
			{
				get
				{
					if (_stretch == null)
						_stretch = (bool?)_group.GetFeature(Element.Feature.Stretch);

					return _stretch.Value;
				}
			}

			public Visibility Visibility
			{
				get
				{
					if (_visibility == null)
						_visibility = (Visibility?)_group.GetFeature(Element.Feature.Visibility);

					return _visibility.Value;
				}
			}

			public void Reset(Feature feature)
			{
				switch (feature)
				{
					case Feature.Width:
						_width = null;

						break;

					case Feature.Height:
						_height = null;

						break;

					case Feature.Alignment:
						_alignment = null;

						break;

					case Feature.Borders:
						_borders = null;

						break;

					case Feature.Spacings:
						_spacings = null;

						break;

					case Feature.Paddings:
						_paddings = null;

						break;

					case Feature.Background:
						_background = null;

						break;

					case Feature.Foreground:
						_foreground = null;

						break;

					case Feature.Stretch:
						_stretch = null;

						break;

					case Feature.Visibility:
						_visibility = null;

						break;
				}
			}

			public void Reset()
			{
				_width = null;
				_height = null;
				_alignment = null;
				_borders = null;
				_spacings = null;
				_paddings = null;
				_background = null;
				_foreground = null;
				_stretch = null;
				_visibility = null;
			}
		}

		private Width _width;
		private Height _height;
		private Alignment _alignment;
		private Borders _borders;
		private Spacings _spacings;
		private Paddings _paddings;
		private Background _background;
		private Foreground _foreground;
		private bool _stretch;
		private Visibility _visibility;
		private ElementCollection _content;
		private Features _features;

		public Group(Layout layout, Element parent)
			: base(layout, parent)
		{
			_width = Width.Default;
			_height = Height.Default;
			_alignment = Alignment.Default;
			_borders = Borders.Default;
			_spacings = Spacings.Default;
			_paddings = Paddings.Default;
			_background = Background.Default;
			_foreground = Foreground.Default;
			_stretch = true;
			_visibility = Visibility.Visible;
			_content = new ElementCollection();
			_features = new Features(this);
		}

		public override ElementType Type
		{
			get
			{
				return ElementType.Group;
			}
		}

		public Width Width
		{
			get
			{
				if (_width == Width.Default)
					_width = new Width();

				return _features.Width;
			}
			set
			{
				if (value != null)
					_width = value;
				else
					_width = Width.Default;

				_features.Reset(Feature.Width);
			}
		}

		public Height Height
		{
			get
			{
				if (_height == Height.Default)
					_height = new Height();

				return _features.Height;
			}
			set
			{
				if (value != null)
					_height = value;
				else
					_height = Height.Default;

				_features.Reset(Feature.Height);
			}
		}

		public Alignment Alignment
		{
			get
			{
				if (_alignment == Alignment.Default)
					_alignment = new Alignment();

				return _features.Alignment;
			}
			set
			{
				if (value != null)
					_alignment = value;
				else
					_alignment = Alignment.Default;

				_features.Reset(Feature.Alignment);
			}
		}

		public Borders Borders
		{
			get
			{
				if (_borders == Borders.Default)
					_borders = new Borders();

				return _features.Borders;
			}
			set
			{
				if (value != null)
					_borders = value;
				else
					_borders = Borders.Default;

				_features.Reset(Feature.Borders);
			}
		}

		public Spacings Spacings
		{
			get
			{
				if (_spacings == Spacings.Default)
					_spacings = new Spacings();

				return _features.Spacings;
			}
			set
			{
				if (value != null)
					_spacings = value;
				else
					_spacings = Spacings.Default;

				_features.Reset(Feature.Spacings);
			}
		}

		public Paddings Paddings
		{
			get
			{
				if (_paddings == Paddings.Default)
					_paddings = new Paddings();

				return _features.Paddings;
			}
			set
			{
				if (value != null)
					_paddings = value;
				else
					_paddings = Paddings.Default;

				_features.Reset(Feature.Paddings);
			}
		}

		public Background Background
		{
			get
			{
				if (_background == Background.Default)
					_background = new Background();

				return _features.Background;
			}
			set
			{
				if (value != null)
					_background = value;
				else
					_background = Background.Default;

				_features.Reset(Feature.Background);
			}
		}

		public Foreground Foreground
		{
			get
			{
				if (_foreground == Foreground.Default)
					_foreground = new Foreground();

				return _features.Foreground;
			}
			set
			{
				if (value != null)
					_foreground = value;
				else
					_foreground = Foreground.Default;

				_features.Reset(Feature.Foreground);
			}
		}

		public bool Stretch
		{
			get
			{
				return _features.Stretch;
			}
			set
			{
				_stretch = value;

				_features.Reset(Feature.Stretch);
			}
		}

		public Visibility Visibility
		{
			get
			{
				return _features.Visibility;
			}
			set
			{
				_visibility = value;

				_features.Reset(Feature.Visibility);
			}
		}

		public ElementCollection Content
		{
			get
			{
				return _content;
			}
		}

		public override object GetFeature(Feature feature)
		{
			switch (feature)
			{
				case Feature.Width:
					return DataBinding.Evaluate(this, "Width", DataContext, _width);

				case Feature.Height:
					return DataBinding.Evaluate(this, "Height", DataContext, _height);

				case Feature.Alignment:
					return DataBinding.Evaluate(this, "Alignment", DataContext, _alignment);

				case Feature.Borders:
					return DataBinding.Evaluate(this, "Borders", DataContext, _borders);

				case Feature.Spacings:
					return DataBinding.Evaluate(this, "Spacings", DataContext, _spacings);

				case Feature.Paddings:
					return DataBinding.Evaluate(this, "Paddings", DataContext, _paddings);

				case Feature.Background:
					return DataBinding.Evaluate(this, "Background", DataContext, _background);

				case Feature.Foreground:
					return DataBinding.Evaluate(this, "Foreground", DataContext, _foreground);

				case Feature.Stretch:
					return DataBinding.Evaluate(this, "Stretch", DataContext, _stretch);

				case Feature.Visibility:
					return DataBinding.Evaluate(this, "Visibility", DataContext, _visibility);
			}

			return null;
		}

		protected override void ResetFeatures()
		{
			_features.Reset();
		}

		public Text.ICaption AddCaption()
		{
			Text.Caption caption = new Text.Caption(_layout, this);

			_content.Add(caption);

			return caption;
		}

		public Text.IText AddText()
		{
			Text.Text text = new Text.Text(_layout, this);

			_content.Add(text);

			return text;
		}

		public IImage AddImage()
		{
			Image img = new Image(_layout, this);

			_content.Add(img);

			return img;
		}

		public IImage AddImage(Fusion.Graphics.Image image)
		{
			Image img = new Image(_layout, this, image);

			_content.Add(img);

			return img;
		}

		public IShape AddShape()
		{
			Shape shp = new Shape(_layout, this);

			_content.Add(shp);

			return shp;
		}

		public IShape AddShape(Fusion.Shape.Shape shape)
		{
			Shape shp = new Shape(_layout, this, shape);

			_content.Add(shp);

			return shp;
		}

		public IGroup AddGroup()
		{
			Group group = new Group(_layout, this);

			_content.Add(group);

			return group;
		}

		public IContour AddContour()
		{
			Contour contour = new Contour(_layout, this);

			_content.Add(contour);

			return contour;
		}

		public ISelector AddSelector()
		{
			Selector selector = new Selector(_layout, this);

			_content.Add(selector);

			return selector;
		}

		public IRule AddRule()
		{
			Rule rule = new Rule(_layout, this);

			_content.Add(rule);

			return rule;
		}

		public IStack AddStack()
		{
			Stack stack = new Stack(_layout, this);

			_content.Add(stack);

			return stack;
		}

		public IBand AddBand()
		{
			Band band = new Band(_layout, this);

			_content.Add(band);

			return band;
		}

		public Grid.IGrid AddGrid()
		{
			Grid.Grid grid = new Grid.Grid(_layout, this);

			_content.Add(grid);

			return grid;
		}

		public Slot.ISlot AddSlot()
		{
			Slot.Slot slot = new Slot.Slot(_layout, this);

			_content.Add(slot);

			return slot;
		}

		public List.IList AddList()
		{
			List.List list = new List.List(_layout, this);

			_content.Add(list);

			return list;
		}

		public Repeater.IRepeater AddRepeater()
		{
			Repeater.Repeater repeater = new Repeater.Repeater(_layout, this);

			_content.Add(repeater);

			return repeater;
		}

		public IPlace AddPlace()
		{
			Place place = new Place(_layout, this);

			_content.Add(place);

			return place;
		}

		public ISite AddSite()
		{
			Site site = new Site(_layout, this);

			_content.Add(site);

			return site;
		}

		public ICanvas AddCanvas()
		{
			Canvas canvas = new Canvas(_layout, this);

			_content.Add(canvas);

			return canvas;
		}

		public IPlaceholder AddPlaceholder()
		{
			Placeholder placeholder = new Placeholder(_layout, this);

			_content.Add(placeholder);

			return placeholder;
		}

		public void Clear()
		{
			_content.Clear();
		}

		public void Remove(IElement element)
		{
			_content.Remove((Element)element);
		}

		public IElement Find(Predicate<IElement> match)
		{
			foreach (Element element in _content)
			{
				if (match(element))
					return element;
			}

			return null;
		}

		public IElement Find(Func<IElement, int, bool> match)
		{
			int i = 0;

			foreach (Element element in _content)
			{
				if (match(element, i))
					return element;

				i++;
			}

			return null;
		}

		public List<IElement> Select(Predicate<IElement> match)
		{
			System.Collections.Generic.List<IElement> list = new List<IElement>();

			Perform(match, element => list.Add(element));

			return list;
		}

		public List<IElement> Select(Func<IElement, int, bool> match)
		{
			System.Collections.Generic.List<IElement> list = new List<IElement>();

			Perform(match, element => list.Add(element));

			return list;
		}

		public void Perform(Predicate<IElement> match, Action<IElement> action)
		{
			foreach (Element element in _content)
			{
				if (match(element))
					action(element);
			}
		}

		public void Perform(Func<IElement, int, bool> match, Action<IElement> action)
		{
			int i = 0;

			foreach (Element element in _content)
			{
				if (match(element, i))
					action(element);

				i++;
			}
		}

		protected override void MeasureImpl(Fusion.Graphics.IGraphics graphics, Fusion.Graphics.Size size)
		{
			_features.Reset();

			float width = 0F;

			switch (_features.Width.Type)
			{
				case WidthType.Default:
					width = size.Width - _features.Spacings.Start - _features.Spacings.End;

					break;

				case WidthType.Direct:
					width = ((DirectWidth)_features.Width).Value;

					break;

				case WidthType.Relative:
					width = (size.Width - _features.Spacings.Start - _features.Spacings.End) * ((RelativeWidth)_features.Width).Value / 100F;

					width = Utils.Round(width, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeWidth)_features.Width).Constraint;

					if (constraint != null)
						width = constraint.Apply(width);

					break;
			}

			if (width < 0F)
				width = 0F;

			float height = 0F;

			switch (_features.Height.Type)
			{
				case HeightType.Default:
					height = size.Height - _features.Spacings.Top - _features.Spacings.Bottom;

					break;

				case HeightType.Direct:
					height = ((DirectHeight)_features.Height).Value;

					break;

				case HeightType.Relative:
				{
					height = (size.Height - _features.Spacings.Top - _features.Spacings.Bottom) * ((RelativeHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}

				case HeightType.Aspect:
				{
					height = width * ((AspectHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((AspectHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}
			}

			if (height < 0F)
				height = 0F;

			Fusion.Graphics.Rectangle scene = Element.MakeScene(0F, 0F, width, height, _features.Borders, _features.Paddings);

			float dh = height - scene.Height;

			Element.NormalizeScene(scene);

			Fusion.Graphics.Size sz = new Fusion.Graphics.Size(scene.Width, scene.Height);

			float fh = 0F;

			foreach (Element element in _content)
			{
				Visibility? visibility = (Visibility?)element.GetFeature(Element.Feature.Visibility);

				if ((visibility != null) && (visibility.Value == Visibility.Gone))
					continue;

				Spacings spacings = (Spacings)element.GetFeature(Feature.Spacings);

				if (spacings != null)
					fh += spacings.Top + spacings.Bottom;

				Height eh = (Height)element.GetFeature(Feature.Height);

				if ((eh == null) || ((eh != null) && (eh.Type != HeightType.Relative)))
					fh += element.Measure(graphics, sz).Height;
			}

			float rh = scene.Height - fh;

			if (rh < 0F)
				rh = 0F;

			float h = 0F;

			foreach (Element element in _content)
			{
				Visibility? visibility = (Visibility?)element.GetFeature(Element.Feature.Visibility);

				if ((visibility != null) && (visibility.Value == Visibility.Gone))
					continue;

				Spacings spacings = (Spacings)element.GetFeature(Feature.Spacings);

				float sh = 0F;

				if (spacings != null)
				{
					sh = spacings.Top + spacings.Bottom;

					h += sh;
				}

				Height eh = (Height)element.GetFeature(Feature.Height);

				if ((eh != null) && (eh.Type == HeightType.Relative))
					h += element.Measure(graphics, new Fusion.Graphics.Size(sz.Width, rh + sh)).Height;
				else
					h += element.Size.Height;
			}

			h += dh;

			if (_features.Stretch && ((_features.Height.Type == HeightType.Default) || (height < h)))
				height = h;

			scene.Height = height - dh;

			_size = new Fusion.Graphics.Size(width, height);

			Element.Align(_content, _features.Alignment, scene, _layout.RenderingScale);
		}

		public override void Draw(Fusion.Graphics.IGraphics graphics, Fusion.Graphics.Point offset, Fusion.Graphics.Zone zone)
		{
			if (_features.Visibility != Visibility.Visible)
				return;

			if ((_size.Width <= 0F) || (_size.Height <= 0F))
				return;

			_features.Reset();

			float x = _pos.X + offset.X;
			float y = _pos.Y + offset.Y;

			offset = new Fusion.Graphics.Point(x, y);

			graphics.SaveState();

			Element.ClipBounds(graphics, x, y, _size.Width, _size.Height, _features.Borders);

			Element.DrawBackground(this, graphics, x, y, _size.Width, _size.Height, _features.Background);

			foreach (Element element in _content)
			{
				if ((zone != null) && !zone.Intersects(y + element.Pos.Y, element.Size.Height))
					continue;

				Visibility? visibility = (Visibility?)element.GetFeature(Element.Feature.Visibility);

				if ((visibility != null) && (visibility.Value == Visibility.Gone))
					continue;

				if (element.Angle != 0F)
				{
					graphics.SaveState();

					graphics.Rotate(x + element.Pos.X, y + element.Pos.Y, element.Angle);

					element.Draw(graphics, offset, zone);

					graphics.RestoreState();
				}
				else
				{
					element.Draw(graphics, offset, zone);
				}
			}

			Element.DrawForeground(this, graphics, x, y, _size.Width, _size.Height, _features.Foreground);

			Element.DrawBorders(graphics, x, y, _size.Width, _size.Height, _features.Borders);

			graphics.RestoreState();
		}

		public override void Reset()
		{
			foreach (Element element in _content)
			{
				element.Reset();
			}

			base.Reset();
		}

		public override void Release()
		{
			foreach (Element element in _content)
			{
				element.Release();
			}

			_width = null;
			_height = null;
			_alignment = null;
			_borders = null;
			_spacings = null;
			_paddings = null;
			_background = null;
			_foreground = null;
			_content = null;
			_features = null;

			base.Release();
		}

		public override Element Clone(Element parent)
		{
			Group group = new Group(_layout, parent);

			CloneImpl(group);

			return group;
		}

		protected override void CloneImpl(Element clone)
		{
			Group group = (Group)clone;

			group.Width = _width;
			group.Height = _height;
			group.Alignment = _alignment;
			group.Borders = _borders;
			group.Spacings = _spacings;
			group.Paddings = _paddings;
			group.Background = _background;
			group.Foreground = _foreground;
			group.Stretch = _stretch;
			group.Visibility = _visibility;

			foreach (Element element in _content)
			{
				group.Content.Add(element.Clone(group));
			}

			base.CloneImpl(clone);
		}
	}
}


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System.Collections.Generic;
using Microsoft.Azure.Mobile.Server.Notifications;
using Xunit;

namespace Microsoft.Azure.Mobile.Server.Test
{
    public class NotificationInstallationTests
    {
        [Fact]
        public void NotificationInstallation_Serialization_IsConsistent()
        {
            // Arrange
            NotificationTemplate testSecondaryTemplate = new NotificationTemplate
            {
                Body = "mySecondaryBody",
                Headers = new Dictionary<string, string>()
            };
            testSecondaryTemplate.Headers["mySecondaryHeaderName"] = "mySecondaryHeaderValue";

            NotificationSecondaryTile testSecondaryTile = new NotificationSecondaryTile
            {
                PushChannel = "myPushChannel",
                Tags = new List<string>(),
                Templates = new Dictionary<string, NotificationTemplate>()
            };
            testSecondaryTile.Tags.Add("myTag");
            testSecondaryTile.Templates["mySecondaryTemplateName"] = testSecondaryTemplate;

            NotificationInstallation installation = new NotificationInstallation
            {
                PushChannel = "myPushChannel",
                Platform = "myPlatform",
                InstallationId = "myId",
                SecondaryTiles = new Dictionary<string, NotificationSecondaryTile>(),
                Templates = new Dictionary<string, NotificationTemplate>()
            };
            installation.SecondaryTiles["myTestTile"] = testSecondaryTile;
            NotificationTemplate testTemplate = new NotificationTemplate
            {
                Body = "myBody",
                Headers = new Dictionary<string, string>()
            };
            testSecondaryTemplate.Headers["myHeaderName"] = "myHeaderValue";
            installation.Templates["myTemplateName"] = testTemplate;

            // Assert
            SerializationAssert.VerifySerialization(installation, "{\"pushChannel\":\"myPushChannel\",\"platform\":\"myPlatform\",\"installationId\":\"myId\",\"templates\":{\"myTemplateName\":{\"body\":\"myBody\",\"headers\":{},\"tags\":[]}},\"secondaryTiles\":{\"myTestTile\":{\"pushChannel\":\"myPushChannel\",\"tags\":[\"myTag\"],\"templates\":{\"mySecondaryTemplateName\":{\"body\":\"mySecondaryBody\",\"headers\":{\"mySecondaryHeaderName\":\"mySecondaryHeaderValue\",\"myHeaderName\":\"myHeaderValue\"},\"tags\":[]}}}},\"tags\":[]}");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Droid\Test\TaskRunner;

use Droid\Model\Inventory\Host;
use Droid\Model\Inventory\Inventory;
use Droid\Model\Inventory\Remote\Enabler;
use Droid\Model\Project\Task;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

use Droid\Application;
use Droid\Logger\LoggerFactory;
use Droid\TaskRunner;
use Droid\Test\AutoloaderAwareTestCase;
use Droid\Transform\Transformer;

class RunTaskLocallyTest extends AutoloaderAwareTestCase
{
    private $app;
    private $command;
    private $enabler;
    private $expr;
    private $host;
    private $inventory;
    private $logger;
    private $loggerFac;
    private $output;
    private $task;
    private $taskRunner;
    private $transformer;

    public function setUp()
    {
        $this->app = $this->getPartialMockApplication();
        $this->command = $this->getMockCommand();
        $this->enabler = $this
            ->getMockBuilder(Enabler::class)
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $this->host = $this
            ->getMockBuilder(Host::class)
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $this->inventory = $this
            ->getMockBuilder(Inventory::class)
            ->getMock()
        ;
        $this->logger = $this
            ->getMockBuilder(LoggerInterface::class)
            ->getMock()
        ;
        $this->loggerFac = $this
            ->getMockBuilder(LoggerFactory::class)
            ->getMock()
        ;
        $this->expr = $this
            ->getMockBuilder(ExpressionLanguage::class)
            ->getMock()
        ;
        $this
            ->loggerFac
            ->method('makeLogger')
            ->willReturn($this->logger)
        ;
        $this->output = $this
            ->getMockBuilder(OutputInterface::class)
            ->getMock()
        ;
        $this->task = $this
            ->getMockBuilder(Task::class)
            ->getMock()
        ;
        $this->transformer = $this
            ->getMockBuilder(Transformer::class)
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $this->taskRunner = $this->getPartialMockTaskRunner();

        $this
            ->host
            ->method('getName')
            ->willReturn('host.example.com')
        ;
    }

    private function getPartialMockApplication()
    {
        return $this
            ->getMockBuilder(Application::class)
            ->setConstructorArgs(array($this->autoloader))
            ->setMethods(
                array(
                    'hasInventory',
                    'getInventory',
                )
            )
            ->getMock()
        ;
    }

    private function getPartialMockTaskRunner()
    {
        return $this
            ->getMockBuilder(TaskRunner::class)
            ->setConstructorArgs(
                array($this->app, $this->transformer, $this->loggerFac, $this->expr, $this->transformer)
            )
            ->setMethods(
                array(
                    'prepareCommandInput',
                    'runRemoteCommand',
                    'runLocalCommand',
                    'commandInputToText',
                )
            )
            ->getMock()
            ->setEnabler($this->enabler)
            ->setOutput($this->output)
        ;
    }

    private function getMockCommand()
    {
        $mock = $this
            ->getMockBuilder(Command::class)
            ->disableOriginalConstructor()
            ->setMethods(
                array(
                    'isEnabled',
                    'getDefinition',
                    'getName',
                    'getAliases',
                )
            )
            ->getMock()
        ;
        $mock
            ->method('isEnabled')
            ->willReturn(true)
        ;
        $mock
            ->method('getDefinition')
            ->willReturn('some-defn')
        ;
        $mock
            ->method('getAliases')
            ->willReturn(array())
        ;
        return $mock;
    }

    /**
     * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException
     */
    public function testRunTaskFailsWhenCommandNotFound()
    {
        $this
            ->task
            ->method('getCommandName')
            ->willReturn('some-unregisterd-command')
        ;
        $this->taskRunner->runTaskLocally($this->task, array());
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Items is refering to non-existant variable
     */
    public function testRunTaskFailsWhenWithItemsCannotBeResolved()
    {
        $this
            ->command
            ->method('getName')
            ->willReturn('do:thing')
        ;
        $this->app->add($this->command);
        $this
            ->task
            ->method('getCommandName')
            ->willReturn('do:thing')
        ;

        $this
            ->task
            ->expects($this->once())
            ->method('getItems')
            ->willReturn('not-a-variable')
        ;
        $this->taskRunner->runTaskLocally($this->task, array());
    }

    public function testRunTaskDoesNothingWithoutAnyWithItems()
    {
        $this
            ->command
            ->method('getName')
            ->willReturn('do:thing')
        ;
        $this->app->add($this->command);
        $this
            ->task
            ->method('getCommandName')
            ->willReturn('do:thing')
        ;
        $this
            ->task
            ->method('getItems')
            ->willReturn(array())
        ;

        $this
            ->task
            ->expects($this->never())
            ->method('getArguments')
        ;
        $this->taskRunner->runTaskLocally($this->task, array());
    }

    public function testRunLocalTaskRunsLocalCommand()
    {
        $taskArgs = array('what' => 'something');
        $commandInput = new ArrayInput($taskArgs);

        $this
            ->command
            ->method('getName')
            ->willReturn('do:thing')
        ;
        $this->app->add($this->command);
        $this
            ->task
            ->method('getCommandName')
            ->willReturn('do:thing')
        ;
        $this
            ->task
            ->method('getItems')
            ->willReturn(array('an-inconsequential-value'))
        ;
        $this
            ->task
            ->method('getArguments')
            ->willReturn($taskArgs)
        ;

        $this
            ->taskRunner
            ->expects($this->once())
            ->method('prepareCommandInput')
            ->with(
                $this->command,
                array('what' => 'something'),
                array('item' => 'an-inconsequential-value')
            )
            ->willReturn($commandInput)
        ;
        $this
            ->taskRunner
            ->expects($this->once())
            ->method('runLocalCommand')
            ->with(
                $this->task,
                $this->command,
                $commandInput
            )
            ->willReturn(0)
        ;

        $this->taskRunner->runTaskLocally($this->task, array());
    }
}


text:
Note that some system might require you to use sudo before each docker command.

First we need to create a network bridge on which we can run docker containers. A bridge can have up to around 1100 containers.
```
docker network create --driver bridge bridgename
```

To run a container using a particular image on a given bridge
```
docker run --network=bridgename --name containername -t -d  imagename /bin/bash
```

In order to start up a lot of containers, we will use a bash script. For example if we want to run 1000 containers on a given bridge, we can use a script like this; this will start 1000 containers named test1, ... , test1000
```
#!/bin/bash
for i in `seq 1 1000`; do
    docker run --network=bridgename --name test$i -t -d  imagename /bin/bash
done
```
We probably also want to import the compiled test programs from local machine into the docker, it works a bit like scp on linux. Here we copy a folder into containers test1, test2, ... , test400 using a bash script.
```
#!/bin/bash

for i in `seq 1 400`; do
        docker cp folderName test$i:/JAMScript/samples/
done
```

In order to start up a JS node, we can manually open up a single container in interactive mode, to do this, we run
```
docker exec -it containername /bin/bash
```

Then we need to open up the MQTT server inside the container using the command
```
mosquitto &
```
Now we can navigate to the directory that contains the JS program and start up the program using
```
node jamout.js --app=appname
```

To run a particular C program with executable name "a.out" on a single container
```
docker exec -t containername /bin/bash -c "./path/to/directory/a.out"
```

To run multiple C programs on different containers, we can use a bash script like below, here we try to open up 400 C programs on 400 containers named test1, test2, ... , test400. Note that this will take about 400 seconds to accomplish, you could reduce the sleep time between each iteration of the loop, but this could increase the risk of connection failure.
```
#!/bin/sh
for i in `seq 1 400`; do
        docker exec -t test$i /bin/bash -c "./path/to/directory/a.out" &
        sleep 1
done
```

In order to have a realistic benchmarking, there should be some network delays between the containers. To achieve this, we use the open-source software Pumba. Download the binary from https://github.com/gaia-adm/pumba
To activate it, run ./pumba with the desired parameters found on the github page. For example, to add a network delay of 25 ms to the container named "mydb" for a duration of 5 minutes.
```
./pumba netem --duration 5m delay --time 25 mydb
```
We can also add a variance to the delay, for example to have a normal distribution with variance of 10 ms
```
./pumba netem --duration 5m delay --time 25 containerName --jitter 10 --distribution normal
```
In practice for JAMScript, we only need to add the network delay to the container that's running the JS program.

After you are done with the test, or if something wrong happened during the run, we have to stop all the C programs in order to to restart the test; unless you are running JAMScript in which case exiting the JS program should automatically stop all the C programs. To close all C programs on test1, ..., test400
```
#!/bin/bash
for i in `seq 1 400`; do
        docker exec test$i pkill -f a.out
done
```

Lastly if you would like to stop and remove all containers, just use the following bash script
```
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
```

You could also simply use the provided script and modify the parameters in the first few lines.


text:
package gcs

import (
	"context"
	"os"
	"reflect"
	"testing"
	"time"

	"github.com/fsouza/fake-gcs-server/fakestorage"
	"github.com/guacsec/guac/pkg/handler/processor"
)

func TestGCS_RetrieveArtifacts(t *testing.T) {
	os.Setenv("GCS_BUCKET_ADDRESS", "some-bucket")
	ctx := context.Background()
	server := fakestorage.NewServer([]fakestorage.Object{
		{
			ObjectAttrs: fakestorage.ObjectAttrs{
				BucketName: "some-bucket",
				Name:       "some/object/file.txt",
				Updated:    time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC),
			},
			Content: []byte("inside the file"),
		},
	})
	defer server.Stop()
	client := server.Client()

	var doc *processor.Document = &processor.Document{
		Blob:   []byte("inside the file"),
		Type:   processor.DocumentUnknown,
		Format: processor.FormatUnknown,
		SourceInformation: processor.SourceInformation{
			Collector: string(CollectorGCS),
			Source:    getBucketPath() + "/some/object/file.txt",
		},
	}

	type fields struct {
		bucket       string
		reader       gcsReader
		lastDownload time.Time
		poll         bool
	}
	tests := []struct {
		name     string
		fields   fields
		want     *processor.Document
		wantErr  bool
		wantDone bool
	}{{
		name:    "no reader",
		want:    nil,
		wantErr: true,
	}, {
		name: "get object",
		fields: fields{
			bucket: getBucketPath(),
			reader: &reader{client: client, bucket: getBucketPath()},
		},
		want:     doc,
		wantErr:  false,
		wantDone: true,
	}, {
		name: "last download time the same",
		fields: fields{
			bucket:       getBucketPath(),
			reader:       &reader{client: client, bucket: getBucketPath()},
			lastDownload: time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC),
		},
		want:     nil,
		wantErr:  false,
		wantDone: true,
	}, {
		name: "last download time set before",
		fields: fields{
			bucket:       getBucketPath(),
			reader:       &reader{client: client, bucket: getBucketPath()},
			lastDownload: time.Date(2009, 10, 17, 20, 34, 58, 651387237, time.UTC),
		},
		want:     doc,
		wantErr:  false,
		wantDone: true,
	}}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			g := &gcs{
				bucket:       tt.fields.bucket,
				reader:       tt.fields.reader,
				lastDownload: tt.fields.lastDownload,
				poll:         tt.fields.poll,
			}
			docChan := make(chan *processor.Document, 1)
			errChan := make(chan error, 1)
			defer close(docChan)
			defer close(errChan)
			go func() {
				errChan <- g.RetrieveArtifacts(ctx, docChan)
			}()
			numCollectors := 1
			collectorsDone := 0
			for collectorsDone < numCollectors {
				select {
				case d := <-docChan:
					if !reflect.DeepEqual(d, tt.want) {
						t.Errorf("g.RetrieveArtifacts() = %v, want %v", d, tt.want)
					}
				case err := <-errChan:
					if (err != nil) != tt.wantErr {
						t.Errorf("g.RetrieveArtifacts() error = %v, wantErr %v", err, tt.wantErr)
						return
					}
					collectorsDone += 1
				}
			}
			// Drain anything left in document channel
			for len(docChan) > 0 {
				<-docChan
			}
			if g.Type() != CollectorGCS {
				t.Errorf("g.Type() = %s, want %s", g.Type(), CollectorGCS)
			}
		})
	}
}


text:
package proto

import (
	"bytes"

	"github.com/hyperledger/fabric/gossip/common"
	"github.com/hyperledger/fabric/gossip/util"
)

func NewGossipMessageComparator(dataBlockStorageSize int) common.MessageReplacingPolicy {
	return (&msgComparator{dataBlockStorageSize: dataBlockStorageSize}).getMsgReplacingPolicy()
}

type msgComparator struct {
	dataBlockStorageSize int
}

func (mc *msgComparator) getMsgReplacingPolicy() common.MessageReplacingPolicy {
	return func(this interface{}, that interface{}) common.InvalidationResult {
		return mc.invalidationPolicy(this, that)
	}
}

func (mc *msgComparator) invalidationPolicy(this interface{}, that interface{}) common.InvalidationResult {
	thisMsg := this.(*GossipMessage)
	thatMsg := that.(*GossipMessage)

	if thisMsg.IsAliveMsg() && thatMsg.IsAliveMsg() {
		return aliveInvalidationPolicy(thisMsg.GetAliveMsg(), thatMsg.GetAliveMsg())
	}

	if thisMsg.IsDataMsg() && thatMsg.IsDataMsg() {
		return mc.dataInvalidationPolicy(thisMsg.GetDataMsg(), thatMsg.GetDataMsg())
	}

	if thisMsg.IsStateInfoMsg() && thatMsg.IsStateInfoMsg() {
		return mc.stateInvalidationPolicy(thisMsg.GetStateInfo(), thatMsg.GetStateInfo())
	}

	return common.MessageNoAction
}

func (mc *msgComparator) stateInvalidationPolicy(thisStateMsg *StateInfo, thatStateMsg *StateInfo) common.InvalidationResult {
	if !bytes.Equal(thisStateMsg.PkiID, thatStateMsg.PkiID) {
		return common.MessageNoAction
	}
	return compareTimestamps(thisStateMsg.Timestamp, thatStateMsg.Timestamp)
}

func (mc *msgComparator) dataInvalidationPolicy(thisDataMsg *DataMessage, thatDataMsg *DataMessage) common.InvalidationResult {
	if thisDataMsg.Payload.SeqNum == thatDataMsg.Payload.SeqNum {
		if thisDataMsg.Payload.Hash == thatDataMsg.Payload.Hash {
			return common.MessageInvalidated
		}
		return common.MessageNoAction
	}

	diff := util.Abs(thisDataMsg.Payload.SeqNum, thatDataMsg.Payload.SeqNum)
	if diff <= uint64(mc.dataBlockStorageSize) {
		return common.MessageNoAction
	}

	if thisDataMsg.Payload.SeqNum > thatDataMsg.Payload.SeqNum {
		return common.MessageInvalidates
	}
	return common.MessageInvalidated
}

func aliveInvalidationPolicy(thisMsg *AliveMessage, thatMsg *AliveMessage) common.InvalidationResult {
	if !bytes.Equal(thisMsg.Membership.PkiID, thatMsg.Membership.PkiID) {
		return common.MessageNoAction
	}

	return compareTimestamps(thisMsg.Timestamp, thatMsg.Timestamp)
}

func compareTimestamps(thisTS *PeerTime, thatTS *PeerTime) common.InvalidationResult {
	if thisTS.IncNumber == thatTS.IncNumber {
		if thisTS.SeqNum > thatTS.SeqNum {
			return common.MessageInvalidates
		}

		return common.MessageInvalidated
	}
	if thisTS.IncNumber < thatTS.IncNumber {
		return common.MessageInvalidated
	}
	return common.MessageInvalidates
}

func (m *GossipMessage) IsAliveMsg() bool {
	return m.GetAliveMsg() != nil
}

func (m *GossipMessage) IsDataMsg() bool {
	return m.GetDataMsg() != nil
}

func (m *GossipMessage) IsStateInfoMsg() bool {
	return m.GetStateInfo() != nil
}


text:
//
//  Copyright (c) 2014 VK.com
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

package com.vk.sdk;

import android.app.Activity;
import android.content.Intent;

/**
 * Class for VK authorization and dialogs helping
 */
public class VKUIHelper {
    private static Activity mTopActivity;

    public static Activity getTopActivity() {
        return mTopActivity;
    }

    /**
     * Call it in onCreate for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onCreate(Activity activity) {
        if (mTopActivity != activity)
            mTopActivity = activity;
    }
    /**
     * Call it in onResume for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onResume(Activity activity) {
        if (mTopActivity != activity)
            mTopActivity = activity;
    }
    /**
     * Call it in onDestroy for of activities where you using VK SDK
     * @param activity Your activity
     */
    public static void onDestroy(Activity activity) {
        if (mTopActivity == activity)
            mTopActivity = null;
    }

    /**
     * Call it in onActivityResult of all activities where you using VK SDK
     * @param requestCode Request code for startActivityForResult
     * @param resultCode Result code of finished activity
     * @param data Result data
     * @deprecated Use onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) instead
     */
    public static void onActivityResult(int requestCode, int resultCode, Intent data) {
        onActivityResult(mTopActivity, requestCode, resultCode, data);
    }

    /**
     * Call it in onActivityResult of all activities where you using VK SDK
     * @param requestCode Request code for startActivityForResult
     * @param resultCode Result code of finished activity
     * @param data Result data
     */
    public static void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        mTopActivity = activity;
        if (requestCode == VKSdk.VK_SDK_REQUEST_CODE) {
            VKSdk.processActivityResult(requestCode, resultCode, data);
        }
    }
}


text:
RSpec.describe Daru::IO::Importers::Log.new do
  context 'parsing rails log' do
    subject { described_class.read(path,format: :rails3).call }

    let(:path) { 'spec/fixtures/log/rails.log' }

    it_behaves_like 'exact daru dataframe',
      ncols: 17,
      nrows: 1,
      order: %i[method resource_path ip timestamp line_type lineno
                source controller action format params rendered_file
                partial_duration status duration view db],
      :'timestamp.to_a' => [20_180_312_174_118],
      :'duration.to_a' => [0.097]
  end

  context 'parsing apache log' do
    subject { described_class.read(path,format: :apache).call }

    let(:path) { 'spec/fixtures/log/apache.log' }

    it_behaves_like 'exact daru dataframe',
      ncols: 14,
      nrows: 1,
      order: %i[remote_host remote_logname user timestamp http_method
                resource_path http_version http_status bytes_sent
                referer user_agent line_type lineno source],
      :'timestamp.to_a' => [20_161_207_103_443],
      :'bytes_sent.to_a' => [571]
  end

  context 'parsing amazon_s3 log' do
    subject { described_class.read(path,format: :amazon_s3).call }

    let(:path) { 'spec/fixtures/log/s3.log' }

    it_behaves_like 'exact daru dataframe',
      ncols: 20,
      nrows: 1,
      order: %i[bucket_owner bucket timestamp remote_ip requester request_id operation
                key request_uri http_status error_code bytes_sent object_size total_time
                turnaround_time referer user_agent line_type lineno source],
      :'timestamp.to_a' => [20_150_612_054_010],
      :'turnaround_time.to_a' => [0.019]
  end
end


text:
package com.coolweather.app.util;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.coolweather.app.R;

import java.util.List;

/**
 * Created by Star on 2015/4/12.
 */
public class WeatherAdapterUtil extends ArrayAdapter<Weather>{
    private int resourceId;

    public WeatherAdapterUtil(Context context, int textViewResourceId,
                              List<Weather> objects){
        super(context,textViewResourceId,objects);
        resourceId = textViewResourceId;
    }

    //此方法在每个子项被滚动到屏幕内的时候会被调用
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Weather weather = getItem(position);  //获得当前项的weather实例
        View view;
        ViewHolder viewHolder;

        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,null);
            viewHolder = new ViewHolder();
            viewHolder.weather_date = (TextView)view.findViewById(R.id.item_date);
            viewHolder.weather_sunny = (TextView)view.findViewById(R.id.item_sunny);
            viewHolder.weather_temperature = (TextView)view.findViewById(R.id.item_temperature);
            viewHolder.weather_wind = (TextView)view.findViewById(R.id.item_wind);

            view.setTag(viewHolder);
        }else {
            view = convertView;
            viewHolder = (ViewHolder)view.getTag();
        }
        viewHolder.weather_date.setText(weather.getDate());
        viewHolder.weather_sunny.setText(weather.getSunny());
        viewHolder.weather_temperature.setText(weather.getTemperature());
        viewHolder.weather_wind.setText(weather.getWind());

        return view;
    }

    class ViewHolder{
        TextView weather_date;
        TextView weather_sunny;
        TextView weather_temperature;
        TextView weather_wind;
    }
}


text:
var dive = require('dive');

var files = 0;

dive(process.argv[2], { all: true }, function (err, file) {
  if (!err) files++;
}, function () {
  console.log(files);
});


text:
namespace System.Security.Cryptography
{

#if CONFIG_CRYPTO && CONFIG_FRAMEWORK_1_2

using System;

public abstract class HMAC : KeyedHashAlgorithm
{
	// Internal state.
	protected int BlockSizeValue;
	private HashAlgorithm alg;
	private String algName;

	// Constructor.
	protected HMAC()
			{
				BlockSizeValue = 1;
			}

	// Create an instance of the default HMAC algorithm.
	public new static HMAC Create()
			{
				return (HMAC)(CryptoConfig.CreateFromName
					(CryptoConfig.HMACDefault, null));
			}

	// Create an instance of a specific HMAC algorithm.
	public new static HMAC Create(String algName)
			{
				return (HMAC)(CryptoConfig.CreateFromName(algName, null));
			}

	// Dispose this object.
	protected override void Dispose(bool disposing)
			{
				if(alg != null)
				{
					((IDisposable)alg).Dispose();
				}
				base.Dispose(disposing);
			}

	// Initialize the key.  If it is 64 bytes or less, then use
	// it as-is.  Otherwise hash it down.
	private void SetKey(byte[] key)
			{
				if(key.Length <= 64)
				{
					KeyValue = key;
				}
				else
				{
					KeyValue = alg.ComputeHash(key);
				}
			}

	// Get or set the hash key.
	public override byte[] Key
			{
				get
				{
					return KeyValue;
				}
				set
				{
					if(State != 0)
					{
						throw new CryptographicException
							(_("Crypto_HashInProgress"));
					}
					else if(value == null)
					{
						throw new ArgumentNullException("value");
					}
					SetKey(value);
				}
			}

	// Get or set the name of the hash algorithm implementation.
	public String HashName
			{
				get
				{
					return algName;
				}
				set
				{
					algName = value;
					alg = HashAlgorithm.Create(algName);
				}
			}

	// Initialize the hash algorithm.
	public override void Initialize()
			{
				if(alg != null)
				{
					alg.Initialize();
				}
				alg = null;
			}

	// Prepare the hash for the initial call to "HashCore" or "HashFinal".
	private void Prepare()
			{
				if(alg == null)
				{
					alg = SHA1.Create(algName);
					if(KeyValue != null)
					{
						alg.InternalHashCore(KeyValue, 0, KeyValue.Length);
					}
				}
			}

	// Write data to the underlying hash algorithm.
	protected override void HashCore(byte[] array, int ibStart, int cbSize)
			{
				Prepare();
				alg.InternalHashCore(array, ibStart, cbSize);
			}

	// Finalize the hash and return the final hash value.
	protected override byte[] HashFinal()
			{
				// Compute the final hash, which is "H(K, H(K, Data))".
				Prepare();
				byte[] inner = alg.InternalHashFinal();
				alg.Initialize();
				if(KeyValue != null)
				{
					alg.InternalHashCore(KeyValue, 0, KeyValue.Length);
				}
				alg.InternalHashCore(inner, 0, inner.Length);
				Array.Clear(inner, 0, inner.Length);
				return alg.InternalHashFinal();
			}

}; // class HMAC

#endif // CONFIG_CRYPTO

}; // namespace System.Security.Cryptography


text:
export default function Feature (Component, featureName, props, actions) {
  return {
    Component,
    name: featureName,
    props,
    actions
  }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Reftest Reference</title>
<link rel="author" title="Emilio Cobos Álvarez" href="mailto:ecobos@igalia.com">

Test passes if you see the word "PASS" below

PASS


text:
#include "InterpreterRuleContext.h"

using namespace antlr4;

InterpreterRuleContext::InterpreterRuleContext() : ParserRuleContext() {
}

InterpreterRuleContext::InterpreterRuleContext(ParserRuleContext *parent, size_t invokingStateNumber, size_t ruleIndex)
  : ParserRuleContext(parent, invokingStateNumber), _ruleIndex(ruleIndex) {
}

size_t InterpreterRuleContext::getRuleIndex() const {
  return _ruleIndex;
}


text:
package rx.redis.commands

import rx.redis.serialization._

import io.netty.buffer.{ ByteBuf, Unpooled }
import org.scalatest.FunSuite

import java.nio.charset.StandardCharsets

class CommandsSuite extends FunSuite {

  val charset = StandardCharsets.UTF_8

  protected def pretty(s: String, snip: Option[Int] = None) =
    Some(s.replaceAllLiterally("\r\n", "\\r\\n")).map(s ⇒ snip.fold(s)(s.take)).get

  protected def ser[A: Writes](c: A, expectedBuf: ByteBuf): Unit = {
    val actualBuf = Writes[A].write(Unpooled.buffer(), c)
    try assert(actualBuf == expectedBuf) finally actualBuf.release()
  }

  protected def sers[A: Writes](c: A, expectedParts: String*) =
    ser(c, rx.redis.RedisCommand(expectedParts.mkString(" ")))
}


text:
<?php

/**
 * @author Bence Eros <crystal@cyclonephp.com>
 * @package CyForm
 */
class CyForm_Field_Submit extends CyForm_Field {

    public function  __construct(CyForm $form, $name, CyForm_Model_Field $model, $cfg) {
        parent::__construct($form, $name, $model, 'submit', $cfg);
    }

    public function set_data($val) {

    }

    public function get_data() {
        return null;
    }

    protected function  before_rendering() {

        if ( ! is_null($this->_model->name)) {
            $this->_model->attributes['name'] = $this->_model->name;
        }
        $this->_model->attributes['value'] = $this->_model->label;
        if (NULL === $this->_model->view) {
            $this->_model->view = 'submit';
        }
    }

}


text:
//
// <PlaceHolderClassName>.xaml.h
// Declaration of the <PlaceHolderClassName> class.
//

#pragma once

#include "<PlaceHolderClassName>.g.h"

namespace IslandwoodAutoGenNamespace {
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public ref class <PlaceHolderClassName> sealed {
    public:
        <PlaceHolderClassName>();
    };
}


text:
//
//  DWZImageHandle.h
//  DWZShareSDKDemo
//
//  Created by lerosua on 14-8-15.
//  Copyright (c) 2014年 lerosua. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#define TMO_UIKIT_DEVICE_WIDTH [UIScreen mainScreen].currentMode.size.width
#define TMO_UIKIT_DEVICE_HEIGHT [UIScreen mainScreen].currentMode.size.height
#define TMO_UIKIT_DEVICE_IS_RETINA (TMO_UIKIT_DEVICE_WIDTH == 640.0 || TMO_UIKIT_DEVICE_WIDTH == 1536.0)

@interface DWZImageHandle : NSObject

/**
 *  返回一张纯色的图片,大小为1px*1px
 *
 *  @param color 指定颜色UIColor对象
 *
 *  @return 返回UIImage对象
 */
+ (UIImage*)imageWithPureColor:(UIColor*)color;

/**
 *  返回一张被指定颜色覆盖的图片,图片必须为png格式
 *
 *  @param color 指定颜色UIColor对象
 *
 *  @return 处理后的UIImage对象
 */
+ (UIImage *)hanleImage:(UIImage *)image CoverWithColor:(UIColor *)color;
//返回图片的灰阶图
+ (UIImage *)grayImage:(UIImage *)sourceImage;
@end


text:
namespace _01.SinoTheWalker
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Globalization;

    public class SinoTheWalker
    {
        public static void Main()
        {
            var startingTime = DateTime.ParseExact(
                Console.ReadLine(), "HH:mm:ss", CultureInfo.InvariantCulture);
            var numberOfSteps = int.Parse(Console.ReadLine());
            var secondsPerStep = int.Parse(Console.ReadLine());
            var secondToAdd = numberOfSteps * secondsPerStep;

            for (int i = 0; i < numberOfSteps; i++)
            {
                startingTime = startingTime.AddSeconds(secondsPerStep);
                if (startingTime.Year > 8000)
                {
                    startingTime = new DateTime(1, 1, 1, startingTime.Hour, startingTime.Minute, startingTime.Second);
                }
            }
            Console.WriteLine($"Time Arrival: { startingTime.ToString("HH:mm:ss")}");
        }
    }
}


text:
package com.all.client.controller;

import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.all.appControl.ActionMethod;
import com.all.appControl.control.ControlEngine;
import com.all.client.model.TrackFile;
import com.all.client.peer.share.ShareService;
import com.all.client.services.MusicEntityService;
import com.all.client.services.reporting.ClientReporter;
import com.all.core.actions.Actions;
import com.all.core.events.ContainerModifiedEvent;
import com.all.core.events.Events;
import com.all.core.model.SearchState;
import com.all.event.ValueEvent;
import com.all.shared.model.Track;
import com.all.shared.stats.usage.UserActions;

@Controller
public class RestoreTracksController {

	@Autowired
	private ControlEngine controlEngine;
	@Autowired
	private ShareService shareService;
	@Autowired
	private MusicEntityService musicEntityService;
	@Autowired
	private ClientReporter reporter;

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

	@ActionMethod(Actions.Library.FIND_TRACKS_LOCALLY_ID)
	public void restoreTracks(File dir) {
		log.debug("Searching in dir: " + dir);
		if (dir != null) {
			controlEngine.fireEvent(Events.Application.SEARCH_TRACKS, new ValueEvent<SearchState>(SearchState.Started));
			List<Track> grayTracks = musicEntityService.getAllReferences();
			log.debug("Gray tracks: " + grayTracks);
			List<File> musicFiles = musicEntityService.findMusicFiles(dir);
			log.debug("Music Files: " + musicFiles.size());
			MultiMap fileTrackMap = getMap(grayTracks);
			filterByTracks(musicFiles, fileTrackMap);
			log.debug("Filtered Files: " + musicFiles.size());
			matchTracksAndFiles(grayTracks, musicFiles, fileTrackMap);
			log.debug("Sharing restored files");
			shareService.run();
			controlEngine.fireEvent(Events.Library.CONTAINER_MODIFIED, new ContainerModifiedEvent(null));
			controlEngine.fireEvent(Events.Application.SEARCH_TRACKS, new ValueEvent<SearchState>(SearchState.Stopped));
			reporter.logUserAction(UserActions.Player.FIND_LOCAL_MEDIA);
		}
	}

	@SuppressWarnings("unchecked")
	private void matchTracksAndFiles(List<Track> grayTracks, List<File> musicFiles, MultiMap fileTrackMap) {
		for (File file : musicFiles) {
			TrackFile trackFile = new TrackFile(file);
			Predicate hashCodePredicate = new BeanPropertyValueEqualsPredicate("hashcode", trackFile.getHashcode());
			Collection<Track> fileTracks = (Collection<Track>) fileTrackMap.get(file.getName());
			Object sameFileTrack = CollectionUtils.find(fileTracks, hashCodePredicate);
			if (sameFileTrack != null) {
				grayTracks.remove(sameFileTrack);
				musicEntityService.addTrackFile(trackFile);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void filterByTracks(List<File> musicFiles, MultiMap fileTrackMap) {
		final Set<String> trackFileNames = fileTrackMap.keySet();
		Predicate fileNamePredicate = new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				File file = (File) object;
				return trackFileNames.contains(file.getName());
			}
		};
		CollectionUtils.filter(musicFiles, fileNamePredicate);
	}

	private MultiMap getMap(List<Track> grayTracks) {
		MultiMap map = new MultiHashMap(grayTracks.size());
		for (Track track : grayTracks) {
			map.put(track.getFileName(), track);
		}
		return map;
	}

}


text:
const router = require('express').Router();

const buildHandler = (req, res) => {
	res.render('build');
};

module.exports = router.get('/', buildHandler);


text:
  {% if site.logo %}{{site.logo}}{% else %}Bef{% endif %}

    About
    Our Project
    Contact


text:
namespace content {
namespace {

// Strip out the non-digital info; if after that, we get an empty string,
// return "0".
std::string ProcessVersionString(const std::string& raw_string) {
  const std::string valid_set = "0123456789.";
  size_t start_pos = raw_string.find_first_of(valid_set);
  if (start_pos == std::string::npos)
    return "0";
  size_t end_pos = raw_string.find_first_not_of(raw_string, start_pos);
  std::string version_string = raw_string.substr(
      start_pos, end_pos - start_pos);
  if (version_string.empty())
    return "0";
  return version_string;
}

#if defined(OS_MACOSX)
void DisplayReconfigCallback(CGDirectDisplayID display,
                             CGDisplayChangeSummaryFlags flags,
                             void* gpu_data_manager) {
  if (flags & kCGDisplayAddFlag) {
    GpuDataManagerImpl* manager =
        reinterpret_cast<GpuDataManagerImpl*>(gpu_data_manager);
    DCHECK(manager);
    manager->HandleGpuSwitch();
  }
}
#endif  // OS_MACOSX

// Block all domains' use of 3D APIs for this many milliseconds if
// approaching a threshold where system stability might be compromised.
const int64 kBlockAllDomainsMs = 10000;
const int kNumResetsWithinDuration = 1;

// Enums for UMA histograms.
enum BlockStatusHistogram {
  BLOCK_STATUS_NOT_BLOCKED,
  BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED,
  BLOCK_STATUS_ALL_DOMAINS_BLOCKED,
  BLOCK_STATUS_MAX
};

}  // namespace anonymous

// static
GpuDataManager* GpuDataManager::GetInstance() {
  return GpuDataManagerImpl::GetInstance();
}

// static
GpuDataManagerImpl* GpuDataManagerImpl::GetInstance() {
  return Singleton<GpuDataManagerImpl>::get();
}

GpuDataManagerImpl::GpuDataManagerImpl()
    : complete_gpu_info_already_requested_(false),
      blacklisted_features_(GPU_FEATURE_TYPE_UNKNOWN),
      preliminary_blacklisted_features_(GPU_FEATURE_TYPE_UNKNOWN),
      gpu_switching_(GPU_SWITCHING_OPTION_AUTOMATIC),
      observer_list_(new GpuDataManagerObserverList),
      software_rendering_(false),
      card_blacklisted_(false),
      update_histograms_(true),
      window_count_(0),
      domain_blocking_enabled_(true) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableAcceleratedCompositing)) {
    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);
    command_line->AppendSwitch(switches::kDisableAcceleratedLayers);
  }
  if (command_line->HasSwitch(switches::kDisableGpu))
    BlacklistCard();
  if (command_line->HasSwitch(switches::kGpuSwitching)) {
    std::string option_string = command_line->GetSwitchValueASCII(
        switches::kGpuSwitching);
    GpuSwitchingOption option = StringToGpuSwitchingOption(option_string);
    if (option != GPU_SWITCHING_OPTION_UNKNOWN)
      gpu_switching_ = option;
  }

#if defined(OS_MACOSX)
  CGDisplayRegisterReconfigurationCallback(DisplayReconfigCallback, this);
#endif  // OS_MACOSX
}

void GpuDataManagerImpl::Initialize() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kSkipGpuDataLoading))
    return;

  GPUInfo gpu_info;
  gpu_info_collector::CollectBasicGraphicsInfo(&gpu_info);
#if defined(ARCH_CPU_X86_FAMILY)
  if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id)
    gpu_info.finalized = true;
#endif

  std::string gpu_blacklist_string;
  if (!command_line->HasSwitch(switches::kIgnoreGpuBlacklist)) {
    const base::StringPiece gpu_blacklist_json =
        GetContentClient()->GetDataResource(
            IDR_GPU_BLACKLIST, ui::SCALE_FACTOR_NONE);
    gpu_blacklist_string = gpu_blacklist_json.as_string();
  }

  InitializeImpl(gpu_blacklist_string, gpu_info);
}

void GpuDataManagerImpl::InitializeForTesting(
    const std::string& gpu_blacklist_json,
    const GPUInfo& gpu_info) {
  // This function is for testing only, so disable histograms.
  update_histograms_ = false;

  InitializeImpl(gpu_blacklist_json, gpu_info);
}

void GpuDataManagerImpl::InitializeImpl(
    const std::string& gpu_blacklist_json,
    const GPUInfo& gpu_info) {
  if (!gpu_blacklist_json.empty()) {
    std::string browser_version_string = ProcessVersionString(
        GetContentClient()->GetProduct());
    CHECK(!browser_version_string.empty());
    gpu_blacklist_.reset(new GpuBlacklist());
    bool succeed = gpu_blacklist_->LoadGpuBlacklist(
        browser_version_string,
        gpu_blacklist_json,
        GpuBlacklist::kCurrentOsOnly);
    CHECK(succeed);
  }

  {
    base::AutoLock auto_lock(gpu_info_lock_);
    gpu_info_ = gpu_info;
  }
  UpdateGpuInfo(gpu_info);
  UpdateGpuSwitchingManager(gpu_info);
  UpdatePreliminaryBlacklistedFeatures();
}

GpuDataManagerImpl::~GpuDataManagerImpl() {
#if defined(OS_MACOSX)
  CGDisplayRemoveReconfigurationCallback(DisplayReconfigCallback, this);
#endif
}

void GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() {
  if (complete_gpu_info_already_requested_ || gpu_info_.finalized)
    return;
  complete_gpu_info_already_requested_ = true;

  GpuProcessHost::SendOnIO(
#if defined(OS_WIN)
      GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED,
#else
      GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
#endif
      CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED,
      new GpuMsg_CollectGraphicsInfo());
}

bool GpuDataManagerImpl::IsCompleteGpuInfoAvailable() const {
  return gpu_info_.finalized;
}

void GpuDataManagerImpl::UpdateGpuInfo(const GPUInfo& gpu_info) {
  // No further update of gpu_info if falling back to software renderer.
  if (software_rendering_)
    return;

  GPUInfo my_gpu_info;
  {
    base::AutoLock auto_lock(gpu_info_lock_);
    gpu_info_collector::MergeGPUInfo(&gpu_info_, gpu_info);
    complete_gpu_info_already_requested_ =
        complete_gpu_info_already_requested_ || gpu_info_.finalized;
    my_gpu_info = gpu_info_;
  }

  GetContentClient()->SetGpuInfo(my_gpu_info);

  if (gpu_blacklist_.get()) {
    GpuBlacklist::Decision decision =
        gpu_blacklist_->MakeBlacklistDecision(
            GpuBlacklist::kOsAny, "", my_gpu_info);
    if (update_histograms_)
      UpdateStats(gpu_blacklist_.get(), decision.blacklisted_features);

    UpdateBlacklistedFeatures(decision.blacklisted_features);
    if (decision.gpu_switching != GPU_SWITCHING_OPTION_UNKNOWN) {
      // Blacklist decision should not overwrite commandline switch from users.
      CommandLine* command_line = CommandLine::ForCurrentProcess();
      if (!command_line->HasSwitch(switches::kGpuSwitching))
        gpu_switching_ = decision.gpu_switching;
    }
  }

  // We have to update GpuFeatureType before notify all the observers.
  NotifyGpuInfoUpdate();
}

GPUInfo GpuDataManagerImpl::GetGPUInfo() const {
  GPUInfo gpu_info;
  {
    base::AutoLock auto_lock(gpu_info_lock_);
    gpu_info = gpu_info_;
  }
  return gpu_info;
}

void GpuDataManagerImpl::GetGpuProcessHandles(
    const GetGpuProcessHandlesCallback& callback) const {
  GpuProcessHost::GetProcessHandles(callback);
}

void GpuDataManagerImpl::RequestVideoMemoryUsageStatsUpdate() const {
  GpuProcessHost::SendOnIO(
      GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
      CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
      new GpuMsg_GetVideoMemoryUsageStats());
}

void GpuDataManagerImpl::AddLogMessage(
    int level, const std::string& header, const std::string& message) {
  base::AutoLock auto_lock(log_messages_lock_);
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger("level", level);
  dict->SetString("header", header);
  dict->SetString("message", message);
  log_messages_.Append(dict);
}

base::ListValue* GpuDataManagerImpl::GetLogMessages() const {
  base::ListValue* value;
  {
    base::AutoLock auto_lock(log_messages_lock_);
    value = log_messages_.DeepCopy();
  }
  return value;
}

std::string GpuDataManagerImpl::GetBlacklistVersion() const {
  if (gpu_blacklist_.get())
    return gpu_blacklist_->GetVersion();
  return "0";
}

GpuFeatureType GpuDataManagerImpl::GetBlacklistedFeatures() const {
  if (software_rendering_) {
    GpuFeatureType flags;

    // Skia's software rendering is probably more efficient than going through
    // software emulation of the GPU, so use that.
    flags = GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS;
    return flags;
  }

  return blacklisted_features_;
}

GpuSwitchingOption GpuDataManagerImpl::GetGpuSwitchingOption() const {
  if (!ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus())
    return GPU_SWITCHING_OPTION_UNKNOWN;
  return gpu_switching_;
}

base::ListValue* GpuDataManagerImpl::GetBlacklistReasons() const {
  ListValue* reasons = new ListValue();
  if (gpu_blacklist_.get())
    gpu_blacklist_->GetBlacklistReasons(reasons);
  return reasons;
}

bool GpuDataManagerImpl::GpuAccessAllowed() const {
  if (software_rendering_)
    return true;

  if (!gpu_info_.gpu_accessible)
    return false;

  if (card_blacklisted_)
    return false;

  // We only need to block GPU process if more features are disallowed other
  // than those in the preliminary gpu feature flags because the latter work
  // through renderer commandline switches.
  uint32 mask = ~(preliminary_blacklisted_features_);
  if ((blacklisted_features_ & mask) != 0)
    return false;

  if (blacklisted_features_ == GPU_FEATURE_TYPE_ALL) {
    // On Linux, we use cached GL strings to make blacklist decsions at browser
    // startup time. We need to launch the GPU process to validate these
    // strings even if all features are blacklisted. If all GPU features are
    // disabled, the GPU process will only initialize GL bindings, create a GL
    // context, and collect full GPU info.
#if !defined(OS_LINUX)
    return false;
#endif
  }

  return true;
}

void GpuDataManagerImpl::HandleGpuSwitch() {
  if (complete_gpu_info_already_requested_) {
    complete_gpu_info_already_requested_ = false;
    gpu_info_.finalized = false;
    RequestCompleteGpuInfoIfNeeded();
  }
}

void GpuDataManagerImpl::AddObserver(GpuDataManagerObserver* observer) {
  observer_list_->AddObserver(observer);
}

void GpuDataManagerImpl::RemoveObserver(GpuDataManagerObserver* observer) {
  observer_list_->RemoveObserver(observer);
}

void GpuDataManagerImpl::SetWindowCount(uint32 count) {
  {
    base::AutoLock auto_lock(gpu_info_lock_);
    window_count_ = count;
  }
  GpuProcessHost::SendOnIO(
      GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
      CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
      new GpuMsg_SetVideoMemoryWindowCount(count));
}

uint32 GpuDataManagerImpl::GetWindowCount() const {
  base::AutoLock auto_lock(gpu_info_lock_);
  return window_count_;
}

void GpuDataManagerImpl::UnblockDomainFrom3DAPIs(const GURL& url) {
  // This method must do two things:
  //
  //  1. If the specific domain is blocked, then unblock it.
  //
  //  2. Reset our notion of how many GPU resets have occurred recently.
  //     This is necessary even if the specific domain was blocked.
  //     Otherwise, if we call Are3DAPIsBlocked with the same domain right
  //     after unblocking it, it will probably still be blocked because of
  //     the recent GPU reset caused by that domain.
  //
  // These policies could be refined, but at a certain point the behavior
  // will become difficult to explain.
  std::string domain = GetDomainFromURL(url);

  base::AutoLock auto_lock(gpu_info_lock_);
  blocked_domains_.erase(domain);
  timestamps_of_gpu_resets_.clear();
}

void GpuDataManagerImpl::DisableDomainBlockingFor3DAPIsForTesting() {
  domain_blocking_enabled_ = false;
}

void GpuDataManagerImpl::DisableGpuWatchdog() {
  GpuProcessHost::SendOnIO(
      GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED,
      CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH,
      new GpuMsg_DisableWatchdog);
}

void GpuDataManagerImpl::AppendRendererCommandLine(
    CommandLine* command_line) const {
  DCHECK(command_line);

  uint32 flags = GetBlacklistedFeatures();
  if ((flags & GPU_FEATURE_TYPE_WEBGL)) {
#if !defined(OS_ANDROID)
    if (!command_line->HasSwitch(switches::kDisableExperimentalWebGL))
      command_line->AppendSwitch(switches::kDisableExperimentalWebGL);
#endif
    if (!command_line->HasSwitch(switches::kDisablePepper3d))
      command_line->AppendSwitch(switches::kDisablePepper3d);
  }
  if ((flags & GPU_FEATURE_TYPE_MULTISAMPLING) &&
      !command_line->HasSwitch(switches::kDisableGLMultisampling))
    command_line->AppendSwitch(switches::kDisableGLMultisampling);
  if ((flags & GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) &&
      !command_line->HasSwitch(switches::kDisableAcceleratedCompositing))
    command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);
  if ((flags & GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) &&
      !command_line->HasSwitch(switches::kDisableAccelerated2dCanvas))
    command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);
  if ((flags & GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) &&
      !command_line->HasSwitch(switches::kDisableAcceleratedVideoDecode))
    command_line->AppendSwitch(switches::kDisableAcceleratedVideoDecode);
  if (ShouldUseSoftwareRendering())
    command_line->AppendSwitch(switches::kDisableFlashFullscreen3d);
}

void GpuDataManagerImpl::AppendGpuCommandLine(
    CommandLine* command_line) const {
  DCHECK(command_line);

  std::string use_gl =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switches::kUseGL);
  FilePath swiftshader_path =
      CommandLine::ForCurrentProcess()->GetSwitchValuePath(
          switches::kSwiftShaderPath);
  uint32 flags = GetBlacklistedFeatures();
  if ((flags & GPU_FEATURE_TYPE_MULTISAMPLING) &&
      !command_line->HasSwitch(switches::kDisableGLMultisampling))
    command_line->AppendSwitch(switches::kDisableGLMultisampling);
  if (flags & GPU_FEATURE_TYPE_TEXTURE_SHARING)
    command_line->AppendSwitch(switches::kDisableImageTransportSurface);

  if (software_rendering_) {
    command_line->AppendSwitchASCII(switches::kUseGL, "swiftshader");
    if (swiftshader_path.empty())
      swiftshader_path = swiftshader_path_;
  } else if ((flags & (GPU_FEATURE_TYPE_WEBGL |
                GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING |
                GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) &&
      (use_gl == "any")) {
    command_line->AppendSwitchASCII(
        switches::kUseGL, gfx::kGLImplementationOSMesaName);
  } else if (!use_gl.empty()) {
    command_line->AppendSwitchASCII(switches::kUseGL, use_gl);
  }
  if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) {
    command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "true");
    switch (gpu_switching_) {
      case GPU_SWITCHING_OPTION_FORCE_DISCRETE:
        command_line->AppendSwitchASCII(switches::kGpuSwitching,
            switches::kGpuSwitchingOptionNameForceDiscrete);
        break;
      case GPU_SWITCHING_OPTION_FORCE_INTEGRATED:
        command_line->AppendSwitchASCII(switches::kGpuSwitching,
            switches::kGpuSwitchingOptionNameForceIntegrated);
        break;
      case GPU_SWITCHING_OPTION_AUTOMATIC:
      case GPU_SWITCHING_OPTION_UNKNOWN:
        break;
    }
  } else {
    command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "false");
  }

  if (!swiftshader_path.empty())
    command_line->AppendSwitchPath(switches::kSwiftShaderPath,
                                   swiftshader_path);

  {
    base::AutoLock auto_lock(gpu_info_lock_);
    if (gpu_info_.optimus)
      command_line->AppendSwitch(switches::kReduceGpuSandbox);
    if (gpu_info_.amd_switchable) {
      // The image transport surface currently doesn't work with AMD Dynamic
      // Switchable graphics.
      command_line->AppendSwitch(switches::kReduceGpuSandbox);
      command_line->AppendSwitch(switches::kDisableImageTransportSurface);
    }
    // Pass GPU and driver information to GPU process. We try to avoid full GPU
    // info collection at GPU process startup, but we need gpu vendor_id,
    // device_id, driver_vendor, driver_version for deciding whether we need to
    // collect full info (on Linux) and for crash reporting purpose.
    command_line->AppendSwitchASCII(switches::kGpuVendorID,
        base::StringPrintf("0x%04x", gpu_info_.gpu.vendor_id));
    command_line->AppendSwitchASCII(switches::kGpuDeviceID,
        base::StringPrintf("0x%04x", gpu_info_.gpu.device_id));
    command_line->AppendSwitchASCII(switches::kGpuDriverVendor,
        gpu_info_.driver_vendor);
    command_line->AppendSwitchASCII(switches::kGpuDriverVersion,
        gpu_info_.driver_version);
  }
}

#if defined(OS_WIN)
bool GpuDataManagerImpl::IsUsingAcceleratedSurface() const {
  if (base::win::GetVersion() < base::win::VERSION_VISTA)
    return false;

  if (gpu_info_.amd_switchable)
    return false;
  if (software_rendering_)
    return false;
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableImageTransportSurface))
    return false;
  uint32 flags = GetBlacklistedFeatures();
  if (flags & GPU_FEATURE_TYPE_TEXTURE_SHARING)
    return false;

  return true;
}
#endif

void GpuDataManagerImpl::BlockDomainFrom3DAPIs(
    const GURL& url, DomainGuilt guilt) {
  BlockDomainFrom3DAPIsAtTime(url, guilt, base::Time::Now());
}

GpuDataManagerImpl::DomainBlockStatus
GpuDataManagerImpl::Are3DAPIsBlocked(const GURL& url) const {
  return Are3DAPIsBlockedAtTime(url, base::Time::Now());
}

void GpuDataManagerImpl::AppendPluginCommandLine(
    CommandLine* command_line) const {
  DCHECK(command_line);

#if defined(OS_MACOSX)
  uint32 flags = GetBlacklistedFeatures();
  // TODO(jbauman): Add proper blacklist support for core animation plugins so
  // special-casing this video card won't be necessary. See
  // http://crbug.com/134015
  if ((flags & GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING) ||
      CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableAcceleratedCompositing)) {
    if (!command_line->HasSwitch(
           switches::kDisableCoreAnimationPlugins))
      command_line->AppendSwitch(
          switches::kDisableCoreAnimationPlugins);
  }
#endif
}

void GpuDataManagerImpl::UpdatePreliminaryBlacklistedFeatures() {
  preliminary_blacklisted_features_ = blacklisted_features_;
}

void GpuDataManagerImpl::NotifyGpuInfoUpdate() {
  observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate);
}

void GpuDataManagerImpl::UpdateVideoMemoryUsageStats(
    const GPUVideoMemoryUsageStats& video_memory_usage_stats) {
  observer_list_->Notify(&GpuDataManagerObserver::OnVideoMemoryUsageStatsUpdate,
                         video_memory_usage_stats);
}

void GpuDataManagerImpl::UpdateBlacklistedFeatures(
    GpuFeatureType features) {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  int flags = features;

  // Force disable using the GPU for these features, even if they would
  // otherwise be allowed.
  if (card_blacklisted_ ||
      command_line->HasSwitch(switches::kBlacklistAcceleratedCompositing)) {
    flags |= GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING;
  }
  if (card_blacklisted_ ||
      command_line->HasSwitch(switches::kBlacklistWebGL)) {
    flags |= GPU_FEATURE_TYPE_WEBGL;
  }
  blacklisted_features_ = static_cast<GpuFeatureType>(flags);

  EnableSoftwareRenderingIfNecessary();
}

void GpuDataManagerImpl::UpdateGpuSwitchingManager(const GPUInfo& gpu_info) {
  ui::GpuSwitchingManager::GetInstance()->SetGpuCount(
      gpu_info.secondary_gpus.size() + 1);

  if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) {
    switch (gpu_switching_) {
      case GPU_SWITCHING_OPTION_FORCE_DISCRETE:
        ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu();
        break;
      case GPU_SWITCHING_OPTION_FORCE_INTEGRATED:
        ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu();
        break;
      case GPU_SWITCHING_OPTION_AUTOMATIC:
      case GPU_SWITCHING_OPTION_UNKNOWN:
        break;
    }
  }
}

void GpuDataManagerImpl::RegisterSwiftShaderPath(const FilePath& path) {
  swiftshader_path_ = path;
  EnableSoftwareRenderingIfNecessary();
}

void GpuDataManagerImpl::EnableSoftwareRenderingIfNecessary() {
  if (!GpuAccessAllowed() ||
      (blacklisted_features_ & GPU_FEATURE_TYPE_WEBGL)) {
    if (!swiftshader_path_.empty() &&
        !CommandLine::ForCurrentProcess()->HasSwitch(
             switches::kDisableSoftwareRasterizer))
      software_rendering_ = true;
  }
}

bool GpuDataManagerImpl::ShouldUseSoftwareRendering() const {
  return software_rendering_;
}

void GpuDataManagerImpl::BlacklistCard() {
  card_blacklisted_ = true;

  blacklisted_features_ = GPU_FEATURE_TYPE_ALL;

  EnableSoftwareRenderingIfNecessary();
  NotifyGpuInfoUpdate();
}

std::string GpuDataManagerImpl::GetDomainFromURL(const GURL& url) const {
  // For the moment, we just use the host, or its IP address, as the
  // entry in the set, rather than trying to figure out the top-level
  // domain. This does mean that a.foo.com and b.foo.com will be
  // treated independently in the blocking of a given domain, but it
  // would require a third-party library to reliably figure out the
  // top-level domain from a URL.
  if (!url.has_host()) {
    return std::string();
  }

  return url.host();
}

void GpuDataManagerImpl::BlockDomainFrom3DAPIsAtTime(
    const GURL& url, DomainGuilt guilt, base::Time at_time) {
  if (!domain_blocking_enabled_)
    return;

  std::string domain = GetDomainFromURL(url);

  base::AutoLock auto_lock(gpu_info_lock_);
  DomainBlockEntry& entry = blocked_domains_[domain];
  entry.last_guilt = guilt;
  timestamps_of_gpu_resets_.push_back(at_time);
}

GpuDataManagerImpl::DomainBlockStatus
GpuDataManagerImpl::Are3DAPIsBlockedAtTime(
    const GURL& url, base::Time at_time) const {
  if (!domain_blocking_enabled_)
    return DOMAIN_BLOCK_STATUS_NOT_BLOCKED;

  // Note: adjusting the policies in this code will almost certainly
  // require adjusting the associated unit tests.
  std::string domain = GetDomainFromURL(url);

  base::AutoLock auto_lock(gpu_info_lock_);
  {
    DomainBlockMap::const_iterator iter = blocked_domains_.find(domain);
    if (iter != blocked_domains_.end()) {
      // Err on the side of caution, and assume that if a particular
      // domain shows up in the block map, it's there for a good
      // reason and don't let its presence there automatically expire.

      UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
                                BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED,
                                BLOCK_STATUS_MAX);

      return DOMAIN_BLOCK_STATUS_BLOCKED;
    }
  }

  // Look at the timestamps of the recent GPU resets to see if there are
  // enough within the threshold which would cause us to blacklist all
  // domains. This doesn't need to be overly precise -- if time goes
  // backward due to a system clock adjustment, that's fine.
  //
  // TODO(kbr): make this pay attention to the TDR thresholds in the
  // Windows registry, but make sure it continues to be testable.
  std::list<base::Time>::iterator iter = timestamps_of_gpu_resets_.begin();
  int num_resets_within_timeframe = 0;
  while (iter != timestamps_of_gpu_resets_.end()) {
    base::Time time = *iter;
    base::TimeDelta delta_t = at_time - time;

    // If this entry has "expired", just remove it.
    if (delta_t.InMilliseconds() > kBlockAllDomainsMs) {
      iter = timestamps_of_gpu_resets_.erase(iter);
      continue;
    }

    ++num_resets_within_timeframe;
    ++iter;
  }

  if (num_resets_within_timeframe >= kNumResetsWithinDuration) {
    UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
                              BLOCK_STATUS_ALL_DOMAINS_BLOCKED,
                              BLOCK_STATUS_MAX);

    return DOMAIN_BLOCK_STATUS_ALL_DOMAINS_BLOCKED;
  }

  UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs",
                            BLOCK_STATUS_NOT_BLOCKED,
                            BLOCK_STATUS_MAX);

  return DOMAIN_BLOCK_STATUS_NOT_BLOCKED;
}

int64 GpuDataManagerImpl::GetBlockAllDomainsDurationInMs() const {
  return kBlockAllDomainsMs;
}

void GpuDataManagerImpl::GetGLStrings(std::string* gl_vendor,
                                      std::string* gl_renderer,
                                      std::string* gl_version) {
  DCHECK(gl_vendor && gl_renderer && gl_version);

  base::AutoLock auto_lock(gpu_info_lock_);
  *gl_vendor = gpu_info_.gl_vendor;
  *gl_renderer = gpu_info_.gl_renderer;
  *gl_version = gpu_info_.gl_version_string;
}

void GpuDataManagerImpl::SetGLStrings(const std::string& gl_vendor,
                                      const std::string& gl_renderer,
                                      const std::string& gl_version) {
  if (gl_vendor.empty() && gl_renderer.empty() && gl_version.empty())
    return;

  GPUInfo gpu_info;
  {
    base::AutoLock auto_lock(gpu_info_lock_);
    // If GPUInfo already got GL strings, do nothing.  This is for the rare
    // situation where GPU process collected GL strings before this call.
    if (!gpu_info_.gl_vendor.empty() ||
        !gpu_info_.gl_renderer.empty() ||
        !gpu_info_.gl_version_string.empty())
      return;
    gpu_info = gpu_info_;
  }

  gpu_info.gl_vendor = gl_vendor;
  gpu_info.gl_renderer = gl_renderer;
  gpu_info.gl_version_string = gl_version;

  gpu_info_collector::CollectDriverInfoGL(&gpu_info);

  UpdateGpuInfo(gpu_info);
  UpdateGpuSwitchingManager(gpu_info);
  UpdatePreliminaryBlacklistedFeatures();
}

}  // namespace content


text:
package org.apache.activemq.artemis.protocol.amqp.sasl;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

public class MechanismFinder {

   private static final Map<String, ServerSASLFactory> FACTORY_MAP = new HashMap<>();
   private static final Comparator<? super ServerSASLFactory> PRECEDENCE_COMPARATOR =
      (f1, f2) -> Integer.compare(f1.getPrecedence(), f2.getPrecedence());
   private static final String[] DEFAULT_MECHANISMS;

   static {
      ServiceLoader<ServerSASLFactory> serviceLoader =
               ServiceLoader.load(ServerSASLFactory.class, MechanismFinder.class.getClassLoader());
      for (ServerSASLFactory factory : serviceLoader) {
         FACTORY_MAP.merge(factory.getMechanism(), factory, (f1, f2) -> {
            if (f2.getPrecedence() > f1.getPrecedence()) {
               return f2;
            } else {
               return f1;
            }
         });
      }
      DEFAULT_MECHANISMS = FACTORY_MAP.values()
                                      .stream()
                                      .filter(ServerSASLFactory::isDefaultPermitted)
                                      .sorted(PRECEDENCE_COMPARATOR.reversed())
                                      .map(ServerSASLFactory::getMechanism)
                                      .toArray(String[]::new);
   }

   public static String[] getDefaultMechanisms() {
      return DEFAULT_MECHANISMS;
   }

   public static ServerSASLFactory getFactory(String mechanism) {
      return FACTORY_MAP.get(mechanism);
   }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_show_playlist"
        android:icon="@drawable/song_pic"
        android:title="Playlist"
        />
</menu>


text:
This project can be used as a starter for a webapp built with CodeIgniter 3.1.

This starter builds on [CodeIgniter3.1-starter1](https://github.com/jedi-academy/CodeIgniter3.1-starter1),
adding a base controller with view templating.

**controllers/Welcome.php** has been modified to set the name of the desired
view file as a *data* parameter, and to then invoke the inherited *render*
method to trigger presentation.

A view template is provided. The CSS has been extracted to an appropriate file
in the public folder. Styling could be improved by using a CSS framework, like
Bootstrap.

The **application/config/autoload.php** configuration has been modified
to preload the template parser library and the url helper.

Configure your web server or virtual host so that your project's
document root maps to this **public** folder inside your project.