// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osuTK;

namespace osu.Game.Tournament.Screens.Gameplay.Components
{
    public class MatchHeader : Container
    {
        private TeamScoreDisplay teamDisplay1;
        private TeamScoreDisplay teamDisplay2;
        private DrawableTournamentHeaderLogo logo;

        private bool showScores = true;

        public bool ShowScores
        {
            get => showScores;
            set
            {
                if (value == showScores)
                    return;

                showScores = value;

                if (IsLoaded)
                    updateDisplay();
            }
        }

        private bool showLogo = true;

        public bool ShowLogo
        {
            get => showLogo;
            set
            {
                if (value == showLogo)
                    return;

                showLogo = value;

                if (IsLoaded)
                    updateDisplay();
            }
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            RelativeSizeAxes = Axes.X;
            Height = 95;
            Children = new Drawable[]
            {
                new FillFlowContainer
                {
                    RelativeSizeAxes = Axes.Both,
                    Direction = FillDirection.Vertical,
                    Padding = new MarginPadding(20),
                    Spacing = new Vector2(5),
                    Children = new Drawable[]
                    {
                        logo = new DrawableTournamentHeaderLogo
                        {
                            Anchor = Anchor.TopCentre,
                            Origin = Anchor.TopCentre,
                            Alpha = showLogo ? 1 : 0
                        },
                        new DrawableTournamentHeaderText
                        {
                            Anchor = Anchor.TopCentre,
                            Origin = Anchor.TopCentre,
                        },
                        new MatchRoundDisplay
                        {
                            Anchor = Anchor.TopCentre,
                            Origin = Anchor.TopCentre,
                            Scale = new Vector2(0.4f)
                        },
                    }
                },
                teamDisplay1 = new TeamScoreDisplay(TeamColour.Red)
                {
                    Anchor = Anchor.TopLeft,
                    Origin = Anchor.TopLeft,
                },
                teamDisplay2 = new TeamScoreDisplay(TeamColour.Blue)
                {
                    Anchor = Anchor.TopRight,
                    Origin = Anchor.TopRight,
                },
            };

            updateDisplay();
        }

        private void updateDisplay()
        {
            teamDisplay1.ShowScore = showScores;
            teamDisplay2.ShowScore = showScores;

            logo.Alpha = showLogo ? 1 : 0;
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Graphics;
using osu.Framework.Bindables;
using osu.Game.Rulesets;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests.Responses;
using osuTK;
using osu.Framework.Allocation;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Overlays.Rankings.Tables;
using System.Linq;
using System.Threading;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.BeatmapListing.Panels;

namespace osu.Game.Overlays.Rankings
{
    public class SpotlightsLayout : CompositeDrawable
    {
        public readonly Bindable<RulesetInfo> Ruleset = new Bindable<RulesetInfo>();

        private readonly Bindable<APISpotlight> selectedSpotlight = new Bindable<APISpotlight>();
        private readonly Bindable<RankingsSortCriteria> sort = new Bindable<RankingsSortCriteria>();

        [Resolved]
        private IAPIProvider api { get; set; }

        [Resolved]
        private RulesetStore rulesets { get; set; }

        private CancellationTokenSource cancellationToken;
        private GetSpotlightRankingsRequest getRankingsRequest;
        private GetSpotlightsRequest spotlightsRequest;

        private SpotlightSelector selector;
        private Container content;
        private LoadingLayer loading;

        [BackgroundDependencyLoader]
        private void load()
        {
            RelativeSizeAxes = Axes.X;
            AutoSizeAxes = Axes.Y;

            InternalChild = new ReverseChildIDFillFlowContainer<Drawable>
            {
                RelativeSizeAxes = Axes.X,
                AutoSizeAxes = Axes.Y,
                Direction = FillDirection.Vertical,
                Children = new Drawable[]
                {
                    selector = new SpotlightSelector
                    {
                        Current = selectedSpotlight,
                    },
                    new Container
                    {
                        RelativeSizeAxes = Axes.X,
                        AutoSizeAxes = Axes.Y,
                        Children = new Drawable[]
                        {
                            content = new Container
                            {
                                RelativeSizeAxes = Axes.X,
                                AutoSizeAxes = Axes.Y,
                                Margin = new MarginPadding { Vertical = 10 }
                            },
                            loading = new LoadingLayer(true)
                        }
                    }
                }
            };

            sort.BindTo(selector.Sort);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            selectedSpotlight.BindValueChanged(_ => onSpotlightChanged());
            sort.BindValueChanged(_ => onSpotlightChanged());
            Ruleset.BindValueChanged(onRulesetChanged);

            getSpotlights();
        }

        private void getSpotlights()
        {
            spotlightsRequest = new GetSpotlightsRequest();
            spotlightsRequest.Success += response => Schedule(() => selector.Spotlights = response.Spotlights);
            api.Queue(spotlightsRequest);
        }

        private void onRulesetChanged(ValueChangedEvent<RulesetInfo> ruleset)
        {
            if (!selector.Spotlights.Any())
                return;

            selectedSpotlight.TriggerChange();
        }

        private void onSpotlightChanged()
        {
            loading.Show();

            cancellationToken?.Cancel();
            getRankingsRequest?.Cancel();

            getRankingsRequest = new GetSpotlightRankingsRequest(Ruleset.Value, selectedSpotlight.Value.Id, sort.Value);
            getRankingsRequest.Success += onSuccess;
            api.Queue(getRankingsRequest);
        }

        private void onSuccess(GetSpotlightRankingsResponse response)
        {
            LoadComponentAsync(createContent(response), loaded =>
            {
                selector.ShowInfo(response);

                content.Clear();
                content.Add(loaded);

                loading.Hide();
            }, (cancellationToken = new CancellationTokenSource()).Token);
        }

        private Drawable createContent(GetSpotlightRankingsResponse response) => new FillFlowContainer
        {
            AutoSizeAxes = Axes.Y,
            RelativeSizeAxes = Axes.X,
            Direction = FillDirection.Vertical,
            Spacing = new Vector2(0, 20),
            Children = new Drawable[]
            {
                new ScoresTable(1, response.Users),
                new FillFlowContainer
                {
                    AutoSizeAxes = Axes.Y,
                    RelativeSizeAxes = Axes.X,
                    Spacing = new Vector2(10),
                    Children = response.BeatmapSets.Select(b => new GridBeatmapPanel(b.ToBeatmapSet(rulesets))
                    {
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                    }).ToList()
                }
            }
        };

        protected override void Dispose(bool isDisposing)
        {
            spotlightsRequest?.Cancel();
            getRankingsRequest?.Cancel();
            cancellationToken?.Cancel();

            base.Dispose(isDisposing);
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;

namespace osu.Game.Tournament.Screens.Drawings.Components
{
    public class VisualiserContainer : Container
    {
        /// <summary>
        /// Number of lines in the visualiser.
        /// </summary>
        public int Lines
        {
            get => allLines.Count;
            set
            {
                while (value > allLines.Count)
                    addLine();

                while (value < allLines.Count)
                    removeLine();
            }
        }

        private readonly List<VisualiserLine> allLines = new List<VisualiserLine>();

        private float offset;

        private void addLine()
        {
            VisualiserLine newLine = new VisualiserLine
            {
                RelativeSizeAxes = Axes.Both,

                Offset = offset,
                CycleTime = RNG.Next(10000, 12000),
            };

            allLines.Add(newLine);
            Add(newLine);

            offset += RNG.Next(100, 5000);
        }

        private void removeLine()
        {
            if (allLines.Count == 0)
                return;

            Remove(allLines.First());
            allLines.Remove(allLines.First());
        }

        private class VisualiserLine : Container
        {
            /// <summary>
            /// Time offset.
            /// </summary>
            public float Offset;

            public double CycleTime;

            private float leftPos => -(float)((Time.Current + Offset) / CycleTime) + expiredCount;

            private Texture texture;

            private int expiredCount;

            [BackgroundDependencyLoader]
            private void load(TextureStore textures)
            {
                texture = textures.Get("Drawings/visualiser-line");
            }

            protected override void UpdateAfterChildren()
            {
                base.UpdateAfterChildren();

                while (Children.Count < 3)
                    addLine();

                float pos = leftPos;

                foreach (var c in Children)
                {
                    if (c.Position.X < -1)
                    {
                        c.ClearTransforms();
                        c.Expire();
                        expiredCount++;
                    }
                    else
                        c.MoveToX(pos, 100);

                    pos += 1;
                }
            }

            private void addLine()
            {
                Add(new Sprite
                {
                    Anchor = Anchor.CentreLeft,
                    Origin = Anchor.CentreLeft,

                    RelativePositionAxes = Axes.Both,
                    RelativeSizeAxes = Axes.Both,

                    Texture = texture,

                    X = leftPos + 1
                });
            }
        }
    }
}


#nullable disable
using System.Collections.Generic;
using System.Text.Json.Serialization;
using MediaBrowser.Model.Entities;

namespace MediaBrowser.Model.Dto
{
    /// <summary>
    /// This is used by the api to get information about a Person within a BaseItem.
    /// </summary>
    public class BaseItemPerson
    {
        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the role.
        /// </summary>
        /// <value>The role.</value>
        public string Role { get; set; }

        /// <summary>
        /// Gets or sets the type.
        /// </summary>
        /// <value>The type.</value>
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets the primary image tag.
        /// </summary>
        /// <value>The primary image tag.</value>
        public string PrimaryImageTag { get; set; }

        /// <summary>
        /// Gets or sets the primary image blurhash.
        /// </summary>
        /// <value>The primary image blurhash.</value>
        public Dictionary<ImageType, Dictionary<string, string>> ImageBlurHashes { get; set; }

        /// <summary>
        /// Gets a value indicating whether this instance has primary image.
        /// </summary>
        /// <value><c>true</c> if this instance has primary image; otherwise, <c>false</c>.</value>
        [JsonIgnore]
        public bool HasPrimaryImage => PrimaryImageTag != null;
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics.Sprites;
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.UserInterface;

namespace osu.Game.Graphics.UserInterface
{
    public abstract class RollingCounter<T> : Container, IHasCurrentValue<T>
        where T : struct, IEquatable<T>
    {
        private readonly BindableWithCurrent<T> current = new BindableWithCurrent<T>();

        public Bindable<T> Current
        {
            get => current.Current;
            set => current.Current = value;
        }

        private SpriteText displayedCountSpriteText;

        /// <summary>
        /// If true, the roll-up duration will be proportional to change in value.
        /// </summary>
        protected virtual bool IsRollingProportional => false;

        /// <summary>
        /// If IsRollingProportional = false, duration in milliseconds for the counter roll-up animation for each
        /// element; else duration in milliseconds for the counter roll-up animation in total.
        /// </summary>
        protected virtual double RollingDuration => 0;

        /// <summary>
        /// Easing for the counter rollover animation.
        /// </summary>
        protected virtual Easing RollingEasing => Easing.OutQuint;

        private T displayedCount;

        /// <summary>
        /// Value shown at the current moment.
        /// </summary>
        public virtual T DisplayedCount
        {
            get => displayedCount;
            set
            {
                if (EqualityComparer<T>.Default.Equals(displayedCount, value))
                    return;

                displayedCount = value;
                UpdateDisplay();
            }
        }

        /// <summary>
        /// Skeleton of a numeric counter which value rolls over time.
        /// </summary>
        protected RollingCounter()
        {
            AutoSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            displayedCountSpriteText = CreateSpriteText();

            UpdateDisplay();
            Child = displayedCountSpriteText;
        }

        protected void UpdateDisplay()
        {
            if (displayedCountSpriteText != null)
                displayedCountSpriteText.Text = FormatCount(DisplayedCount);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            Current.BindValueChanged(val => TransformCount(DisplayedCount, val.NewValue), true);
        }

        /// <summary>
        /// Sets count value, bypassing rollover animation.
        /// </summary>
        /// <param name="count">New count value.</param>
        public virtual void SetCountWithoutRolling(T count)
        {
            Current.Value = count;
            StopRolling();
        }

        /// <summary>
        /// Stops rollover animation, forcing the displayed count to be the actual count.
        /// </summary>
        public virtual void StopRolling()
        {
            FinishTransforms(false, nameof(DisplayedCount));
            DisplayedCount = Current.Value;
        }

        /// <summary>
        /// Resets count to default value.
        /// </summary>
        public virtual void ResetCount()
        {
            SetCountWithoutRolling(default);
        }

        /// <summary>
        /// Calculates the duration of the roll-up animation by using the difference between the current visible value
        /// and the new final value.
        /// </summary>
        /// <remarks>
        /// To be used in conjunction with IsRollingProportional = true.
        /// Unless a derived class needs to have a proportional rolling, it is not necessary to override this function.
        /// </remarks>
        /// <param name="currentValue">Current visible value.</param>
        /// <param name="newValue">New final value.</param>
        /// <returns>Calculated rollover duration in milliseconds.</returns>
        protected virtual double GetProportionalDuration(T currentValue, T newValue)
        {
            return RollingDuration;
        }

        /// <summary>
        /// Used to format counts.
        /// </summary>
        /// <param name="count">Count to format.</param>
        /// <returns>Count formatted as a string.</returns>
        protected virtual string FormatCount(T count)
        {
            return count.ToString();
        }

        /// <summary>
        /// Called when the count is updated to add a transformer that changes the value of the visible count (i.e.
        /// implement the rollover animation).
        /// </summary>
        /// <param name="currentValue">Count value before modification.</param>
        /// <param name="newValue">Expected count value after modification.</param>
        protected virtual void TransformCount(T currentValue, T newValue)
        {
            double rollingTotalDuration =
                IsRollingProportional
                    ? GetProportionalDuration(currentValue, newValue)
                    : RollingDuration;

            this.TransformTo(nameof(DisplayedCount), newValue, rollingTotalDuration, RollingEasing);
        }

        protected virtual OsuSpriteText CreateSpriteText() => new OsuSpriteText
        {
            Font = OsuFont.Numeric.With(size: 40f),
        };
    }
}


using BurningKnight.assets.lighting;
using BurningKnight.entity.component;
using BurningKnight.level.biome;
using BurningKnight.save;
using BurningKnight.state;
using ImGuiNET;
using Lens.util.file;
using Lens.util.math;
using Microsoft.Xna.Framework;

namespace BurningKnight.level.entities.plant {
	public class Plant : Prop {
		private static string[] variants = {
			"plant_a", "plant_b", "plant_c", "plant_d", "plant_e", "plant_f",
			"plant_i", "plant_j", "plant_k", "plant_l", "plant_m", "plant_n", "plant_o"
		};

		public byte Variant;

		public override void Update(float dt) {
			base.Update(dt);

			if (GraphicsComponent == null) {
				var s = variants[Variant % variants.Length];
				var g = Variant == 255 ? new PlantGraphicsComponent("props", Events.Halloween ? "pumpkin" : "cabbadge")
					: new PlantGraphicsComponent($"{Run.Level.Biome.Id}_biome", $"{s}{(Variant >= variants.Length ? "s" : "")}");

				AddComponent(g);
				g.Flipped = Rnd.Chance();

				Width = g.Sprite.Width;
				Height = g.Sprite.Height;

				var caves = Run.Level.Biome is CaveBiome;

				if (Variant != 255 && (caves || Run.Depth != 0 || (s != "plant_k" && s != "plant_m"))) {
					if (caves) {
						AddComponent(new LightComponent(this, Rnd.Int(16, 32), new Color(0.4f, 0.1f, 0.4f, 1f)));
					} else if (s == "plant_m") {
						AddComponent(new LightComponent(this, 24, new Color(0.4f, 0.4f, 1f, 1f)));
					} else if (s == "plant_k") {
						AddComponent(new LightComponent(this, 24, new Color(1f, 0.4f, 0.4f, 1f)));
					}
				}

				AddComponent(new ShadowComponent());
			}
		}

		public override void Init() {
			base.Init();
			Variant = (byte) Rnd.Int(variants.Length * 2);

			if (Events.Halloween && Rnd.Chance(10)) {
				Variant = 255;
			}
		}

		public override void Load(FileReader stream) {
			base.Load(stream);
			Variant = stream.ReadByte();
		}

		public override void Save(FileWriter stream) {
			base.Save(stream);
			stream.WriteByte(Variant);
		}

		public override void RenderImDebug() {
			base.RenderImDebug();
			var v = (int) Variant;

			if (ImGui.InputInt("Id", ref v)) {
				Variant = (byte) v;
				RemoveComponent<PlantGraphicsComponent>();
			}
		}
	}
}


using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace Core2D.Views.Style
{
    public class TextStyleView : UserControl
    {
        public TextStyleView()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Edit.Blueprints.Components;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
using osuTK.Input;

namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
    public class HoldNotePlacementBlueprint : ManiaPlacementBlueprint<HoldNote>
    {
        private readonly EditBodyPiece bodyPiece;
        private readonly EditNotePiece headPiece;
        private readonly EditNotePiece tailPiece;

        [Resolved]
        private IScrollingInfo scrollingInfo { get; set; }

        public HoldNotePlacementBlueprint()
            : base(new HoldNote())
        {
            RelativeSizeAxes = Axes.Both;

            InternalChildren = new Drawable[]
            {
                bodyPiece = new EditBodyPiece { Origin = Anchor.TopCentre },
                headPiece = new EditNotePiece { Origin = Anchor.Centre },
                tailPiece = new EditNotePiece { Origin = Anchor.Centre }
            };
        }

        protected override void Update()
        {
            base.Update();

            if (Column != null)
            {
                headPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.StartTime)).Y;
                tailPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.EndTime)).Y;

                switch (scrollingInfo.Direction.Value)
                {
                    case ScrollingDirection.Down:
                        headPiece.Y -= headPiece.DrawHeight / 2;
                        tailPiece.Y -= tailPiece.DrawHeight / 2;
                        break;

                    case ScrollingDirection.Up:
                        headPiece.Y += headPiece.DrawHeight / 2;
                        tailPiece.Y += tailPiece.DrawHeight / 2;
                        break;
                }
            }

            var topPosition = new Vector2(headPiece.DrawPosition.X, Math.Min(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));
            var bottomPosition = new Vector2(headPiece.DrawPosition.X, Math.Max(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));

            bodyPiece.Position = topPosition;
            bodyPiece.Width = headPiece.Width;
            bodyPiece.Height = (bottomPosition - topPosition).Y;
        }

        protected override void OnMouseUp(MouseUpEvent e)
        {
            if (e.Button != MouseButton.Left)
                return;

            base.OnMouseUp(e);
            EndPlacement(true);
        }

        private double originalStartTime;

        public override void UpdateTimeAndPosition(SnapResult result)
        {
            base.UpdateTimeAndPosition(result);

            if (PlacementActive)
            {
                if (result.Time is double endTime)
                {
                    HitObject.StartTime = endTime < originalStartTime ? endTime : originalStartTime;
                    HitObject.Duration = Math.Abs(endTime - originalStartTime);
                }
            }
            else
            {
                if (result.Playfield != null)
                {
                    headPiece.Width = tailPiece.Width = result.Playfield.DrawWidth;
                    headPiece.X = tailPiece.X = ToLocalSpace(result.ScreenSpacePosition).X;
                }

                if (result.Time is double startTime)
                    originalStartTime = HitObject.StartTime = startTime;
            }
        }
    }
}


#pragma warning disable CS1591

using System;
using Jellyfin.Data.Entities;
using MediaBrowser.Model.Notifications;

namespace MediaBrowser.Controller.Notifications
{
    public class UserNotification
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public string Url { get; set; }

        public NotificationLevel Level { get; set; }

        public DateTime Date { get; set; }

        public User User { get; set; }
    }
}


// MIT License - Copyright (C) The Mono.Xna Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.

using System;
using System.Collections.Generic;
using MonoGame.Framework.Utilities;

namespace Microsoft.Xna.Framework
{
    ///
    /// A container for services for a <see cref="Game"/>.
    ///
    public class GameServiceContainer : IServiceProvider
    {
        Dictionary<Type, object> services;

        ///
        /// Create an empty <see cref="GameServiceContainer"/>.
        ///
        public GameServiceContainer()
        {
            services = new Dictionary<Type, object>();
        }

        ///
        /// Add a service provider to this container.
        ///
        /// <param name="type">The type of the service.</param>
        /// <param name="provider">The provider of the service.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="type"/> or <paramref name="provider"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="provider"/> cannot be assigned to <paramref name="type"/>.
        /// </exception>
        public void AddService(Type type, object provider)
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (provider == null)
                throw new ArgumentNullException("provider");
            if (!ReflectionHelpers.IsAssignableFrom(type, provider))
                throw new ArgumentException("The provider does not match the specified service type!");

            services.Add(type, provider);
        }

        ///
        /// Get a service provider for the service of the specified type.
        ///
        /// <param name="type">The type of the service.</param>
        /// <returns>
        /// A service provider for the service of the specified type or null if
        /// no suitable service provider is registered in this container.
        /// </returns>
        /// <exception cref="ArgumentNullException">If the specified type is null.</exception>
        public object GetService(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            object service;
            if (services.TryGetValue(type, out service))
                return service;

            return null;
        }

        ///
        /// Remove the service with the specified type. Does nothing no service of the specified type is registered.
        ///
        /// <param name="type">The type of the service to remove.</param>
        /// <exception cref="ArgumentNullException">If the specified type is null.</exception>
        public void RemoveService(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            services.Remove(type);
        }

        ///
        /// Add a service provider to this container.
        ///
        /// <typeparam name="T">The type of the service.</typeparam>
        /// <param name="provider">The provider of the service.</param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="provider"/> is null.
        /// </exception>
        public void AddService<T>(T provider)
        {
            AddService(typeof(T), provider);
        }

        ///
        /// Get a service provider of the specified type.
        ///
        /// <typeparam name="T">The type of the service provider.</typeparam>
        /// <returns>
        /// A service provider of the specified type or null if
        /// no suitable service provider is registered in this container.
        /// </returns>
 	public T GetService<T>() where T : class
        {
            var service = GetService(typeof(T));

            if (service == null)
                return null;

            return (T)service;
        }
    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Api.ModelBinders
{
    /// <summary>
    /// Comma delimited array model binder.
    /// Returns an empty array of specified type if there is no query parameter.
    /// </summary>
    public class CommaDelimitedArrayModelBinder : IModelBinder
    {
        private readonly ILogger<CommaDelimitedArrayModelBinder> _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="CommaDelimitedArrayModelBinder"/> class.
        /// </summary>
        /// <param name="logger">Instance of the <see cref="ILogger{CommaDelimitedArrayModelBinder}"/> interface.</param>
        public CommaDelimitedArrayModelBinder(ILogger<CommaDelimitedArrayModelBinder> logger)
        {
            _logger = logger;
        }

        /// <inheritdoc/>
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
            var converter = TypeDescriptor.GetConverter(elementType);

            if (valueProviderResult.Length > 1)
            {
                var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);
                bindingContext.Result = ModelBindingResult.Success(typedValues);
            }
            else
            {
                var value = valueProviderResult.FirstValue;

                if (value != null)
                {
                    var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    var typedValues = GetParsedResult(splitValues, elementType, converter);
                    bindingContext.Result = ModelBindingResult.Success(typedValues);
                }
                else
                {
                    var emptyResult = Array.CreateInstance(elementType, 0);
                    bindingContext.Result = ModelBindingResult.Success(emptyResult);
                }
            }

            return Task.CompletedTask;
        }

        private Array GetParsedResult(IReadOnlyList<string> values, Type elementType, TypeConverter converter)
        {
            var parsedValues = new object?[values.Count];
            var convertedCount = 0;
            for (var i = 0; i < values.Count; i++)
            {
                try
                {
                    parsedValues[i] = converter.ConvertFromString(values[i].Trim());
                    convertedCount++;
                }
                catch (FormatException e)
                {
                    _logger.LogDebug(e, "Error converting value.");
                }
            }

            var typedValues = Array.CreateInstance(elementType, convertedCount);
            var typedValueIndex = 0;
            for (var i = 0; i < parsedValues.Length; i++)
            {
                if (parsedValues[i] != null)
                {
                    typedValues.SetValue(parsedValues[i], typedValueIndex);
                    typedValueIndex++;
                }
            }

            return typedValues;
        }
    }
}


#pragma warning disable CS1591

using System;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Sorting;
using MediaBrowser.Model.Querying;

namespace Emby.Server.Implementations.Sorting
{
    public class SeriesSortNameComparer : IBaseItemComparer
    {
        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name => ItemSortBy.SeriesSortName;

        /// <summary>
        /// Compares the specified x.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns>System.Int32.</returns>
        public int Compare(BaseItem x, BaseItem y)
        {
            return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);
        }

        private static string GetValue(BaseItem item)
        {
            var hasSeries = item as IHasSeries;

            return hasSeries?.FindSeriesSortName();
        }
    }
}


using System.Collections.Generic;
using Lens.entity;

namespace BurningKnight.entity {
	public class RenderTriggerManager {
		private Entity entity;
		private List<RenderTrigger> triggers = new List<RenderTrigger>();

		public RenderTriggerManager(Entity e) {
			entity = e;
		}

		public void Add(RenderTrigger trigger) {
			entity.Area.Add(trigger);
			triggers.Add(trigger);
		}

		public void Update() {
			if (entity.Done) {
				Destroy();
				return;
			}

			foreach (var t in triggers) {
				if (t.Done || t.Area != entity.Area) {
					t.Done = false;
					t.Area = null;
					t.Components = null;
					entity.Area.Add(t);
				}
			}
		}

		public void Destroy() {
			foreach (var t in triggers) {
				t.Done = true;
				entity.Area.Remove(t);
			}
		}
	}
}


using BurningKnight.assets.particle.custom;
using BurningKnight.entity.component;

namespace BurningKnight.debug {
	public class GodModeCommand : ConsoleCommand {
		public GodModeCommand() {
			_Init();
		}

		protected void _Init() {
			{
				Name = "gm";
				ShortName = "g";
			}
		}

		public override void Run(Console Console, string[] Args) {
			var all = Console.GameArea.Tagged[Tags.Player];

			foreach (var player in all) {
				var health = player.GetComponent<HealthComponent>();
				health.Unhittable = !health.Unhittable;

				TextParticle.Add(player, "God Mode", 1, true, !health.Unhittable);
				Console.Print(health.Unhittable ? "God mode is on" : "God mode is off");
			}
		}
	}
}


using System;
using System.Threading;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
using MediaBrowser.Model.SyncPlay;
using Microsoft.Extensions.Logging;

namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
    /// <summary>
    /// Class PlayingGroupState.
    /// </summary>
    /// <remarks>
    /// Class is not thread-safe, external locking is required when accessing methods.
    /// </remarks>
    public class PlayingGroupState : AbstractGroupState
    {
        /// <summary>
        /// The logger.
        /// </summary>
        private readonly ILogger<PlayingGroupState> _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="PlayingGroupState"/> class.
        /// </summary>
        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
        public PlayingGroupState(ILoggerFactory loggerFactory)
            : base(loggerFactory)
        {
            _logger = LoggerFactory.CreateLogger<PlayingGroupState>();
        }

        /// <inheritdoc />
        public override GroupStateType Type { get; } = GroupStateType.Playing;

        /// <summary>
        /// Gets or sets a value indicating whether requests for buffering should be ignored.
        /// </summary>
        public bool IgnoreBuffering { get; set; }

        /// <inheritdoc />
        public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Wait for session to be ready.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.SessionJoined(context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Do nothing.
        }

        /// <inheritdoc />
        public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            if (!prevState.Equals(Type))
            {
                // Pick a suitable time that accounts for latency.
                var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing);

                // Unpause group and set starting point in future.
                // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position).
                // The added delay does not guarantee, of course, that the command will be received in time.
                // Playback synchronization will mainly happen client side.
                context.LastActivity = DateTime.UtcNow.AddMilliseconds(delayMillis);

                var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
                context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);

                // Notify relevant state change event.
                SendGroupStateUpdate(context, request, session, cancellationToken);
            }
            else
            {
                // Client got lost, sending current state.
                var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
                context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
            }
        }

        /// <inheritdoc />
        public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var pausedState = new PausedGroupState(LoggerFactory);
            context.SetState(pausedState);
            pausedState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var idleState = new IdleGroupState(LoggerFactory);
            context.SetState(idleState);
            idleState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            if (IgnoreBuffering)
            {
                return;
            }

            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            if (prevState.Equals(Type))
            {
                // Group was not waiting, make sure client has latest state.
                var command = context.NewSyncPlayCommand(SendCommandType.Unpause);
                context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
            }
            else if (prevState.Equals(GroupStateType.Waiting))
            {
                // Notify relevant state change event.
                SendGroupStateUpdate(context, request, session, cancellationToken);
            }
        }

        /// <inheritdoc />
        public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }
    }
}


using System.Collections.Immutable;
using System.Runtime.Serialization;
using Core2D.Bindings;
using Core2D.Containers;
using Core2D.Shapes;

namespace Core2D.Data
{
    [DataContract(IsReference = true)]
    public class DataFlow
    {
        public void Bind(ProjectContainer project)
        {
            foreach (var document in project.Documents)
            {
                Bind(document);
            }
        }

        public void Bind(DocumentContainer document)
        {
            foreach (var container in document.Pages)
            {
                var db = container.Properties;
                var r = container.Record;

                Bind(container.Template, db, r);
                Bind(container, db, r);
            }
        }

        public void Bind(PageContainer container, object db, object r)
        {
            foreach (var layer in container.Layers)
            {
                Bind(layer, db, r);
            }
        }

        public void Bind(LayerContainer layer, object db, object r)
        {
            foreach (var shape in layer.Shapes)
            {
                shape.Bind(this, db, r);
            }
        }

        public void Bind(LineShape line, object db, object r)
        {
        }

        public void Bind(RectangleShape rectangle, object db, object r)
        {
        }

        public void Bind(EllipseShape ellipse, object db, object r)
        {
        }

        public void Bind(ArcShape arc, object db, object r)
        {
        }

        public void Bind(CubicBezierShape cubicBezier, object db, object r)
        {
        }

        public void Bind(QuadraticBezierShape quadraticBezier, object db, object r)
        {
        }

        public void Bind(TextShape text, object db, object r)
        {
            var properties = (ImmutableArray<Property>)db;
            var record = (Record)r;
            var tbind = TextBinding.Bind(text, properties, record);
            text.SetProperty(nameof(TextShape.Text), tbind);
        }

        public void Bind(ImageShape image, object db, object r)
        {
        }

        public void Bind(PathShape path, object db, object r)
        {
        }
    }
}


using System;
using System.IO;
using Core2D;
using Core2D.Containers;
using Core2D.Data;
using Core2D.Renderer;
using Core2D.Renderer.Presenters;
using Core2D.Renderer.SkiaSharp;

namespace Core2D.FileWriter.SkiaSharpWebp
{
    public sealed class WebpSkiaSharpWriter : IFileWriter
    {
        private readonly IServiceProvider _serviceProvider;

        public WebpSkiaSharpWriter(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public string Name { get; } = "Webp (SkiaSharp)";

        public string Extension { get; } = "webp";

        public void Save(Stream stream, object item, object options)
        {
            if (item == null)
            {
                return;
            }

            var ic = options as IImageCache;
            if (options == null)
            {
                return;
            }

            var renderer = new SkiaSharpRenderer(_serviceProvider);
            renderer.State.DrawShapeState.Flags = ShapeStateFlags.Printable;
            renderer.State.ImageCache = ic;

            var presenter = new ExportPresenter();

            IProjectExporter exporter = new WebpSkiaSharpExporter(renderer, presenter);

            if (item is PageContainer page)
            {
                var dataFlow = _serviceProvider.GetService<DataFlow>();
                var db = (object)page.Properties;
                var record = (object)page.Record;

                dataFlow.Bind(page.Template, db, record);
                dataFlow.Bind(page, db, record);

                exporter.Save(stream, page);
            }
            else if (item is DocumentContainer document)
            {
                throw new NotSupportedException("Saving documents as webp drawing is not supported.");
            }
            else if (item is ProjectContainer project)
            {
                throw new NotSupportedException("Saving projects as webp drawing is not supported.");
            }
        }
    }
}


#nullable disable
#pragma warning disable CS1591

using System;
using MediaBrowser.Model.Dto;

namespace MediaBrowser.Model.Dlna
{
    /// <summary>
    /// Class AudioOptions.
    /// </summary>
    public class AudioOptions
    {
        public AudioOptions()
        {
            Context = EncodingContext.Streaming;

            EnableDirectPlay = true;
            EnableDirectStream = true;
        }

        public bool EnableDirectPlay { get; set; }

        public bool EnableDirectStream { get; set; }

        public bool ForceDirectPlay { get; set; }

        public bool ForceDirectStream { get; set; }

        public Guid ItemId { get; set; }

        public MediaSourceInfo[] MediaSources { get; set; }

        public DeviceProfile Profile { get; set; }

        /// <summary>
        /// Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested.
        /// </summary>
        public string MediaSourceId { get; set; }

        public string DeviceId { get; set; }

        /// <summary>
        /// Allows an override of supported number of audio channels
        /// Example: DeviceProfile supports five channel, but user only has stereo speakers
        /// </summary>
        public int? MaxAudioChannels { get; set; }

        /// <summary>
        /// The application's configured quality setting.
        /// </summary>
        public int? MaxBitrate { get; set; }

        /// <summary>
        /// Gets or sets the context.
        /// </summary>
        /// <value>The context.</value>
        public EncodingContext Context { get; set; }

        /// <summary>
        /// Gets or sets the audio transcoding bitrate.
        /// </summary>
        /// <value>The audio transcoding bitrate.</value>
        public int? AudioTranscodingBitrate { get; set; }

        /// <summary>
        /// Gets the maximum bitrate.
        /// </summary>
        /// <returns>System.Nullable<System.Int32>.</returns>
        public int? GetMaxBitrate(bool isAudio)
        {
            if (MaxBitrate.HasValue)
            {
                return MaxBitrate;
            }

            if (Profile == null)
            {
                return null;
            }

            if (Context == EncodingContext.Static)
            {
                if (isAudio && Profile.MaxStaticMusicBitrate.HasValue)
                {
                    return Profile.MaxStaticMusicBitrate;
                }

                return Profile.MaxStaticBitrate;
            }

            return Profile.MaxStreamingBitrate;
        }
    }
}


using System.Threading;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
using MediaBrowser.Model.SyncPlay;
using Microsoft.Extensions.Logging;

namespace MediaBrowser.Controller.SyncPlay.GroupStates
{
    /// <summary>
    /// Class IdleGroupState.
    /// </summary>
    /// <remarks>
    /// Class is not thread-safe, external locking is required when accessing methods.
    /// </remarks>
    public class IdleGroupState : AbstractGroupState
    {
        /// <summary>
        /// The logger.
        /// </summary>
        private readonly ILogger<IdleGroupState> _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="IdleGroupState"/> class.
        /// </summary>
        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
        public IdleGroupState(ILoggerFactory loggerFactory)
            : base(loggerFactory)
        {
            _logger = LoggerFactory.CreateLogger<IdleGroupState>();
        }

        /// <inheritdoc />
        public override GroupStateType Type { get; } = GroupStateType.Idle;

        /// <inheritdoc />
        public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Do nothing.
        }

        /// <inheritdoc />
        public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, prevState, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, prevState, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, prevState, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, prevState, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            SendStopCommand(context, prevState, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        /// <inheritdoc />
        public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            // Change state.
            var waitingState = new WaitingGroupState(LoggerFactory);
            context.SetState(waitingState);
            waitingState.HandleRequest(request, context, Type, session, cancellationToken);
        }

        private void SendStopCommand(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)
        {
            var command = context.NewSyncPlayCommand(SendCommandType.Stop);
            if (!prevState.Equals(Type))
            {
                context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);
            }
            else
            {
                context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);
            }
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Online.API.Requests.Responses;

namespace osu.Game.Overlays.Changelog
{
    public class ChangelogHeader : BreadcrumbControlOverlayHeader
    {
        public readonly Bindable<APIChangelogBuild> Build = new Bindable<APIChangelogBuild>();

        public Action ListingSelected;

        public ChangelogUpdateStreamControl Streams;

        private const string listing_string = "listing";

        private Box streamsBackground;

        public ChangelogHeader()
        {
            TabControl.AddItem(listing_string);
            Current.ValueChanged += e =>
            {
                if (e.NewValue == listing_string)
                    ListingSelected?.Invoke();
            };

            Build.ValueChanged += showBuild;

            Streams.Current.ValueChanged += e =>
            {
                if (e.NewValue?.LatestBuild != null && !e.NewValue.Equals(Build.Value?.UpdateStream))
                    Build.Value = e.NewValue.LatestBuild;
            };
        }

        [BackgroundDependencyLoader]
        private void load(OverlayColourProvider colourProvider)
        {
            streamsBackground.Colour = colourProvider.Background5;
        }

        private void showBuild(ValueChangedEvent<APIChangelogBuild> e)
        {
            if (e.OldValue != null)
                TabControl.RemoveItem(e.OldValue.ToString());

            if (e.NewValue != null)
            {
                TabControl.AddItem(e.NewValue.ToString());
                Current.Value = e.NewValue.ToString();

                updateCurrentStream();
            }
            else
            {
                Current.Value = listing_string;
                Streams.Current.Value = null;
            }
        }

        protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/changelog");

        protected override Drawable CreateContent() => new Container
        {
            RelativeSizeAxes = Axes.X,
            AutoSizeAxes = Axes.Y,
            Children = new Drawable[]
            {
                streamsBackground = new Box
                {
                    RelativeSizeAxes = Axes.Both
                },
                new Container
                {
                    RelativeSizeAxes = Axes.X,
                    AutoSizeAxes = Axes.Y,
                    Padding = new MarginPadding
                    {
                        Horizontal = 65,
                        Vertical = 20
                    },
                    Child = Streams = new ChangelogUpdateStreamControl()
                }
            }
        };

        protected override OverlayTitle CreateTitle() => new ChangelogHeaderTitle();

        public void Populate(List<APIUpdateStream> streams)
        {
            Streams.Populate(streams);
            updateCurrentStream();
        }

        private void updateCurrentStream()
        {
            if (Build.Value == null)
                return;

            Streams.Current.Value = Streams.Items.FirstOrDefault(s => s.Name == Build.Value.UpdateStream.Name);
        }

        private class ChangelogHeaderTitle : OverlayTitle
        {
            public ChangelogHeaderTitle()
            {
                Title = "changelog";
                Description = "track recent dev updates in the osu! ecosystem";
                IconTexture = "Icons/Hexacons/devtools";
            }
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics;
using osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations;
using osuTK.Graphics;

namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
    public class GroupVisualisation : PointVisualisation
    {
        public readonly ControlPointGroup Group;

        private readonly IBindableList<ControlPoint> controlPoints = new BindableList<ControlPoint>();

        [Resolved]
        private OsuColour colours { get; set; }

        public GroupVisualisation(ControlPointGroup group)
            : base(group.Time)
        {
            Group = group;
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            controlPoints.BindTo(Group.ControlPoints);
            controlPoints.BindCollectionChanged((_, __) =>
            {
                if (controlPoints.Count == 0)
                {
                    Colour = Color4.Transparent;
                    return;
                }

                Colour = controlPoints.Any(c => c is TimingControlPoint) ? colours.YellowDark : colours.Green;
            }, true);
        }
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Primitives;
using OpenRA.Traits;

namespace OpenRA.Mods.Common.Traits
{
	[Desc("Spawn base actor at the spawnpoint and support units in an annulus around the base actor. Both are defined at MPStartUnits. Attach this to the world actor.")]
	public class SpawnMPUnitsInfo : TraitInfo, Requires<MPStartUnitsInfo>, ILobbyOptions
	{
		public readonly string StartingUnitsClass = "none";

		[Translate]
		[Desc("Descriptive label for the starting units option in the lobby.")]
		public readonly string DropdownLabel = "Starting Units";

		[Translate]
		[Desc("Tooltip description for the starting units option in the lobby.")]
		public readonly string DropdownDescription = "Change the units that you start the game with";

		[Desc("Prevent the starting units option from being changed in the lobby.")]
		public readonly bool DropdownLocked = false;

		[Desc("Whether to display the starting units option in the lobby.")]
		public readonly bool DropdownVisible = true;

		[Desc("Display order for the starting units option in the lobby.")]
		public readonly int DropdownDisplayOrder = 0;

		IEnumerable<LobbyOption> ILobbyOptions.LobbyOptions(Ruleset rules)
		{
			var startingUnits = new Dictionary<string, string>();

			// Duplicate classes are defined for different race variants
			foreach (var t in rules.Actors["world"].TraitInfos<MPStartUnitsInfo>())
				startingUnits[t.Class] = t.ClassName;

			if (startingUnits.Any())
				yield return new LobbyOption("startingunits", DropdownLabel, DropdownDescription, DropdownVisible, DropdownDisplayOrder,
					new ReadOnlyDictionary<string, string>(startingUnits), StartingUnitsClass, DropdownLocked);
		}

		public override object Create(ActorInitializer init) { return new SpawnMPUnits(this); }
	}

	public class SpawnMPUnits : IWorldLoaded
	{
		readonly SpawnMPUnitsInfo info;

		public SpawnMPUnits(SpawnMPUnitsInfo info)
		{
			this.info = info;
		}

		public void WorldLoaded(World world, WorldRenderer wr)
		{
			foreach (var p in world.Players)
				if (p.Playable)
					SpawnUnitsForPlayer(world, p);
		}

		void SpawnUnitsForPlayer(World w, Player p)
		{
			var spawnClass = p.PlayerReference.StartingUnitsClass ?? w.LobbyInfo.GlobalSettings
				.OptionOrDefault("startingunits", info.StartingUnitsClass);

			var unitGroup = w.Map.Rules.Actors["world"].TraitInfos<MPStartUnitsInfo>()
				.Where(g => g.Class == spawnClass && g.Factions != null && g.Factions.Contains(p.Faction.InternalName))
				.RandomOrDefault(w.SharedRandom);

			if (unitGroup == null)
				throw new InvalidOperationException("No starting units defined for faction {0} with class {1}".F(p.Faction.InternalName, spawnClass));

			if (unitGroup.BaseActor != null)
			{
				var facing = unitGroup.BaseActorFacing.HasValue ? unitGroup.BaseActorFacing.Value : new WAngle(w.SharedRandom.Next(1024));
				w.CreateActor(unitGroup.BaseActor.ToLowerInvariant(), new TypeDictionary
				{
					new LocationInit(p.HomeLocation + unitGroup.BaseActorOffset),
					new OwnerInit(p),
					new SkipMakeAnimsInit(),
					new FacingInit(facing),
				});
			}

			if (!unitGroup.SupportActors.Any())
				return;

			var supportSpawnCells = w.Map.FindTilesInAnnulus(p.HomeLocation, unitGroup.InnerSupportRadius + 1, unitGroup.OuterSupportRadius);

			foreach (var s in unitGroup.SupportActors)
			{
				var actorRules = w.Map.Rules.Actors[s.ToLowerInvariant()];
				var ip = actorRules.TraitInfo<IPositionableInfo>();
				var validCell = supportSpawnCells.Shuffle(w.SharedRandom).FirstOrDefault(c => ip.CanEnterCell(w, null, c));

				if (validCell == CPos.Zero)
				{
					Log.Write("debug", "No cells available to spawn starting unit {0} for player {1}".F(s, p));
					continue;
				}

				var subCell = ip.SharesCell ? w.ActorMap.FreeSubCell(validCell) : 0;
				var facing = unitGroup.SupportActorsFacing.HasValue ? unitGroup.SupportActorsFacing.Value : new WAngle(w.SharedRandom.Next(1024));

				w.CreateActor(s.ToLowerInvariant(), new TypeDictionary
				{
					new OwnerInit(p),
					new LocationInit(validCell),
					new SubCellInit(subCell),
					new FacingInit(facing),
				});
			}
		}
	}
}


using MediaBrowser.Model.Entities;

namespace Emby.Naming.Video
{
    /// <summary>
    /// Represents a single video file.
    /// </summary>
    public class VideoFileInfo
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="VideoFileInfo"/> class.
        /// </summary>
        /// <param name="name">Name of file.</param>
        /// <param name="path">Path to the file.</param>
        /// <param name="container">Container type.</param>
        /// <param name="year">Year of release.</param>
        /// <param name="extraType">Extra type.</param>
        /// <param name="extraRule">Extra rule.</param>
        /// <param name="format3D">Format 3D.</param>
        /// <param name="is3D">Is 3D.</param>
        /// <param name="isStub">Is Stub.</param>
        /// <param name="stubType">Stub type.</param>
        /// <param name="isDirectory">Is directory.</param>
        public VideoFileInfo(string name, string path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default)
        {
            Path = path;
            Container = container;
            Name = name;
            Year = year;
            ExtraType = extraType;
            ExtraRule = extraRule;
            Format3D = format3D;
            Is3D = is3D;
            IsStub = isStub;
            StubType = stubType;
            IsDirectory = isDirectory;
        }

        /// <summary>
        /// Gets or sets the path.
        /// </summary>
        /// <value>The path.</value>
        public string Path { get; set; }

        /// <summary>
        /// Gets or sets the container.
        /// </summary>
        /// <value>The container.</value>
        public string? Container { get; set; }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the year.
        /// </summary>
        /// <value>The year.</value>
        public int? Year { get; set; }

        /// <summary>
        /// Gets or sets the type of the extra, e.g. trailer, theme song, behind the scenes, etc.
        /// </summary>
        /// <value>The type of the extra.</value>
        public ExtraType? ExtraType { get; set; }

        /// <summary>
        /// Gets or sets the extra rule.
        /// </summary>
        /// <value>The extra rule.</value>
        public ExtraRule? ExtraRule { get; set; }

        /// <summary>
        /// Gets or sets the format3 d.
        /// </summary>
        /// <value>The format3 d.</value>
        public string? Format3D { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether [is3 d].
        /// </summary>
        /// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
        public bool Is3D { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is stub.
        /// </summary>
        /// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
        public bool IsStub { get; set; }

        /// <summary>
        /// Gets or sets the type of the stub.
        /// </summary>
        /// <value>The type of the stub.</value>
        public string? StubType { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is a directory.
        /// </summary>
        /// <value>The type.</value>
        public bool IsDirectory { get; set; }

        /// <summary>
        /// Gets the file name without extension.
        /// </summary>
        /// <value>The file name without extension.</value>
        public string FileNameWithoutExtension => !IsDirectory
            ? System.IO.Path.GetFileNameWithoutExtension(Path)
            : System.IO.Path.GetFileName(Path);

        /// <inheritdoc />
        public override string ToString()
        {
            return "VideoFileInfo(Name: '" + Name + "')";
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects.Drawables;
using osu.Game.Rulesets.Catch.Replays;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osuTK;

namespace osu.Game.Rulesets.Catch.UI
{
    public class CatcherArea : Container
    {
        public const float CATCHER_SIZE = 106.75f;

        public readonly Catcher MovableCatcher;
        private readonly CatchComboDisplay comboDisplay;

        public CatcherArea(Container<CaughtObject> droppedObjectContainer, BeatmapDifficulty difficulty = null)
        {
            Size = new Vector2(CatchPlayfield.WIDTH, CATCHER_SIZE);
            Children = new Drawable[]
            {
                comboDisplay = new CatchComboDisplay
                {
                    RelativeSizeAxes = Axes.None,
                    AutoSizeAxes = Axes.Both,
                    Anchor = Anchor.TopLeft,
                    Origin = Anchor.Centre,
                    Margin = new MarginPadding { Bottom = 350f },
                    X = CatchPlayfield.CENTER_X
                },
                MovableCatcher = new Catcher(this, droppedObjectContainer, difficulty) { X = CatchPlayfield.CENTER_X },
            };
        }

        public void OnNewResult(DrawableCatchHitObject hitObject, JudgementResult result)
        {
            MovableCatcher.OnNewResult(hitObject, result);

            if (!result.Type.IsScorable())
                return;

            if (hitObject.HitObject.LastInCombo)
            {
                if (result.Judgement is CatchJudgement catchJudgement && catchJudgement.ShouldExplodeFor(result))
                    MovableCatcher.Explode();
                else
                    MovableCatcher.Drop();
            }

            comboDisplay.OnNewResult(hitObject, result);
        }

        public void OnRevertResult(DrawableCatchHitObject hitObject, JudgementResult result)
        {
            comboDisplay.OnRevertResult(hitObject, result);
            MovableCatcher.OnRevertResult(hitObject, result);
        }

        protected override void UpdateAfterChildren()
        {
            base.UpdateAfterChildren();

            var state = (GetContainingInputManager().CurrentState as RulesetInputManagerInputState<CatchAction>)?.LastReplayState as CatchFramedReplayInputHandler.CatchReplayState;

            if (state?.CatcherX != null)
                MovableCatcher.X = state.CatcherX.Value;

            comboDisplay.X = MovableCatcher.X;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.Serialization;
using Core2D.Shapes;

namespace Core2D.Containers
{
    public class InvalidateLayerEventArgs : EventArgs { }

    public delegate void InvalidateLayerEventHandler(object sender, InvalidateLayerEventArgs e);

    [DataContract(IsReference = true)]
    public class LayerContainer : BaseContainer
    {
        public event InvalidateLayerEventHandler InvalidateLayerHandler;

        private bool _isVisible = true;
        private ImmutableArray<BaseShape> _shapes;

        [DataMember(IsRequired = false, EmitDefaultValue = true)]
        public bool IsVisible
        {
            get => _isVisible;
            set
            {
                RaiseAndSetIfChanged(ref _isVisible, value);
                InvalidateLayer();
            }
        }

        [DataMember(IsRequired = false, EmitDefaultValue = true)]
        public ImmutableArray<BaseShape> Shapes
        {
            get => _shapes;
            set => RaiseAndSetIfChanged(ref _shapes, value);
        }

        public void InvalidateLayer() => InvalidateLayerHandler?.Invoke(this, new InvalidateLayerEventArgs());

        public override object Copy(IDictionary<object, object> shared)
        {
            throw new NotImplementedException();
        }

        public override bool IsDirty()
        {
            var isDirty = base.IsDirty();

            foreach (var shape in Shapes)
            {
                isDirty |= shape.IsDirty();
            }

            return isDirty;
        }

        public override void Invalidate()
        {
            base.Invalidate();

            foreach (var shape in Shapes)
            {
                shape.Invalidate();
            }
        }
    }
}


// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.

using System;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Graphics;

namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics
{
    internal class DefaultTextureProfile : TextureProfile
    {
        public override bool Supports(TargetPlatform platform)
        {
            return  platform == TargetPlatform.Android ||
                    platform == TargetPlatform.DesktopGL ||
                    platform == TargetPlatform.MacOSX ||
                    platform == TargetPlatform.NativeClient ||
                    platform == TargetPlatform.RaspberryPi ||
                    platform == TargetPlatform.Windows ||
                    platform == TargetPlatform.WindowsPhone8 ||
                    platform == TargetPlatform.WindowsStoreApp ||
                    platform == TargetPlatform.iOS ||
                    platform == TargetPlatform.Web;
        }

        private static bool IsCompressedTextureFormat(TextureProcessorOutputFormat format)
        {
            switch (format)
            {
                case TextureProcessorOutputFormat.AtcCompressed:
                case TextureProcessorOutputFormat.DxtCompressed:
                case TextureProcessorOutputFormat.Etc1Compressed:
                case TextureProcessorOutputFormat.PvrCompressed:
                    return true;
            }
            return false;
        }

        private static TextureProcessorOutputFormat GetTextureFormatForPlatform(TextureProcessorOutputFormat format, TargetPlatform platform)
        {
            // Select the default texture compression format for the target platform
            if (format == TextureProcessorOutputFormat.Compressed)
            {
                if (platform == TargetPlatform.iOS)
                    format = TextureProcessorOutputFormat.PvrCompressed;
                else if (platform == TargetPlatform.Android)
                    format = TextureProcessorOutputFormat.Etc1Compressed;
                else
                    format = TextureProcessorOutputFormat.DxtCompressed;
            }

            if (IsCompressedTextureFormat(format))
            {
                // Make sure the target platform supports the selected texture compression format
                if (platform == TargetPlatform.iOS)
                {
                    if (format != TextureProcessorOutputFormat.PvrCompressed)
                        throw new PlatformNotSupportedException("iOS platform only supports PVR texture compression");
                }
                else if (platform == TargetPlatform.Windows ||
                            platform == TargetPlatform.WindowsPhone8 ||
                            platform == TargetPlatform.WindowsStoreApp ||
                            platform == TargetPlatform.DesktopGL ||
                            platform == TargetPlatform.MacOSX ||
                            platform == TargetPlatform.NativeClient ||
                            platform == TargetPlatform.Web)
                {
                    if (format != TextureProcessorOutputFormat.DxtCompressed)
                        throw new PlatformNotSupportedException(format + " platform only supports DXT texture compression");
                }
            }

            return format;
        }

        public override void Requirements(ContentProcessorContext context, TextureProcessorOutputFormat format, out bool requiresPowerOfTwo, out bool requiresSquare)
        {
            if (format == TextureProcessorOutputFormat.Compressed)
                format = GetTextureFormatForPlatform(format, context.TargetPlatform);

            // Does it require POT textures?
            switch (format)
            {
                default:
                    requiresPowerOfTwo = false;
                    break;

                case TextureProcessorOutputFormat.DxtCompressed:
                    requiresPowerOfTwo = context.TargetProfile == GraphicsProfile.Reach;
                    break;

                case TextureProcessorOutputFormat.PvrCompressed:
                case TextureProcessorOutputFormat.Etc1Compressed:
                    requiresPowerOfTwo = true;
                    break;
            }

            // Does it require square textures?
            switch (format)
            {
                default:
                    requiresSquare = false;
                    break;

                case TextureProcessorOutputFormat.PvrCompressed:
                    requiresSquare = true;
                    break;
            }
        }

        protected override void PlatformCompressTexture(ContentProcessorContext context, TextureContent content, TextureProcessorOutputFormat format, bool isSpriteFont)
        {
            format = GetTextureFormatForPlatform(format, context.TargetPlatform);

            // Make sure we're in a floating point format
            content.ConvertBitmapType(typeof(PixelBitmapContent<Vector4>));

            switch (format)
            {
                case TextureProcessorOutputFormat.AtcCompressed:
                    GraphicsUtil.CompressAti(context, content, isSpriteFont);
                    break;

                case TextureProcessorOutputFormat.Color16Bit:
                    GraphicsUtil.CompressColor16Bit(context, content);
                    break;

                case TextureProcessorOutputFormat.DxtCompressed:
                    GraphicsUtil.CompressDxt(context, content, isSpriteFont);
                    break;

                case TextureProcessorOutputFormat.Etc1Compressed:
                    GraphicsUtil.CompressEtc1(context, content, isSpriteFont);
                    break;

                case TextureProcessorOutputFormat.PvrCompressed:
                    GraphicsUtil.CompressPvrtc(context, content, isSpriteFont);
                    break;
            }
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;

namespace osu.Game.Screens.Play
{
    public class ComboEffects : CompositeDrawable
    {
        private readonly ScoreProcessor processor;

        private SkinnableSound comboBreakSample;

        private Bindable<bool> alwaysPlayFirst;

        private double? firstBreakTime;

        public ComboEffects(ScoreProcessor processor)
        {
            this.processor = processor;
        }

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("Gameplay/combobreak"));
            alwaysPlayFirst = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();
            processor.Combo.BindValueChanged(onComboChange);
        }

        [Resolved(canBeNull: true)]
        private ISamplePlaybackDisabler samplePlaybackDisabler { get; set; }

        [Resolved]
        private GameplayClock gameplayClock { get; set; }

        private void onComboChange(ValueChangedEvent<int> combo)
        {
            // handle the case of rewinding before the first combo break time.
            if (gameplayClock.CurrentTime < firstBreakTime)
                firstBreakTime = null;

            if (gameplayClock.ElapsedFrameTime < 0)
                return;

            if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlayFirst.Value && firstBreakTime == null)))
            {
                firstBreakTime = gameplayClock.CurrentTime;

                // combo break isn't a pausable sound itself as we want to let it play out.
                // we still need to disable during seeks, though.
                if (samplePlaybackDisabler?.SamplePlaybackDisabled.Value == true)
                    return;

                comboBreakSample?.Play();
            }
        }
    }
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Input;
using osu.Game.Configuration;

namespace osu.Game.Input
{
    /// <summary>
    /// Connects <see cref="OsuSetting.ConfineMouseMode"/> with <see cref="FrameworkSetting.ConfineMouseMode"/>.
    /// If <see cref="OsuGame.LocalUserPlaying"/> is true, we should also confine the mouse cursor if it has been
    /// requested with <see cref="OsuConfineMouseMode.DuringGameplay"/>.
    /// </summary>
    public class ConfineMouseTracker : Component
    {
        private Bindable<ConfineMouseMode> frameworkConfineMode;
        private Bindable<WindowMode> frameworkWindowMode;

        private Bindable<OsuConfineMouseMode> osuConfineMode;
        private IBindable<bool> localUserPlaying;

        [BackgroundDependencyLoader]
        private void load(OsuGame game, FrameworkConfigManager frameworkConfigManager, OsuConfigManager osuConfigManager)
        {
            frameworkConfineMode = frameworkConfigManager.GetBindable<ConfineMouseMode>(FrameworkSetting.ConfineMouseMode);
            frameworkWindowMode = frameworkConfigManager.GetBindable<WindowMode>(FrameworkSetting.WindowMode);
            frameworkWindowMode.BindValueChanged(_ => updateConfineMode());

            osuConfineMode = osuConfigManager.GetBindable<OsuConfineMouseMode>(OsuSetting.ConfineMouseMode);
            localUserPlaying = game.LocalUserPlaying.GetBoundCopy();

            osuConfineMode.ValueChanged += _ => updateConfineMode();
            localUserPlaying.BindValueChanged(_ => updateConfineMode(), true);
        }

        private void updateConfineMode()
        {
            // confine mode is unavailable on some platforms
            if (frameworkConfineMode.Disabled)
                return;

            if (frameworkWindowMode.Value == WindowMode.Fullscreen)
            {
                frameworkConfineMode.Value = ConfineMouseMode.Fullscreen;
                return;
            }

            switch (osuConfineMode.Value)
            {
                case OsuConfineMouseMode.Never:
                    frameworkConfineMode.Value = ConfineMouseMode.Never;
                    break;

                case OsuConfineMouseMode.DuringGameplay:
                    frameworkConfineMode.Value = localUserPlaying.Value ? ConfineMouseMode.Always : ConfineMouseMode.Never;
                    break;

                case OsuConfineMouseMode.Always:
                    frameworkConfineMode.Value = ConfineMouseMode.Always;
                    break;
            }
        }
    }
}


// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.

using System.Runtime.InteropServices;
using System;

namespace MonoGame.Framework.Utilities
{
    internal enum OS
    {
        Windows,
        Linux,
        MacOSX,
        Unknown
    }

    internal static class CurrentPlatform
    {
        private static bool _init = false;
        private static OS _os;

        [DllImport("libc")]
        static extern int uname(IntPtr buf);

        private static void Init()
        {
            if (_init)
                return;

            var pid = Environment.OSVersion.Platform;

            switch (pid)
            {
                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                    _os = OS.Windows;
                    break;
                case PlatformID.MacOSX:
                    _os = OS.MacOSX;
                    break;
                case PlatformID.Unix:
                    _os = OS.MacOSX;

                    var buf = IntPtr.Zero;

                    try
                    {
                        buf = Marshal.AllocHGlobal(8192);

                        if (uname(buf) == 0 && Marshal.PtrToStringAnsi(buf) == "Linux")
                            _os = OS.Linux;
                    }
                    catch
                    {
                    }
                    finally
                    {
                        if (buf != IntPtr.Zero)
                            Marshal.FreeHGlobal(buf);
                    }

                    break;
                default:
                    _os = OS.Unknown;
                    break;
            }

            _init = true;
        }

        public static OS OS
        {
            get
            {
                Init();
                return _os;
            }
        }

        public static string Rid
        {
            get
            {
                if (CurrentPlatform.OS == OS.Windows && Environment.Is64BitProcess)
                    return "win-x64";
                else if (CurrentPlatform.OS == OS.Windows && !Environment.Is64BitProcess)
                    return "win-x86";
                else if (CurrentPlatform.OS == OS.Linux)
                    return "linux-x64";
                else if (CurrentPlatform.OS == OS.MacOSX)
                    return "osx";
                else
                    return "unknown";
            }
        }
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.IO;
using OpenRA.FileFormats;
using OpenRA.Primitives;

namespace OpenRA.Graphics
{
	public sealed class Sheet : IDisposable
	{
		bool dirty;
		bool releaseBufferOnCommit;
		ITexture texture;
		byte[] data;

		public readonly Size Size;
		public readonly SheetType Type;

		public byte[] GetData()
		{
			CreateBuffer();
			return data;
		}

		public bool Buffered { get { return data != null || texture == null; } }

		public Sheet(SheetType type, Size size)
		{
			Type = type;
			Size = size;
		}

		public Sheet(SheetType type, ITexture texture)
		{
			Type = type;
			this.texture = texture;
			Size = texture.Size;
		}

		public Sheet(SheetType type, Stream stream)
		{
			var png = new Png(stream);
			Size = new Size(png.Width, png.Height);
			data = new byte[4 * Size.Width * Size.Height];
			Util.FastCopyIntoSprite(new Sprite(this, new Rectangle(0, 0, png.Width, png.Height), TextureChannel.Red), png);

			Type = type;
			ReleaseBuffer();
		}

		public ITexture GetTexture()
		{
			if (texture == null)
			{
				texture = Game.Renderer.Context.CreateTexture();
				dirty = true;
			}

			if (data != null && dirty)
			{
				texture.SetData(data, Size.Width, Size.Height);
				dirty = false;
				if (releaseBufferOnCommit)
					data = null;
			}

			return texture;
		}

		public Png AsPng()
		{
			var data = GetData();

			// Convert BGRA to RGBA
			for (var i = 0; i < Size.Width * Size.Height; i++)
			{
				var temp = data[i * 4];
				data[i * 4] = data[i * 4 + 2];
				data[i * 4 + 2] = temp;
			}

			return new Png(data, Size.Width, Size.Height);
		}

		public Png AsPng(TextureChannel channel, IPalette pal)
		{
			var d = GetData();
			var plane = new byte[Size.Width * Size.Height];
			var dataStride = 4 * Size.Width;
			var channelOffset = (int)channel;

			for (var y = 0; y < Size.Height; y++)
				for (var x = 0; x < Size.Width; x++)
					plane[y * Size.Width + x] = d[y * dataStride + channelOffset + 4 * x];

			var palColors = new Color[Palette.Size];
			for (var i = 0; i < Palette.Size; i++)
				palColors[i] = pal.GetColor(i);

			return new Png(plane, Size.Width, Size.Height, palColors);
		}

		public void CreateBuffer()
		{
			if (data != null)
				return;
			if (texture == null)
				data = new byte[4 * Size.Width * Size.Height];
			else
				data = texture.GetData();
			releaseBufferOnCommit = false;
		}

		public void CommitBufferedData()
		{
			if (!Buffered)
				throw new InvalidOperationException(
					"This sheet is unbuffered. You cannot call CommitBufferedData on an unbuffered sheet. " +
					"If you need to completely replace the texture data you should set data into the texture directly. " +
					"If you need to make only small changes to the texture data consider creating a buffered sheet instead.");

			dirty = true;
		}

		public void ReleaseBuffer()
		{
			if (!Buffered)
				return;
			dirty = true;
			releaseBufferOnCommit = true;

			// Commit data from the buffer to the texture, allowing the buffer to be released and reclaimed by GC.
			if (Game.Renderer != null)
				GetTexture();
		}

		public void Dispose()
		{
			texture?.Dispose();
		}
	}
}


using System;
using System.Collections.Generic;
using BurningKnight.level;
using Lens.entity;
using Lens.util;
using Lens.util.file;

namespace BurningKnight.save {
	public class PrefabSaver : LevelSave {
		public List<PrefabData> Datas = new List<PrefabData>();

		public override void Load(Area area, FileReader reader) {
			Datas.Clear();
			base.Load(area, reader);
		}

		protected override void ReadEntity(Area area, FileReader reader, string type, bool post) {
			if (type == "level.rooms.Room") {
				type = "entity.room.Room";
			} else if (type == "entity.item.ItemStand") {
				type = "entity.item.stand.ItemStand";
			}

			var t = Type.GetType($"BurningKnight.{type}", true, false);

			if (typeof(Level).IsAssignableFrom(t)) {
				base.ReadEntity(area, reader, type, post);
				return;
			}

			var prefab = new PrefabData();
			prefab.Type = t;

			var size = reader.ReadInt16();
			prefab.Data = new byte[size];

			for (var i = 0; i < size; i++) {
				prefab.Data[i] = reader.ReadByte();
			}

			Datas.Add(prefab);
		}
	}
}


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Difficulty.Utils;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Objects;

namespace osu.Game.Rulesets.Taiko.Difficulty.Skills
{
    /// <summary>
    /// Calculates the stamina coefficient of taiko difficulty.
    /// </summary>
    /// <remarks>
    /// The reference play style chosen uses two hands, with full alternating (the hand changes after every hit).
    /// </remarks>
    public class Stamina : Skill
    {
        protected override double SkillMultiplier => 1;
        protected override double StrainDecayBase => 0.4;

        /// <summary>
        /// Maximum number of entries to keep in <see cref="notePairDurationHistory"/>.
        /// </summary>
        private const int max_history_length = 2;

        /// <summary>
        /// The index of the hand this <see cref="Stamina"/> instance is associated with.
        /// </summary>
        /// <remarks>
        /// The value of 0 indicates the left hand (full alternating gameplay starting with left hand is assumed).
        /// This naturally translates onto index offsets of the objects in the map.
        /// </remarks>
        private readonly int hand;

        /// <summary>
        /// Stores the last <see cref="max_history_length"/> durations between notes hit with the hand indicated by <see cref="hand"/>.
        /// </summary>
        private readonly LimitedCapacityQueue<double> notePairDurationHistory = new LimitedCapacityQueue<double>(max_history_length);

        /// <summary>
        /// Stores the <see cref="DifficultyHitObject.DeltaTime"/> of the last object that was hit by the <i>other</i> hand.
        /// </summary>
        private double offhandObjectDuration = double.MaxValue;

        /// <summary>
        /// Creates a <see cref="Stamina"/> skill.
        /// </summary>
        /// <param name="rightHand">Whether this instance is performing calculations for the right hand.</param>
        public Stamina(bool rightHand)
        {
            hand = rightHand ? 1 : 0;
        }

        protected override double StrainValueOf(DifficultyHitObject current)
        {
            if (!(current.BaseObject is Hit))
            {
                return 0.0;
            }

            TaikoDifficultyHitObject hitObject = (TaikoDifficultyHitObject)current;

            if (hitObject.ObjectIndex % 2 == hand)
            {
                double objectStrain = 1;

                if (hitObject.ObjectIndex == 1)
                    return 1;

                notePairDurationHistory.Enqueue(hitObject.DeltaTime + offhandObjectDuration);

                double shortestRecentNote = notePairDurationHistory.Min();
                objectStrain += speedBonus(shortestRecentNote);

                if (hitObject.StaminaCheese)
                    objectStrain *= cheesePenalty(hitObject.DeltaTime + offhandObjectDuration);

                return objectStrain;
            }

            offhandObjectDuration = hitObject.DeltaTime;
            return 0;
        }

        /// <summary>
        /// Applies a penalty for hit objects marked with <see cref="TaikoDifficultyHitObject.StaminaCheese"/>.
        /// </summary>
        /// <param name="notePairDuration">The duration between the current and previous note hit using the hand indicated by <see cref="hand"/>.</param>
        private double cheesePenalty(double notePairDuration)
        {
            if (notePairDuration > 125) return 1;
            if (notePairDuration < 100) return 0.6;

            return 0.6 + (notePairDuration - 100) * 0.016;
        }

        /// <summary>
        /// Applies a speed bonus dependent on the time since the last hit performed using this hand.
        /// </summary>
        /// <param name="notePairDuration">The duration between the current and previous note hit using the hand indicated by <see cref="hand"/>.</param>
        private double speedBonus(double notePairDuration)
        {
            if (notePairDuration >= 200) return 0;

            double bonus = 200 - notePairDuration;
            bonus *= bonus;
            return bonus / 100000;
        }
    }
}