{"lang_cluster":"C#","source_code":"\ufeffusing System;\nusing BurningKnight.assets;\nusing BurningKnight.entity.component;\nusing BurningKnight.ui.imgui;\nusing Lens.graphics;\nusing Lens.util;\nusing Lens.util.math;\nusing Microsoft.Xna.Framework;\n\nnamespace BurningKnight.entity.item {\n\tpublic class ItemGraphicsComponent : SliceComponent {\n\t\tpublic const float FlashSize = 0.025f;\n\t\tpublic const int ScourgedColorId = 48;\n\t\tpublic static Color MaskedColor = new Color(0f, 0f, 0f, 0.75f);\n\t\tpublic static Vector4 ScourgedColor = Palette.Default[ScourgedColorId].ToVector4();\n\t\t\n\t\tpublic float T;\n\t\t\n\t\tpublic ItemGraphicsComponent(string slice) : base(CommonAse.Items, slice) {\n\t\t\tT = Rnd.Float(32f);\n\t\t}\n\n\t\tpublic override void Init() {\n\t\t\tbase.Init();\n\t\t\t\n\t\t\tEntity.Width = Sprite.Source.Width;\n\t\t\tEntity.Height = Sprite.Source.Height;\n\t\t}\n\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\t\t\tT += dt;\n\t\t}\n\n\t\tpublic static float CalculateMove(float t) {\n\t\t\treturn (float) (Math.Sin(t * 3f) * 0.5f + 0.5f) * -5.5f;\n\t\t}\n\n\t\tpublic virtual Vector2 CalculatePosition(bool shadow = false) {\n\t\t\treturn Entity.Position + Sprite.Center + new Vector2(0, shadow ? 8 : CalculateMove(T));\n\t\t}\n\n\t\tpublic override void Render(bool shadow) {\n\t\t\tif (Entity.HasComponent()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar item = (Item) Entity;\n\t\t\tvar s = item.Hidden ? Item.UnknownRegion : Sprite;\n\t\t\tvar origin = s.Center;\n\t\t\tvar position = CalculatePosition(shadow);\n\t\t\tvar angle = (float) Math.Cos(T * 1.8f) * 0.4f;\n\t\t\tvar cursed = item.Scourged;\n\n\t\t\tif (!shadow) {\n\t\t\t\tvar interact = Entity.TryGetComponent(out var component) &&\n\t\t\t\t component.OutlineAlpha > 0.05f;\n\n\t\t\t\tif (cursed || interact) {\n\t\t\t\t\tvar shader = Shaders.Entity;\n\t\t\t\t\tShaders.Begin(shader);\n\n\t\t\t\t\tshader.Parameters[\"flash\"].SetValue(cursed ? 1f : component.OutlineAlpha);\n\t\t\t\t\tshader.Parameters[\"flashReplace\"].SetValue(1f);\n\t\t\t\t\tshader.Parameters[\"flashColor\"].SetValue(!cursed ? ColorUtils.White : ColorUtils.Mix(ScourgedColor, ColorUtils.White, component.OutlineAlpha));\n\n\t\t\t\t\tforeach (var d in MathUtils.Directions) {\n\t\t\t\t\t\tGraphics.Render(s, position + d, angle, origin);\n\t\t\t\t\t}\n\n\t\t\t\t\tShaders.End();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (item.Masked) {\n\t\t\t\tGraphics.Color = MaskedColor;\n\t\t\t\tGraphics.Render(s, position, angle, origin);\n\t\t\t\tGraphics.Color = ColorUtils.WhiteColor;\n\t\t\t} else {\n\t\t\t\tif (!shadow && DebugWindow.ItemShader && !Settings.LowQuality) {\n\t\t\t\t\tvar shader = Shaders.Item;\n\t\t\t\t\n\t\t\t\t\tShaders.Begin(shader);\n\t\t\t\t\tshader.Parameters[\"time\"].SetValue(T * 0.1f);\n\t\t\t\t\tshader.Parameters[\"size\"].SetValue(FlashSize);\n\t\t\t\t}\n\n\t\t\t\tGraphics.Render(s, position, angle, origin);\n\n\t\t\t\tif (!shadow && DebugWindow.ItemShader && !Settings.LowQuality) {\n\t\t\t\t\tShaders.End();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic class ItemGraphicsComponent : SliceComponent {\n\t\tpublic const float FlashSize = 0.025f;\n\t\tpublic const int ScourgedColorId = 48;\n\t\tpublic static Color MaskedColor = new Color(0f, 0f, 0f, 0.75f);\n\t\tpublic static Vector4 ScourgedColor = Palette.Default[ScourgedColorId].ToVector4();\n\t\t\n\t\tpublic float T;\n\t\t\n\t\tpublic ItemGraphicsComponent(string slice) : base(CommonAse.Items, slice) {\n\t\t\tT = Rnd.Float(32f);\n\t\t}\n\n\t\tpublic override void Init() {\n\t\t\tbase.Init();\n\t\t\t\n\t\t\tEntity.Width = Sprite.Source.Width;\n\t\t\tEntity.Height = Sprite.Source.Height;\n\t\t}\n\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\t\t\tT += dt;\n\t\t}\n\n\t\tpublic static float CalculateMove(float t) {\n\t\t\treturn (float) (Math.Sin(t * 3f) * 0.5f + 0.5f) * -5.5f;\n\t\t}\n\n\t\tpublic virtual Vector2 CalculatePosition(bool shadow = false) {\n\t\t\treturn Entity.Position + Sprite.Center + new Vector2(0, shadow ? 8 : CalculateMove(T));\n\t\t}\n\n\t\tpublic override void Render(bool shadow) {\n\t\t\tif (Entity.HasComponent()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar item = (Item) Entity;\n\t\t\tvar s = item.Hidden ? Item.UnknownRegion : Sprite;\n\t\t\tvar origin = s.Center;\n\t\t\tvar position = CalculatePosition(shadow);\n\t\t\tvar angle = (float) Math.Cos(T * 1.8f) * 0.4f;\n\t\t\tvar cursed = item.Scourged;\n\n\t\t\tif (!shadow) {\n\t\t\t\tvar interact = Entity.TryGetComponent(out var component) &&\n\t\t\t\t component.OutlineAlpha > 0.05f;\n\n\t\t\t\tif (cursed || interact) {\n\t\t\t\t\tvar shader = Shaders.Entity;\n\t\t\t\t\tShaders.Begin(shader);\n\n\t\t\t\t\tshader.Parameters[\"flash\"].SetValue(cursed ? 1f : component.OutlineAlpha);\n\t\t\t\t\tshader.Parameters[\"flashReplace\"].SetValue(1f);\n\t\t\t\t\tshader.Parameters[\"flashColor\"].SetValue(!cursed ? ColorUtils.White : ColorUtils.Mix(ScourgedColor, ColorUtils.White, component.OutlineAlpha));\n\n\t\t\t\t\tforeach (var d in MathUtils.Directions) {\n\t\t\t\t\t\tGraphics.Render(s, position + d, angle, origin);\n\t\t\t\t\t}\n\n\t\t\t\t\tShaders.End();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (item.Masked) {\n\t\t\t\tGraphics.Color = MaskedColor;\n\t\t\t\tGraphics.Render(s, position, angle, origin);\n\t\t\t\tGraphics.Color = ColorUtils.WhiteColor;\n\t\t\t} else {\n\t\t\t\tif (!shadow && DebugWindow.ItemShader && !Settings.LowQuality) {\n\t\t\t\t\tvar shader = Shaders.Item;\n\t\t\t\t\n\t\t\t\t\tShaders.Begin(shader);\n\t\t\t\t\tshader.Parameters[\"time\"].SetValue(T * 0.1f);\n\t\t\t\t\tshader.Parameters[\"size\"].SetValue(FlashSize);\n\t\t\t\t}\n\n\t\t\t\tGraphics.Render(s, position, angle, origin);\n\n\t\t\t\tif (!shadow && DebugWindow.ItemShader && !Settings.LowQuality) {\n\t\t\t\t\tShaders.End();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":1} {"lang_cluster":"C#","source_code":"\ufeff#region License Information (GPL v3)\n\n\/*\n ShareX - A program that allows you to take screenshots and share any file type\n Copyright (c) 2007-2020 ShareX Team\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n Optionally you can also view the license at .\n*\/\n\n#endregion License Information (GPL v3)\n\nusing System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\nnamespace ShareX.HelpersLib\n{\n public class JsonFileNameEditor : FileNameEditor\n {\n public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n {\n if (context == null || provider == null)\n {\n return base.EditValue(context, provider, value);\n }\n using (OpenFileDialog dlg = new OpenFileDialog())\n {\n dlg.Filter = \"JavaScript Object Notation files (*.json)|*.json\";\n if (dlg.ShowDialog() == DialogResult.OK)\n {\n value = dlg.FileName;\n }\n }\n return value;\n }\n }\n}","smell_code":" public class JsonFileNameEditor : FileNameEditor\n {\n public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n {\n if (context == null || provider == null)\n {\n return base.EditValue(context, provider, value);\n }\n using (OpenFileDialog dlg = new OpenFileDialog())\n {\n dlg.Filter = \"JavaScript Object Notation files (*.json)|*.json\";\n if (dlg.ShowDialog() == DialogResult.OK)\n {\n value = dlg.FileName;\n }\n }\n return value;\n }\n }","smell":"large class","id":2} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Linq;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t[Desc(\"Reloads an ammo pool.\")]\n\tpublic class ReloadAmmoPoolInfo : PausableConditionalTraitInfo\n\t{\n\t\t[Desc(\"Reload ammo pool with this name.\")]\n\t\tpublic readonly string AmmoPool = \"primary\";\n\n\t\t[Desc(\"Reload time in ticks per Count.\")]\n\t\tpublic readonly int Delay = 50;\n\n\t\t[Desc(\"How much ammo is reloaded after Delay.\")]\n\t\tpublic readonly int Count = 1;\n\n\t\t[Desc(\"Whether or not reload timer should be reset when ammo has been fired.\")]\n\t\tpublic readonly bool ResetOnFire = false;\n\n\t\t[Desc(\"Play this sound each time ammo is reloaded.\")]\n\t\tpublic readonly string Sound = null;\n\n\t\tpublic override object Create(ActorInitializer init) { return new ReloadAmmoPool(this); }\n\n\t\tpublic override void RulesetLoaded(Ruleset rules, ActorInfo ai)\n\t\t{\n\t\t\tif (ai.TraitInfos().Count(ap => ap.Name == AmmoPool) != 1)\n\t\t\t\tthrow new YamlException(\"ReloadsAmmoPool.AmmoPool requires exactly one AmmoPool with matching Name!\");\n\n\t\t\tbase.RulesetLoaded(rules, ai);\n\t\t}\n\t}\n\n\tpublic class ReloadAmmoPool : PausableConditionalTrait, ITick, INotifyAttack, ISync\n\t{\n\t\tAmmoPool ammoPool;\n\t\tIReloadAmmoModifier[] modifiers;\n\n\t\t[Sync]\n\t\tint remainingTicks;\n\n\t\tpublic ReloadAmmoPool(ReloadAmmoPoolInfo info)\n\t\t\t: base(info) { }\n\n\t\tprotected override void Created(Actor self)\n\t\t{\n\t\t\tammoPool = self.TraitsImplementing().Single(ap => ap.Info.Name == Info.AmmoPool);\n\t\t\tmodifiers = self.TraitsImplementing().ToArray();\n\t\t\tbase.Created(self);\n\n\t\t\tself.World.AddFrameEndTask(w =>\n\t\t\t{\n\t\t\t\tremainingTicks = Util.ApplyPercentageModifiers(Info.Delay, modifiers.Select(m => m.GetReloadAmmoModifier()));\n\t\t\t});\n\t\t}\n\n\t\tvoid INotifyAttack.Attacking(Actor self, in Target target, Armament a, Barrel barrel)\n\t\t{\n\t\t\tif (Info.ResetOnFire)\n\t\t\t\tremainingTicks = Util.ApplyPercentageModifiers(Info.Delay, modifiers.Select(m => m.GetReloadAmmoModifier()));\n\t\t}\n\n\t\tvoid INotifyAttack.PreparingAttack(Actor self, in Target target, Armament a, Barrel barrel) { }\n\n\t\tvoid ITick.Tick(Actor self)\n\t\t{\n\t\t\tif (IsTraitPaused || IsTraitDisabled)\n\t\t\t\treturn;\n\n\t\t\tReload(self, Info.Delay, Info.Count, Info.Sound);\n\t\t}\n\n\t\tprotected virtual void Reload(Actor self, int reloadDelay, int reloadCount, string sound)\n\t\t{\n\t\t\tif (!ammoPool.HasFullAmmo && --remainingTicks == 0)\n\t\t\t{\n\t\t\t\tremainingTicks = Util.ApplyPercentageModifiers(reloadDelay, modifiers.Select(m => m.GetReloadAmmoModifier()));\n\t\t\t\tif (!string.IsNullOrEmpty(sound))\n\t\t\t\t\tGame.Sound.PlayToPlayer(SoundType.World, self.Owner, sound, self.CenterPosition);\n\n\t\t\t\tammoPool.GiveAmmo(self, reloadCount);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t[Desc(\"Reloads an ammo pool.\")]\n\tpublic class ReloadAmmoPoolInfo : PausableConditionalTraitInfo\n\t{\n\t\t[Desc(\"Reload ammo pool with this name.\")]\n\t\tpublic readonly string AmmoPool = \"primary\";\n\n\t\t[Desc(\"Reload time in ticks per Count.\")]\n\t\tpublic readonly int Delay = 50;\n\n\t\t[Desc(\"How much ammo is reloaded after Delay.\")]\n\t\tpublic readonly int Count = 1;\n\n\t\t[Desc(\"Whether or not reload timer should be reset when ammo has been fired.\")]\n\t\tpublic readonly bool ResetOnFire = false;\n\n\t\t[Desc(\"Play this sound each time ammo is reloaded.\")]\n\t\tpublic readonly string Sound = null;\n\n\t\tpublic override object Create(ActorInitializer init) { return new ReloadAmmoPool(this); }\n\n\t\tpublic override void RulesetLoaded(Ruleset rules, ActorInfo ai)\n\t\t{\n\t\t\tif (ai.TraitInfos().Count(ap => ap.Name == AmmoPool) != 1)\n\t\t\t\tthrow new YamlException(\"ReloadsAmmoPool.AmmoPool requires exactly one AmmoPool with matching Name!\");\n\n\t\t\tbase.RulesetLoaded(rules, ai);\n\t\t}\n\t}","smell":"large class","id":3} {"lang_cluster":"C#","source_code":"\ufeff#region License Information (GPL v3)\n\n\/*\n ShareX - A program that allows you to take screenshots and share any file type\n Copyright (c) 2007-2020 ShareX Team\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n Optionally you can also view the license at .\n*\/\n\n#endregion License Information (GPL v3)\n\nusing ShareX.HelpersLib;\n\nnamespace ShareX.UploadersLib.FileUploaders\n{\n public class AmazonS3Settings\n {\n public string AccessKeyID { get; set; }\n [JsonEncrypt]\n public string SecretAccessKey { get; set; }\n public string Endpoint { get; set; }\n public string Region { get; set; }\n public bool UsePathStyle { get; set; }\n public string Bucket { get; set; }\n public string ObjectPrefix { get; set; }\n public bool UseCustomCNAME { get; set; }\n public string CustomDomain { get; set; }\n public AmazonS3StorageClass StorageClass { get; set; }\n public bool SetPublicACL { get; set; } = true;\n public bool SignedPayload { get; set; }\n public bool RemoveExtensionImage { get; set; }\n public bool RemoveExtensionVideo { get; set; }\n public bool RemoveExtensionText { get; set; }\n }\n}","smell_code":" public class AmazonS3Settings\n {\n public string AccessKeyID { get; set; }\n [JsonEncrypt]\n public string SecretAccessKey { get; set; }\n public string Endpoint { get; set; }\n public string Region { get; set; }\n public bool UsePathStyle { get; set; }\n public string Bucket { get; set; }\n public string ObjectPrefix { get; set; }\n public bool UseCustomCNAME { get; set; }\n public string CustomDomain { get; set; }\n public AmazonS3StorageClass StorageClass { get; set; }\n public bool SetPublicACL { get; set; } = true;\n public bool SignedPayload { get; set; }\n public bool RemoveExtensionImage { get; set; }\n public bool RemoveExtensionVideo { get; set; }\n public bool RemoveExtensionText { get; set; }\n }","smell":"large class","id":4} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Online.API.Requests;\nusing osu.Game.Users;\nusing System;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics;\nusing osu.Game.Online.API.Requests.Responses;\nusing System.Collections.Generic;\nusing osu.Game.Online.API;\nusing osu.Framework.Allocation;\n\nnamespace osu.Game.Overlays.Profile.Sections.Ranks\n{\n public class PaginatedScoreContainer : PaginatedProfileSubsection\n {\n private readonly ScoreType type;\n\n public PaginatedScoreContainer(ScoreType type, Bindable user, string headerText, CounterVisibilityState counterVisibilityState, string missingText = \"\")\n : base(user, headerText, missingText, counterVisibilityState)\n {\n this.type = type;\n\n ItemsPerPage = 5;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n ItemsContainer.Direction = FillDirection.Vertical;\n }\n\n protected override int GetCount(User user)\n {\n switch (type)\n {\n case ScoreType.Firsts:\n return user.ScoresFirstCount;\n\n default:\n return 0;\n }\n }\n\n protected override void OnItemsReceived(List items)\n {\n if (VisiblePages == 0)\n drawableItemIndex = 0;\n\n base.OnItemsReceived(items);\n\n if (type == ScoreType.Recent)\n SetCount(items.Count);\n }\n\n protected override APIRequest> CreateRequest() =>\n new GetUserScoresRequest(User.Value.Id, type, VisiblePages++, ItemsPerPage);\n\n private int drawableItemIndex;\n\n protected override Drawable CreateDrawableItem(APILegacyScoreInfo model)\n {\n switch (type)\n {\n default:\n return new DrawableProfileScore(model.CreateScoreInfo(Rulesets));\n\n case ScoreType.Best:\n return new DrawableProfileWeightedScore(model.CreateScoreInfo(Rulesets), Math.Pow(0.95, drawableItemIndex++));\n }\n }\n }\n}","smell_code":" public class PaginatedScoreContainer : PaginatedProfileSubsection\n {\n private readonly ScoreType type;\n\n public PaginatedScoreContainer(ScoreType type, Bindable user, string headerText, CounterVisibilityState counterVisibilityState, string missingText = \"\")\n : base(user, headerText, missingText, counterVisibilityState)\n {\n this.type = type;\n\n ItemsPerPage = 5;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n ItemsContainer.Direction = FillDirection.Vertical;\n }\n\n protected override int GetCount(User user)\n {\n switch (type)\n {\n case ScoreType.Firsts:\n return user.ScoresFirstCount;\n\n default:\n return 0;\n }\n }\n\n protected override void OnItemsReceived(List items)\n {\n if (VisiblePages == 0)\n drawableItemIndex = 0;\n\n base.OnItemsReceived(items);\n\n if (type == ScoreType.Recent)\n SetCount(items.Count);\n }\n\n protected override APIRequest> CreateRequest() =>\n new GetUserScoresRequest(User.Value.Id, type, VisiblePages++, ItemsPerPage);\n\n private int drawableItemIndex;\n\n protected override Drawable CreateDrawableItem(APILegacyScoreInfo model)\n {\n switch (type)\n {\n default:\n return new DrawableProfileScore(model.CreateScoreInfo(Rulesets));\n\n case ScoreType.Best:\n return new DrawableProfileWeightedScore(model.CreateScoreInfo(Rulesets), Math.Pow(0.95, drawableItemIndex++));\n }\n }\n }","smell":"large class","id":5} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t[AttributeUsage(AttributeTargets.Field)]\n\tpublic sealed class VoiceSetReferenceAttribute : Attribute { }\n\n\t[AttributeUsage(AttributeTargets.Field)]\n\tpublic sealed class VoiceReferenceAttribute : Attribute { }\n\n\t[AttributeUsage(AttributeTargets.Field)]\n\tpublic sealed class LocomotorReferenceAttribute : Attribute { }\n\n\t[AttributeUsage(AttributeTargets.Field)]\n\tpublic sealed class NotificationReferenceAttribute : Attribute\n\t{\n\t\tpublic readonly string NotificationTypeFieldName = null;\n\t\tpublic readonly string NotificationType = null;\n\n\t\tpublic NotificationReferenceAttribute(string type = null, string typeFromField = null)\n\t\t{\n\t\t\tNotificationType = type;\n\t\t\tNotificationTypeFieldName = typeFromField;\n\t\t}\n\t}\n}","smell_code":"\t[AttributeUsage(AttributeTargets.Field)]\n\tpublic sealed class LocomotorReferenceAttribute : Attribute { }","smell":"large class","id":6} {"lang_cluster":"C#","source_code":"namespace BurningKnight.debug {\n\tpublic class TileCommand : ConsoleCommand {\n\t\tpublic TileCommand() {\n\t\t\tName = \"tile\";\n\t\t\tShortName = \"t\";\n\t\t}\n\t\t\n\t\tpublic override void Run(Console Console, string[] Args) {\n\t\t\tvar level = state.Run.Level;\n\n\t\t\tif (level != null) {\n\t\t\t\t\/\/ level.Resize(level.Width, level.Height);\n\t\t\t\tlevel.RefreshSurfaces();\n\t\t\t\tlevel.TileUp(true);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic class TileCommand : ConsoleCommand {\n\t\tpublic TileCommand() {\n\t\t\tName = \"tile\";\n\t\t\tShortName = \"t\";\n\t\t}\n\t\t\n\t\tpublic override void Run(Console Console, string[] Args) {\n\t\t\tvar level = state.Run.Level;\n\n\t\t\tif (level != null) {\n\t\t\t\t\/\/ level.Resize(level.Width, level.Height);\n\t\t\t\tlevel.RefreshSurfaces();\n\t\t\t\tlevel.TileUp(true);\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":7} {"lang_cluster":"C#","source_code":"using BurningKnight.entity;\nusing BurningKnight.entity.component;\nusing BurningKnight.entity.creature.player;\nusing BurningKnight.entity.fx;\nusing BurningKnight.save;\nusing BurningKnight.state;\nusing BurningKnight.ui.editor;\nusing ImGuiNET;\nusing Lens;\nusing Lens.assets;\nusing Lens.entity;\nusing Lens.util.camera;\nusing Lens.util.file;\nusing Microsoft.Xna.Framework;\nusing VelcroPhysics.Dynamics;\n\nnamespace BurningKnight.level.entities {\n\tpublic class HiddenEntrance : SaveableEntity, PlaceableEntity {\n\t\tinternal string id;\n\t\t\n\t\tprivate bool Interact(Entity entity) {\n\t\t\tforeach (var e in Area.Tagged[Tags.HiddenEntrance]) {\n\t\t\t\tif (e is HiddenExit h && h.id == id) {\n\t\t\t\t\tvar state = (InGameState) Engine.Instance.State;\n\t\t\t\t\tAudio.PlaySfx(\"player_descending\");\t\t\t\n\n\t\t\t\t\tstate.TransitionToBlack(Center, () => {\n\t\t\t\t\t\tforeach (var p in Area.Tagged[Tags.Player]) {\n\t\t\t\t\t\t\tp.BottomCenter = e.BottomCenter + new Vector2(0, 2);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstate.ResetFollowing();\n\t\t\t\t\t\tCamera.Instance.Jump();\n\t\t\t\t\t\tstate.TransitionToOpen();\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\n\t\tprivate bool CanInteract(Entity e) {\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\n\t\t\tDepth = Layers.Entrance;\n\t\t\tAddTag(Tags.HiddenEntrance);\n\t\t\t\n\t\t\tAddComponent(new InteractableComponent(Interact) {\n\t\t\t\tOnStart = entity => {\n\t\t\t\t\tif (entity is LocalPlayer) {\n\t\t\t\t\t\tEngine.Instance.State.Ui.Add(new InteractFx(this, Locale.Get(\"descend\")));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\tCanInteract = CanInteract\n\t\t\t});\n\t\t\t\n\t\t\tAddComponent(new RectBodyComponent(0, 0, Width, Height, BodyType.Static, true));\n\t\t\tAddComponent(new InteractableSliceComponent(\"props\", \"dark_market\"));\n\t\t}\n\n\t\tprivate bool set;\n\t\t\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\n\t\t\tif (!set) {\n\t\t\t\tset = true;\n\n\t\t\t\tif (Run.Depth > 0) {\n\t\t\t\t\tGameSave.Put(\"saw_blackmarket\", true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Load(FileReader stream) {\n\t\t\tbase.Load(stream);\n\t\t\tid = stream.ReadString();\n\t\t}\n\n\t\tpublic override void Save(FileWriter stream) {\n\t\t\tbase.Save(stream);\n\t\t\t\n\t\t\tif (id == null) {\n\t\t\t\tid = \"\";\n\t\t\t}\n\t\t\t\n\t\t\tstream.WriteString(id);\n\t\t}\n\n\t\tpublic override void RenderImDebug() {\n\t\t\tbase.RenderImDebug();\n\n\t\t\tif (id == null) {\n\t\t\t\tid = \"\";\n\t\t\t}\n\n\t\t\tImGui.InputText(\"Id\", ref id, 64);\n\t\t}\n\t}\n}","smell_code":"\tpublic class HiddenEntrance : SaveableEntity, PlaceableEntity {\n\t\tinternal string id;\n\t\t\n\t\tprivate bool Interact(Entity entity) {\n\t\t\tforeach (var e in Area.Tagged[Tags.HiddenEntrance]) {\n\t\t\t\tif (e is HiddenExit h && h.id == id) {\n\t\t\t\t\tvar state = (InGameState) Engine.Instance.State;\n\t\t\t\t\tAudio.PlaySfx(\"player_descending\");\t\t\t\n\n\t\t\t\t\tstate.TransitionToBlack(Center, () => {\n\t\t\t\t\t\tforeach (var p in Area.Tagged[Tags.Player]) {\n\t\t\t\t\t\t\tp.BottomCenter = e.BottomCenter + new Vector2(0, 2);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstate.ResetFollowing();\n\t\t\t\t\t\tCamera.Instance.Jump();\n\t\t\t\t\t\tstate.TransitionToOpen();\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\n\t\tprivate bool CanInteract(Entity e) {\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\n\t\t\tDepth = Layers.Entrance;\n\t\t\tAddTag(Tags.HiddenEntrance);\n\t\t\t\n\t\t\tAddComponent(new InteractableComponent(Interact) {\n\t\t\t\tOnStart = entity => {\n\t\t\t\t\tif (entity is LocalPlayer) {\n\t\t\t\t\t\tEngine.Instance.State.Ui.Add(new InteractFx(this, Locale.Get(\"descend\")));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\tCanInteract = CanInteract\n\t\t\t});\n\t\t\t\n\t\t\tAddComponent(new RectBodyComponent(0, 0, Width, Height, BodyType.Static, true));\n\t\t\tAddComponent(new InteractableSliceComponent(\"props\", \"dark_market\"));\n\t\t}\n\n\t\tprivate bool set;\n\t\t\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\n\t\t\tif (!set) {\n\t\t\t\tset = true;\n\n\t\t\t\tif (Run.Depth > 0) {\n\t\t\t\t\tGameSave.Put(\"saw_blackmarket\", true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Load(FileReader stream) {\n\t\t\tbase.Load(stream);\n\t\t\tid = stream.ReadString();\n\t\t}\n\n\t\tpublic override void Save(FileWriter stream) {\n\t\t\tbase.Save(stream);\n\t\t\t\n\t\t\tif (id == null) {\n\t\t\t\tid = \"\";\n\t\t\t}\n\t\t\t\n\t\t\tstream.WriteString(id);\n\t\t}\n\n\t\tpublic override void RenderImDebug() {\n\t\t\tbase.RenderImDebug();\n\n\t\t\tif (id == null) {\n\t\t\t\tid = \"\";\n\t\t\t}\n\n\t\t\tImGui.InputText(\"Id\", ref id, 64);\n\t\t}\n\t}","smell":"large class","id":8} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing OpenRA.Graphics;\nusing OpenRA.Mods.Common.Orders;\nusing OpenRA.Mods.Common.Traits.Render;\nusing OpenRA.Primitives;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\tclass GrantExternalConditionPowerInfo : SupportPowerInfo\n\t{\n\t\t[FieldLoader.Require]\n\t\t[Desc(\"The condition to apply. Must be included in the target actor's ExternalConditions list.\")]\n\t\tpublic readonly string Condition = null;\n\n\t\t[Desc(\"Duration of the condition (in ticks). Set to 0 for a permanent condition.\")]\n\t\tpublic readonly int Duration = 0;\n\n\t\t[FieldLoader.Require]\n\t\t[Desc(\"Size of the footprint of the affected area.\")]\n\t\tpublic readonly CVec Dimensions = CVec.Zero;\n\n\t\t[FieldLoader.Require]\n\t\t[Desc(\"Actual footprint. Cells marked as x will be affected.\")]\n\t\tpublic readonly string Footprint = string.Empty;\n\n\t\t[Desc(\"Sound to instantly play at the targeted area.\")]\n\t\tpublic readonly string OnFireSound = null;\n\n\t\t[Desc(\"Player relationships which condition can be applied to.\")]\n\t\tpublic readonly PlayerRelationship ValidRelationships = PlayerRelationship.Ally;\n\n\t\t[SequenceReference]\n\t\t[Desc(\"Sequence to play for granting actor when activated.\",\n\t\t\t\"This requires the actor to have the WithSpriteBody trait or one of its derivatives.\")]\n\t\tpublic readonly string Sequence = \"active\";\n\n\t\t[Desc(\"Cursor to display when there are no units to apply the condition in range.\")]\n\t\tpublic readonly string BlockedCursor = \"move-blocked\";\n\n\t\tpublic override object Create(ActorInitializer init) { return new GrantExternalConditionPower(init.Self, this); }\n\t}\n\n\tclass GrantExternalConditionPower : SupportPower\n\t{\n\t\treadonly GrantExternalConditionPowerInfo info;\n\t\treadonly char[] footprint;\n\n\t\tpublic GrantExternalConditionPower(Actor self, GrantExternalConditionPowerInfo info)\n\t\t\t: base(self, info)\n\t\t{\n\t\t\tthis.info = info;\n\t\t\tfootprint = info.Footprint.Where(c => !char.IsWhiteSpace(c)).ToArray();\n\t\t}\n\n\t\tpublic override void SelectTarget(Actor self, string order, SupportPowerManager manager)\n\t\t{\n\t\t\tself.World.OrderGenerator = new SelectConditionTarget(Self.World, order, manager, this);\n\t\t}\n\n\t\tpublic override void Activate(Actor self, Order order, SupportPowerManager manager)\n\t\t{\n\t\t\tbase.Activate(self, order, manager);\n\t\t\tPlayLaunchSounds();\n\n\t\t\tvar wsb = self.TraitOrDefault();\n\t\t\tif (wsb != null && wsb.DefaultAnimation.HasSequence(info.Sequence))\n\t\t\t\twsb.PlayCustomAnimation(self, info.Sequence);\n\n\t\t\tGame.Sound.Play(SoundType.World, info.OnFireSound, order.Target.CenterPosition);\n\n\t\t\tforeach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition)))\n\t\t\t\ta.TraitsImplementing()\n\t\t\t\t\t.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self))\n\t\t\t\t\t?.GrantCondition(a, self, info.Duration);\n\t\t}\n\n\t\tpublic IEnumerable UnitsInRange(CPos xy)\n\t\t{\n\t\t\tvar tiles = CellsMatching(xy, footprint, info.Dimensions);\n\t\t\tvar units = new List();\n\t\t\tforeach (var t in tiles)\n\t\t\t\tunits.AddRange(Self.World.ActorMap.GetActorsAt(t));\n\n\t\t\treturn units.Distinct().Where(a =>\n\t\t\t{\n\t\t\t\tif (!info.ValidRelationships.HasStance(Self.Owner.RelationshipWith(a.Owner)))\n\t\t\t\t\treturn false;\n\n\t\t\t\treturn a.TraitsImplementing()\n\t\t\t\t\t.Any(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, Self));\n\t\t\t});\n\t\t}\n\n\t\tclass SelectConditionTarget : OrderGenerator\n\t\t{\n\t\t\treadonly GrantExternalConditionPower power;\n\t\t\treadonly char[] footprint;\n\t\t\treadonly CVec dimensions;\n\t\t\treadonly Sprite tile;\n\t\t\treadonly SupportPowerManager manager;\n\t\t\treadonly string order;\n\n\t\t\tpublic SelectConditionTarget(World world, string order, SupportPowerManager manager, GrantExternalConditionPower power)\n\t\t\t{\n\t\t\t\t\/\/ Clear selection if using Left-Click Orders\n\t\t\t\tif (Game.Settings.Game.UseClassicMouseStyle)\n\t\t\t\t\tmanager.Self.World.Selection.Clear();\n\n\t\t\t\tthis.manager = manager;\n\t\t\t\tthis.order = order;\n\t\t\t\tthis.power = power;\n\t\t\t\tfootprint = power.info.Footprint.Where(c => !char.IsWhiteSpace(c)).ToArray();\n\t\t\t\tdimensions = power.info.Dimensions;\n\t\t\t\ttile = world.Map.Rules.Sequences.GetSequence(\"overlay\", \"target-select\").GetSprite(0);\n\t\t\t}\n\n\t\t\tprotected override IEnumerable OrderInner(World world, CPos cell, int2 worldPixel, MouseInput mi)\n\t\t\t{\n\t\t\t\tworld.CancelInputMode();\n\t\t\t\tif (mi.Button == MouseButton.Left && power.UnitsInRange(cell).Any())\n\t\t\t\t\tyield return new Order(order, manager.Self, Target.FromCell(world, cell), false) { SuppressVisualFeedback = true };\n\t\t\t}\n\n\t\t\tprotected override void Tick(World world)\n\t\t\t{\n\t\t\t\t\/\/ Cancel the OG if we can't use the power\n\t\t\t\tif (!manager.Powers.ContainsKey(order))\n\t\t\t\t\tworld.CancelInputMode();\n\t\t\t}\n\n\t\t\tprotected override IEnumerable RenderAboveShroud(WorldRenderer wr, World world) { yield break; }\n\n\t\t\tprotected override IEnumerable RenderAnnotations(WorldRenderer wr, World world)\n\t\t\t{\n\t\t\t\tvar xy = wr.Viewport.ViewToWorld(Viewport.LastMousePos);\n\t\t\t\tforeach (var unit in power.UnitsInRange(xy))\n\t\t\t\t{\n\t\t\t\t\tvar decorations = unit.TraitsImplementing().FirstEnabledTraitOrDefault();\n\t\t\t\t\tif (decorations != null)\n\t\t\t\t\t\tforeach (var d in decorations.RenderSelectionAnnotations(unit, wr, Color.Red))\n\t\t\t\t\t\t\tyield return d;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprotected override IEnumerable Render(WorldRenderer wr, World world)\n\t\t\t{\n\t\t\t\tvar xy = wr.Viewport.ViewToWorld(Viewport.LastMousePos);\n\t\t\t\tvar pal = wr.Palette(TileSet.TerrainPaletteInternalName);\n\n\t\t\t\tforeach (var t in power.CellsMatching(xy, footprint, dimensions))\n\t\t\t\t\tyield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, pal, 1f, true, true);\n\t\t\t}\n\n\t\t\tprotected override string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi)\n\t\t\t{\n\t\t\t\treturn power.UnitsInRange(cell).Any() ? power.info.Cursor : power.info.BlockedCursor;\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tclass GrantExternalConditionPower : SupportPower\n\t{\n\t\treadonly GrantExternalConditionPowerInfo info;\n\t\treadonly char[] footprint;\n\n\t\tpublic GrantExternalConditionPower(Actor self, GrantExternalConditionPowerInfo info)\n\t\t\t: base(self, info)\n\t\t{\n\t\t\tthis.info = info;\n\t\t\tfootprint = info.Footprint.Where(c => !char.IsWhiteSpace(c)).ToArray();\n\t\t}\n\n\t\tpublic override void SelectTarget(Actor self, string order, SupportPowerManager manager)\n\t\t{\n\t\t\tself.World.OrderGenerator = new SelectConditionTarget(Self.World, order, manager, this);\n\t\t}\n\n\t\tpublic override void Activate(Actor self, Order order, SupportPowerManager manager)\n\t\t{\n\t\t\tbase.Activate(self, order, manager);\n\t\t\tPlayLaunchSounds();\n\n\t\t\tvar wsb = self.TraitOrDefault();\n\t\t\tif (wsb != null && wsb.DefaultAnimation.HasSequence(info.Sequence))\n\t\t\t\twsb.PlayCustomAnimation(self, info.Sequence);\n\n\t\t\tGame.Sound.Play(SoundType.World, info.OnFireSound, order.Target.CenterPosition);\n\n\t\t\tforeach (var a in UnitsInRange(self.World.Map.CellContaining(order.Target.CenterPosition)))\n\t\t\t\ta.TraitsImplementing()\n\t\t\t\t\t.FirstOrDefault(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, self))\n\t\t\t\t\t?.GrantCondition(a, self, info.Duration);\n\t\t}\n\n\t\tpublic IEnumerable UnitsInRange(CPos xy)\n\t\t{\n\t\t\tvar tiles = CellsMatching(xy, footprint, info.Dimensions);\n\t\t\tvar units = new List();\n\t\t\tforeach (var t in tiles)\n\t\t\t\tunits.AddRange(Self.World.ActorMap.GetActorsAt(t));\n\n\t\t\treturn units.Distinct().Where(a =>\n\t\t\t{\n\t\t\t\tif (!info.ValidRelationships.HasStance(Self.Owner.RelationshipWith(a.Owner)))\n\t\t\t\t\treturn false;\n\n\t\t\t\treturn a.TraitsImplementing()\n\t\t\t\t\t.Any(t => t.Info.Condition == info.Condition && t.CanGrantCondition(a, Self));\n\t\t\t});\n\t\t}\n\n\t\tclass SelectConditionTarget : OrderGenerator\n\t\t{\n\t\t\treadonly GrantExternalConditionPower power;\n\t\t\treadonly char[] footprint;\n\t\t\treadonly CVec dimensions;\n\t\t\treadonly Sprite tile;\n\t\t\treadonly SupportPowerManager manager;\n\t\t\treadonly string order;\n\n\t\t\tpublic SelectConditionTarget(World world, string order, SupportPowerManager manager, GrantExternalConditionPower power)\n\t\t\t{\n\t\t\t\t\/\/ Clear selection if using Left-Click Orders\n\t\t\t\tif (Game.Settings.Game.UseClassicMouseStyle)\n\t\t\t\t\tmanager.Self.World.Selection.Clear();\n\n\t\t\t\tthis.manager = manager;\n\t\t\t\tthis.order = order;\n\t\t\t\tthis.power = power;\n\t\t\t\tfootprint = power.info.Footprint.Where(c => !char.IsWhiteSpace(c)).ToArray();\n\t\t\t\tdimensions = power.info.Dimensions;\n\t\t\t\ttile = world.Map.Rules.Sequences.GetSequence(\"overlay\", \"target-select\").GetSprite(0);\n\t\t\t}\n\n\t\t\tprotected override IEnumerable OrderInner(World world, CPos cell, int2 worldPixel, MouseInput mi)\n\t\t\t{\n\t\t\t\tworld.CancelInputMode();\n\t\t\t\tif (mi.Button == MouseButton.Left && power.UnitsInRange(cell).Any())\n\t\t\t\t\tyield return new Order(order, manager.Self, Target.FromCell(world, cell), false) { SuppressVisualFeedback = true };\n\t\t\t}\n\n\t\t\tprotected override void Tick(World world)\n\t\t\t{\n\t\t\t\t\/\/ Cancel the OG if we can't use the power\n\t\t\t\tif (!manager.Powers.ContainsKey(order))\n\t\t\t\t\tworld.CancelInputMode();\n\t\t\t}\n\n\t\t\tprotected override IEnumerable RenderAboveShroud(WorldRenderer wr, World world) { yield break; }\n\n\t\t\tprotected override IEnumerable RenderAnnotations(WorldRenderer wr, World world)\n\t\t\t{\n\t\t\t\tvar xy = wr.Viewport.ViewToWorld(Viewport.LastMousePos);\n\t\t\t\tforeach (var unit in power.UnitsInRange(xy))\n\t\t\t\t{\n\t\t\t\t\tvar decorations = unit.TraitsImplementing().FirstEnabledTraitOrDefault();\n\t\t\t\t\tif (decorations != null)\n\t\t\t\t\t\tforeach (var d in decorations.RenderSelectionAnnotations(unit, wr, Color.Red))\n\t\t\t\t\t\t\tyield return d;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprotected override IEnumerable Render(WorldRenderer wr, World world)\n\t\t\t{\n\t\t\t\tvar xy = wr.Viewport.ViewToWorld(Viewport.LastMousePos);\n\t\t\t\tvar pal = wr.Palette(TileSet.TerrainPaletteInternalName);\n\n\t\t\t\tforeach (var t in power.CellsMatching(xy, footprint, dimensions))\n\t\t\t\t\tyield return new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, pal, 1f, true, true);\n\t\t\t}\n\n\t\t\tprotected override string GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi)\n\t\t\t{\n\t\t\t\treturn power.UnitsInRange(cell).Any() ? power.info.Cursor : power.info.BlockedCursor;\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":9} {"lang_cluster":"C#","source_code":"using BurningKnight.entity.component;\nusing BurningKnight.entity.creature.player;\nusing Lens.entity;\nusing VelcroPhysics.Dynamics;\n\nnamespace BurningKnight.entity.pc {\n\tpublic class Controller : Entity {\n\t\tpublic Pico Pico;\n\t\t\n\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\n\t\t\tHeight = 9;\n\n\t\t\tAddComponent(new RectBodyComponent(0, 0, Width, Height, BodyType.Static, false));\n\t\t\tAddComponent(new SensorBodyComponent(-10, -10, Width + 20, Height + 20, BodyType.Static, true));\n\t\t\tAddComponent(new InteractableComponent(Interact));\n\t\t\tAddComponent(new InteractableSliceComponent(\"props\", \"controller\"));\n\t\t\tAddComponent(new ShadowComponent());\n\t\t}\n\n\t\tprivate bool Interact(Entity e) {\n\t\t\tPico.TurnOn();\n\t\t\tPico.Entity = e;\n\t\t\t\n\t\t\te.RemoveComponent();\n\t\t\treturn true;\n\t\t}\n\t}\n}","smell_code":"\tpublic class Controller : Entity {\n\t\tpublic Pico Pico;\n\t\t\n\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\n\t\t\tHeight = 9;\n\n\t\t\tAddComponent(new RectBodyComponent(0, 0, Width, Height, BodyType.Static, false));\n\t\t\tAddComponent(new SensorBodyComponent(-10, -10, Width + 20, Height + 20, BodyType.Static, true));\n\t\t\tAddComponent(new InteractableComponent(Interact));\n\t\t\tAddComponent(new InteractableSliceComponent(\"props\", \"controller\"));\n\t\t\tAddComponent(new ShadowComponent());\n\t\t}\n\n\t\tprivate bool Interact(Entity e) {\n\t\t\tPico.TurnOn();\n\t\t\tPico.Entity = e;\n\t\t\t\n\t\t\te.RemoveComponent();\n\t\t\treturn true;\n\t\t}\n\t}","smell":"large class","id":10} {"lang_cluster":"C#","source_code":"using System.IO;\nusing System.Threading;\nusing MediaBrowser.Common.Configuration;\nusing MediaBrowser.Controller.Entities.Audio;\nusing MediaBrowser.Controller.Providers;\nusing MediaBrowser.Model.IO;\nusing MediaBrowser.XbmcMetadata.Parsers;\nusing Microsoft.Extensions.Logging;\n\nnamespace MediaBrowser.XbmcMetadata.Providers\n{\n \/\/\/ \n \/\/\/ Nfo provider for artists.\n \/\/\/ <\/summary>\n public class ArtistNfoProvider : BaseNfoProvider\n {\n private readonly ILogger _logger;\n private readonly IConfigurationManager _config;\n private readonly IProviderManager _providerManager;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The logger.<\/param>\n \/\/\/ The file system.<\/param>\n \/\/\/ the configuration manager.<\/param>\n \/\/\/ The provider manager.<\/param>\n public ArtistNfoProvider(\n IFileSystem fileSystem,\n ILogger logger,\n IConfigurationManager config,\n IProviderManager providerManager)\n : base(fileSystem)\n {\n _logger = logger;\n _config = config;\n _providerManager = providerManager;\n }\n\n \/\/\/ \n protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken)\n {\n new BaseNfoParser(_logger, _config, _providerManager).Fetch(result, path, cancellationToken);\n }\n\n \/\/\/ \n protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)\n => directoryService.GetFile(Path.Combine(info.Path, \"artist.nfo\"));\n }\n}","smell_code":" public class ArtistNfoProvider : BaseNfoProvider\n {\n private readonly ILogger _logger;\n private readonly IConfigurationManager _config;\n private readonly IProviderManager _providerManager;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The logger.<\/param>\n \/\/\/ The file system.<\/param>\n \/\/\/ the configuration manager.<\/param>\n \/\/\/ The provider manager.<\/param>\n public ArtistNfoProvider(\n IFileSystem fileSystem,\n ILogger logger,\n IConfigurationManager config,\n IProviderManager providerManager)\n : base(fileSystem)\n {\n _logger = logger;\n _config = config;\n _providerManager = providerManager;\n }\n\n \/\/\/ \n protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken)\n {\n new BaseNfoParser(_logger, _config, _providerManager).Fetch(result, path, cancellationToken);\n }\n\n \/\/\/ \n protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)\n => directoryService.GetFile(Path.Combine(info.Path, \"artist.nfo\"));\n }","smell":"large class","id":11} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing OpenRA.Mods.Common.Traits;\nusing OpenRA.Scripting;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Scripting\n{\n\t[ScriptPropertyGroup(\"Player\")]\n\tpublic class PlayerStatsProperties : ScriptPlayerProperties, Requires\n\t{\n\t\treadonly PlayerStatistics stats;\n\n\t\tpublic PlayerStatsProperties(ScriptContext context, Player player)\n\t\t\t: base(context, player)\n\t\t{\n\t\t\tstats = player.PlayerActor.Trait();\n\t\t}\n\n\t\t[Desc(\"The combined value of units killed by this player.\")]\n\t\tpublic int KillsCost { get { return stats.KillsCost; } }\n\n\t\t[Desc(\"The combined value of all units lost by this player.\")]\n\t\tpublic int DeathsCost { get { return stats.DeathsCost; } }\n\n\t\t[Desc(\"The total number of units killed by this player.\")]\n\t\tpublic int UnitsKilled { get { return stats.UnitsKilled; } }\n\n\t\t[Desc(\"The total number of units lost by this player.\")]\n\t\tpublic int UnitsLost { get { return stats.UnitsDead; } }\n\n\t\t[Desc(\"The total number of buildings killed by this player.\")]\n\t\tpublic int BuildingsKilled { get { return stats.BuildingsKilled; } }\n\n\t\t[Desc(\"The total number of buildings lost by this player.\")]\n\t\tpublic int BuildingsLost { get { return stats.BuildingsDead; } }\n\t}\n}","smell_code":"\t[ScriptPropertyGroup(\"Player\")]\n\tpublic class PlayerStatsProperties : ScriptPlayerProperties, Requires\n\t{\n\t\treadonly PlayerStatistics stats;\n\n\t\tpublic PlayerStatsProperties(ScriptContext context, Player player)\n\t\t\t: base(context, player)\n\t\t{\n\t\t\tstats = player.PlayerActor.Trait();\n\t\t}\n\n\t\t[Desc(\"The combined value of units killed by this player.\")]\n\t\tpublic int KillsCost { get { return stats.KillsCost; } }\n\n\t\t[Desc(\"The combined value of all units lost by this player.\")]\n\t\tpublic int DeathsCost { get { return stats.DeathsCost; } }\n\n\t\t[Desc(\"The total number of units killed by this player.\")]\n\t\tpublic int UnitsKilled { get { return stats.UnitsKilled; } }\n\n\t\t[Desc(\"The total number of units lost by this player.\")]\n\t\tpublic int UnitsLost { get { return stats.UnitsDead; } }\n\n\t\t[Desc(\"The total number of buildings killed by this player.\")]\n\t\tpublic int BuildingsKilled { get { return stats.BuildingsKilled; } }\n\n\t\t[Desc(\"The total number of buildings lost by this player.\")]\n\t\tpublic int BuildingsLost { get { return stats.BuildingsDead; } }\n\t}","smell":"large class","id":12} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osuTK;\nusing osu.Game.Beatmaps;\nusing osu.Game.Rulesets.Objects;\nusing osu.Game.Rulesets.Osu.Objects;\nusing System.Collections.Generic;\nusing osu.Game.Rulesets.Objects.Types;\nusing System.Linq;\nusing System.Threading;\nusing osu.Game.Rulesets.Osu.UI;\nusing osu.Framework.Extensions.IEnumerableExtensions;\n\nnamespace osu.Game.Rulesets.Osu.Beatmaps\n{\n public class OsuBeatmapConverter : BeatmapConverter\n {\n public OsuBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)\n : base(beatmap, ruleset)\n {\n }\n\n public override bool CanConvert() => Beatmap.HitObjects.All(h => h is IHasPosition);\n\n protected override IEnumerable ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken)\n {\n var positionData = original as IHasPosition;\n var comboData = original as IHasCombo;\n\n switch (original)\n {\n case IHasPathWithRepeats curveData:\n return new Slider\n {\n StartTime = original.StartTime,\n Samples = original.Samples,\n Path = curveData.Path,\n NodeSamples = curveData.NodeSamples,\n RepeatCount = curveData.RepeatCount,\n Position = positionData?.Position ?? Vector2.Zero,\n NewCombo = comboData?.NewCombo ?? false,\n ComboOffset = comboData?.ComboOffset ?? 0,\n LegacyLastTickOffset = (original as IHasLegacyLastTickOffset)?.LegacyLastTickOffset,\n \/\/ prior to v8, speed multipliers don't adjust for how many ticks are generated over the same distance.\n \/\/ this results in more (or less) ticks being generated in CreateBeatmap() => new OsuBeatmap();\n }\n}","smell_code":" public class OsuBeatmapConverter : BeatmapConverter\n {\n public OsuBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)\n : base(beatmap, ruleset)\n {\n }\n\n public override bool CanConvert() => Beatmap.HitObjects.All(h => h is IHasPosition);\n\n protected override IEnumerable ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken)\n {\n var positionData = original as IHasPosition;\n var comboData = original as IHasCombo;\n\n switch (original)\n {\n case IHasPathWithRepeats curveData:\n return new Slider\n {\n StartTime = original.StartTime,\n Samples = original.Samples,\n Path = curveData.Path,\n NodeSamples = curveData.NodeSamples,\n RepeatCount = curveData.RepeatCount,\n Position = positionData?.Position ?? Vector2.Zero,\n NewCombo = comboData?.NewCombo ?? false,\n ComboOffset = comboData?.ComboOffset ?? 0,\n LegacyLastTickOffset = (original as IHasLegacyLastTickOffset)?.LegacyLastTickOffset,\n \/\/ prior to v8, speed multipliers don't adjust for how many ticks are generated over the same distance.\n \/\/ this results in more (or less) ticks being generated in CreateBeatmap() => new OsuBeatmap();\n }","smell":"large class","id":13} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Input.Events;\nusing osuTK.Input;\nusing osuTK;\n\nnamespace osu.Game.Screens.Play\n{\n public class KeyCounterMouse : KeyCounter\n {\n public MouseButton Button { get; }\n\n public KeyCounterMouse(MouseButton button)\n : base(getStringRepresentation(button))\n {\n Button = button;\n }\n\n public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;\n\n private static string getStringRepresentation(MouseButton button)\n {\n switch (button)\n {\n default:\n return button.ToString();\n\n case MouseButton.Left:\n return @\"M1\";\n\n case MouseButton.Right:\n return @\"M2\";\n }\n }\n\n protected override bool OnMouseDown(MouseDownEvent e)\n {\n if (e.Button == Button)\n {\n IsLit = true;\n Increment();\n }\n\n return base.OnMouseDown(e);\n }\n\n protected override void OnMouseUp(MouseUpEvent e)\n {\n if (e.Button == Button) IsLit = false;\n base.OnMouseUp(e);\n }\n }\n}","smell_code":" public class KeyCounterMouse : KeyCounter\n {\n public MouseButton Button { get; }\n\n public KeyCounterMouse(MouseButton button)\n : base(getStringRepresentation(button))\n {\n Button = button;\n }\n\n public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;\n\n private static string getStringRepresentation(MouseButton button)\n {\n switch (button)\n {\n default:\n return button.ToString();\n\n case MouseButton.Left:\n return @\"M1\";\n\n case MouseButton.Right:\n return @\"M2\";\n }\n }\n\n protected override bool OnMouseDown(MouseDownEvent e)\n {\n if (e.Button == Button)\n {\n IsLit = true;\n Increment();\n }\n\n return base.OnMouseDown(e);\n }\n\n protected override void OnMouseUp(MouseUpEvent e)\n {\n if (e.Button == Button) IsLit = false;\n base.OnMouseUp(e);\n }\n }","smell":"large class","id":14} {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing MediaBrowser.Common.Configuration;\nusing Newtonsoft.Json.Linq;\n\nnamespace Jellyfin.Server.Migrations.Routines\n{\n \/\/\/ \n \/\/\/ Migration to initialize the user logging configuration file \"logging.user.json\".\n \/\/\/ If the deprecated logging.json file exists and has a custom config, it will be used as logging.user.json,\n \/\/\/ otherwise a blank file will be created.\n \/\/\/ <\/summary>\n internal class CreateUserLoggingConfigFile : IMigrationRoutine\n {\n \/\/\/ \n \/\/\/ File history for logging.json as existed during this migration creation. The contents for each has been minified.\n \/\/\/ <\/summary>\n private readonly List _defaultConfigHistory = new List\n {\n \/\/ 9a6c27947353585391e211aa88b925f81e8cd7b9\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":{\"\"Default\"\":\"\"Information\"\",\"\"Override\"\":{\"\"Microsoft\"\":\"\"Warning\"\",\"\"System\"\":\"\"Warning\"\"}},\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ 71bdcd730705a714ee208eaad7290b7c68df3885\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ a44936f97f8afc2817d3491615a7cfe1e31c251c\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}\",\n \/\/ 7af3754a11ad5a4284f107997fb5419a010ce6f3\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}]}}\",\n \/\/ 60691349a11f541958e0b2247c9abc13cb40c9fb\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}]}}\",\n \/\/ 65fe243afbcc4b596cf8726708c1965cd34b5f68\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ 96c9af590494aa8137d5a061aaf1e68feee60b67\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n };\n\n private readonly IApplicationPaths _appPaths;\n\n public CreateUserLoggingConfigFile(IApplicationPaths appPaths)\n {\n _appPaths = appPaths;\n }\n\n \/\/\/ \n public Guid Id => Guid.Parse(\"{EF103419-8451-40D8-9F34-D1A8E93A1679}\");\n\n \/\/\/ \n public string Name => \"CreateLoggingConfigHeirarchy\";\n\n \/\/\/ \n public bool PerformOnNewInstall => false;\n\n \/\/\/ \n public void Perform()\n {\n var logDirectory = _appPaths.ConfigurationDirectoryPath;\n var existingConfigPath = Path.Combine(logDirectory, \"logging.json\");\n\n \/\/ If the existing logging.json config file is unmodified, then 'reset' it by moving it to 'logging.old.json'\n \/\/ NOTE: This config file has 'reloadOnChange: true', so this change will take effect immediately even though it has already been loaded\n if (File.Exists(existingConfigPath) && ExistingConfigUnmodified(existingConfigPath))\n {\n File.Move(existingConfigPath, Path.Combine(logDirectory, \"logging.old.json\"));\n }\n }\n\n \/\/\/ \n \/\/\/ Check if the existing logging.json file has not been modified by the user by comparing it to all the\n \/\/\/ versions in our git history. Until now, the file has never been migrated after first creation so users\n \/\/\/ could have any version from the git history.\n \/\/\/ <\/summary>\n \/\/\/ does not exist or could not be read.<\/exception>\n private bool ExistingConfigUnmodified(string oldConfigPath)\n {\n var existingConfigJson = JToken.Parse(File.ReadAllText(oldConfigPath));\n return _defaultConfigHistory\n .Select(historicalConfigText => JToken.Parse(historicalConfigText))\n .Any(historicalConfigJson => JToken.DeepEquals(existingConfigJson, historicalConfigJson));\n }\n }\n}","smell_code":" internal class CreateUserLoggingConfigFile : IMigrationRoutine\n {\n \/\/\/ \n \/\/\/ File history for logging.json as existed during this migration creation. The contents for each has been minified.\n \/\/\/ <\/summary>\n private readonly List _defaultConfigHistory = new List\n {\n \/\/ 9a6c27947353585391e211aa88b925f81e8cd7b9\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":{\"\"Default\"\":\"\"Information\"\",\"\"Override\"\":{\"\"Microsoft\"\":\"\"Warning\"\",\"\"System\"\":\"\"Warning\"\"}},\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ 71bdcd730705a714ee208eaad7290b7c68df3885\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ a44936f97f8afc2817d3491615a7cfe1e31c251c\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}\",\n \/\/ 7af3754a11ad5a4284f107997fb5419a010ce6f3\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}]}}\",\n \/\/ 60691349a11f541958e0b2247c9abc13cb40c9fb\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}\"\"}}]}}]}}\",\n \/\/ 65fe243afbcc4b596cf8726708c1965cd34b5f68\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] {ThreadId} {SourceContext}: {Message:lj} {NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {ThreadId} {SourceContext}:{Message} {NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n \/\/ 96c9af590494aa8137d5a061aaf1e68feee60b67\n @\"{\"\"Serilog\"\":{\"\"MinimumLevel\"\":\"\"Information\"\",\"\"WriteTo\"\":[{\"\"Name\"\":\"\"Console\"\",\"\"Args\"\":{\"\"outputTemplate\"\":\"\"[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}\"\"}},{\"\"Name\"\":\"\"Async\"\",\"\"Args\"\":{\"\"configure\"\":[{\"\"Name\"\":\"\"File\"\",\"\"Args\"\":{\"\"path\"\":\"\"%JELLYFIN_LOG_DIR%\/\/log_.log\"\",\"\"rollingInterval\"\":\"\"Day\"\",\"\"retainedFileCountLimit\"\":3,\"\"rollOnFileSizeLimit\"\":true,\"\"fileSizeLimitBytes\"\":100000000,\"\"outputTemplate\"\":\"\"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}:{Message}{NewLine}{Exception}\"\"}}]}}],\"\"Enrich\"\":[\"\"FromLogContext\"\",\"\"WithThreadId\"\"]}}\",\n };\n\n private readonly IApplicationPaths _appPaths;\n\n public CreateUserLoggingConfigFile(IApplicationPaths appPaths)\n {\n _appPaths = appPaths;\n }\n\n \/\/\/ \n public Guid Id => Guid.Parse(\"{EF103419-8451-40D8-9F34-D1A8E93A1679}\");\n\n \/\/\/ \n public string Name => \"CreateLoggingConfigHeirarchy\";\n\n \/\/\/ \n public bool PerformOnNewInstall => false;\n\n \/\/\/ \n public void Perform()\n {\n var logDirectory = _appPaths.ConfigurationDirectoryPath;\n var existingConfigPath = Path.Combine(logDirectory, \"logging.json\");\n\n \/\/ If the existing logging.json config file is unmodified, then 'reset' it by moving it to 'logging.old.json'\n \/\/ NOTE: This config file has 'reloadOnChange: true', so this change will take effect immediately even though it has already been loaded\n if (File.Exists(existingConfigPath) && ExistingConfigUnmodified(existingConfigPath))\n {\n File.Move(existingConfigPath, Path.Combine(logDirectory, \"logging.old.json\"));\n }\n }\n\n \/\/\/ \n \/\/\/ Check if the existing logging.json file has not been modified by the user by comparing it to all the\n \/\/\/ versions in our git history. Until now, the file has never been migrated after first creation so users\n \/\/\/ could have any version from the git history.\n \/\/\/ <\/summary>\n \/\/\/ does not exist or could not be read.<\/exception>\n private bool ExistingConfigUnmodified(string oldConfigPath)\n {\n var existingConfigJson = JToken.Parse(File.ReadAllText(oldConfigPath));\n return _defaultConfigHistory\n .Select(historicalConfigText => JToken.Parse(historicalConfigText))\n .Any(historicalConfigJson => JToken.DeepEquals(existingConfigJson, historicalConfigJson));\n }\n }","smell":"large class","id":15} {"lang_cluster":"C#","source_code":"\/\/ MonoGame - Copyright (C) The MonoGame Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing SharpFont;\n\nnamespace Microsoft.Xna.Framework.Content.Pipeline.Graphics\n{\n\t\/\/ Uses FreeType to rasterize TrueType fonts into a series of glyph bitmaps.\n\tinternal class SharpFontImporter : IFontImporter\n\t{\n\t\t\/\/ Properties hold the imported font data.\n\t\tpublic IEnumerable Glyphs { get; private set; }\n\n\t\tpublic float LineSpacing { get; private set; }\n\n\t\tpublic int YOffsetMin { get; private set; }\n\n\t\t\/\/ Size of the temp surface used for GDI+ rasterization.\n\t\tconst int MaxGlyphSize = 1024;\n\n\t\tLibrary lib = null;\n\n\t\tpublic void Import(FontDescription options, string fontName)\n\t\t{\n\t\t\tlib = new Library();\n\t\t\t\/\/ Create a bunch of GDI+ objects.\n\t\t\tvar face = CreateFontFace(options, fontName);\n\t\t\ttry\n {\n\t\t\t\t\t\/\/ Which characters do we want to include?\n var characters = options.Characters;\n\n\t\t\t\t\tvar glyphList = new List();\n\t\t\t\t\t\/\/ Rasterize each character in turn.\n\t\t\t\t\tforeach (char character in characters)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar glyph = ImportGlyph(character, face);\n\t\t\t\t\t\tglyphList.Add(glyph);\n\t\t\t\t\t}\n\t\t\t\t\tGlyphs = glyphList;\n\n\t\t\t\t\t\/\/ Store the font height.\n\t\t\t\t\tLineSpacing = face.Size.Metrics.Height >> 6;\n\n\t\t\t\t\t\/\/ The height used to calculate the Y offset for each character.\n\t\t\t\t\tYOffsetMin = -face.Size.Metrics.Ascender >> 6;\n\t\t\t}\n finally\n {\n\t\t\t\tif (face != null)\n\t\t\t\t\tface.Dispose();\n\t\t\t\tif (lib != null)\n {\n\t\t\t\t\tlib.Dispose();\n\t\t\t\t\tlib = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/ Attempts to instantiate the requested GDI+ font object.\n\t\tprivate Face CreateFontFace(FontDescription options, string fontName)\n\t\t{\n\t\t\ttry\n {\n\t\t\t\tconst uint dpi = 96;\n\t\t\t\tvar face = lib.NewFace(fontName, 0);\n\t\t\t\tvar fixedSize = ((int)options.Size) << 6;\n\t\t\t\tface.SetCharSize(0, fixedSize, dpi, dpi);\n\n\t\t\t\tif (face.FamilyName == \"Microsoft Sans Serif\" && options.FontName != \"Microsoft Sans Serif\")\n\t\t\t\t\tthrow new PipelineException(string.Format(\"Font {0} is not installed on this computer.\", options.FontName));\n\n\t\t\t\treturn face;\n\n\t\t\t\t\/\/ A font substitution must have occurred.\n\t\t\t\t\/\/throw new Exception(string.Format(\"Can't find font '{0}'.\", options.FontName));\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Rasterizes a single character glyph.\n\t\tprivate Glyph ImportGlyph(char character, Face face)\n\t\t{\n\t\t\tuint glyphIndex = face.GetCharIndex(character);\n\t\t\tface.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);\n\t\t\tface.Glyph.RenderGlyph(RenderMode.Normal);\n\n\t\t\t\/\/ Render the character.\n BitmapContent glyphBitmap = null;\n\t\t\tif (face.Glyph.Bitmap.Width > 0 && face.Glyph.Bitmap.Rows > 0)\n {\n glyphBitmap = new PixelBitmapContent(face.Glyph.Bitmap.Width, face.Glyph.Bitmap.Rows);\n\t\t\t\tbyte[] gpixelAlphas = new byte[face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows];\n \/\/if the character bitmap has 1bpp we have to expand the buffer data to get the 8bpp pixel data\n \/\/each byte in bitmap.bufferdata contains the value of to 8 pixels in the row\n \/\/if bitmap is of width 10, each row has 2 bytes with 10 valid bits, and the last 6 bits of 2nd byte must be discarded\n if(face.Glyph.Bitmap.PixelMode == PixelMode.Mono)\n {\n \/\/variables needed for the expansion, amount of written data, length of the data to write\n int written = 0, length = face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows;\n for(int i = 0; written < length; i++)\n {\n \/\/width in pixels of each row\n int width = face.Glyph.Bitmap.Width;\n while(width > 0)\n {\n \/\/valid data in the current byte\n int stride = MathHelper.Min(8, width);\n \/\/copy the valid bytes to pixeldata\n \/\/System.Array.Copy(ExpandByte(face.Glyph.Bitmap.BufferData[i]), 0, gpixelAlphas, written, stride);\n ExpandByteAndCopy(face.Glyph.Bitmap.BufferData[i], stride, gpixelAlphas, written);\n written += stride;\n width -= stride;\n if(width > 0)\n i++;\n }\n }\n }\n else\n Marshal.Copy(face.Glyph.Bitmap.Buffer, gpixelAlphas, 0, gpixelAlphas.Length);\n glyphBitmap.SetPixelData(gpixelAlphas);\n\t\t\t}\n\n if (glyphBitmap == null) \n\t\t\t{\n\t\t\t\tvar gHA = face.Glyph.Metrics.HorizontalAdvance >> 6;\n\t\t\t\tvar gVA = face.Size.Metrics.Height >> 6;\n\n\t\t\t\tgHA = gHA > 0 ? gHA : gVA;\n\t\t\t\tgVA = gVA > 0 ? gVA : gHA;\n\n glyphBitmap = new PixelBitmapContent(gHA, gVA);\n\t\t\t}\n\n\t\t\t\/\/ not sure about this at all\n\t\t\tvar abc = new ABCFloat ();\n\t\t\tabc.A = face.Glyph.Metrics.HorizontalBearingX >> 6;\n\t\t\tabc.B = face.Glyph.Metrics.Width >> 6;\n\t\t\tabc.C = (face.Glyph.Metrics.HorizontalAdvance >> 6) - (abc.A + abc.B);\n\n\t\t\t\/\/ Construct the output Glyph object.\n\t\t\treturn new Glyph(character, glyphBitmap)\n\t\t\t{\n\t\t\t\tXOffset = -(face.Glyph.Advance.X >> 6),\n\t\t\t\tXAdvance = face.Glyph.Metrics.HorizontalAdvance >> 6,\n\t\t\t\tYOffset = -(face.Glyph.Metrics.HorizontalBearingY >> 6),\n\t\t\t\tCharacterWidths = abc\n\t\t\t};\n\t\t}\n\n\n \/\/\/ \n \/\/\/ Reads each individual bit of a byte from left to right and expands it to a full byte, \n \/\/\/ ones get byte.maxvalue, and zeros get byte.minvalue.\n \/\/\/ <\/summary>\n \/\/\/ Byte to expand and copy<\/param>\n \/\/\/ Number of Bits of the Byte to copy, from 1 to 8<\/param>\n \/\/\/ Byte array where to copy the results<\/param>\n \/\/\/ Position where to begin copying the results in destination<\/param>\n private static void ExpandByteAndCopy(byte origin, int length, byte[] destination, int startIndex)\n {\n byte tmp;\n for(int i = 7; i > 7 - length; i--)\n {\n tmp = (byte) (1 << i);\n if(origin \/ tmp == 1)\n {\n destination[startIndex + 7 - i] = byte.MaxValue;\n origin -= tmp;\n }\n else\n destination[startIndex + 7 - i] = byte.MinValue;\n }\n }\n }\n}","smell_code":"\tinternal class SharpFontImporter : IFontImporter\n\t{\n\t\t\/\/ Properties hold the imported font data.\n\t\tpublic IEnumerable Glyphs { get; private set; }\n\n\t\tpublic float LineSpacing { get; private set; }\n\n\t\tpublic int YOffsetMin { get; private set; }\n\n\t\t\/\/ Size of the temp surface used for GDI+ rasterization.\n\t\tconst int MaxGlyphSize = 1024;\n\n\t\tLibrary lib = null;\n\n\t\tpublic void Import(FontDescription options, string fontName)\n\t\t{\n\t\t\tlib = new Library();\n\t\t\t\/\/ Create a bunch of GDI+ objects.\n\t\t\tvar face = CreateFontFace(options, fontName);\n\t\t\ttry\n {\n\t\t\t\t\t\/\/ Which characters do we want to include?\n var characters = options.Characters;\n\n\t\t\t\t\tvar glyphList = new List();\n\t\t\t\t\t\/\/ Rasterize each character in turn.\n\t\t\t\t\tforeach (char character in characters)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar glyph = ImportGlyph(character, face);\n\t\t\t\t\t\tglyphList.Add(glyph);\n\t\t\t\t\t}\n\t\t\t\t\tGlyphs = glyphList;\n\n\t\t\t\t\t\/\/ Store the font height.\n\t\t\t\t\tLineSpacing = face.Size.Metrics.Height >> 6;\n\n\t\t\t\t\t\/\/ The height used to calculate the Y offset for each character.\n\t\t\t\t\tYOffsetMin = -face.Size.Metrics.Ascender >> 6;\n\t\t\t}\n finally\n {\n\t\t\t\tif (face != null)\n\t\t\t\t\tface.Dispose();\n\t\t\t\tif (lib != null)\n {\n\t\t\t\t\tlib.Dispose();\n\t\t\t\t\tlib = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/ Attempts to instantiate the requested GDI+ font object.\n\t\tprivate Face CreateFontFace(FontDescription options, string fontName)\n\t\t{\n\t\t\ttry\n {\n\t\t\t\tconst uint dpi = 96;\n\t\t\t\tvar face = lib.NewFace(fontName, 0);\n\t\t\t\tvar fixedSize = ((int)options.Size) << 6;\n\t\t\t\tface.SetCharSize(0, fixedSize, dpi, dpi);\n\n\t\t\t\tif (face.FamilyName == \"Microsoft Sans Serif\" && options.FontName != \"Microsoft Sans Serif\")\n\t\t\t\t\tthrow new PipelineException(string.Format(\"Font {0} is not installed on this computer.\", options.FontName));\n\n\t\t\t\treturn face;\n\n\t\t\t\t\/\/ A font substitution must have occurred.\n\t\t\t\t\/\/throw new Exception(string.Format(\"Can't find font '{0}'.\", options.FontName));\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Rasterizes a single character glyph.\n\t\tprivate Glyph ImportGlyph(char character, Face face)\n\t\t{\n\t\t\tuint glyphIndex = face.GetCharIndex(character);\n\t\t\tface.LoadGlyph(glyphIndex, LoadFlags.Default, LoadTarget.Normal);\n\t\t\tface.Glyph.RenderGlyph(RenderMode.Normal);\n\n\t\t\t\/\/ Render the character.\n BitmapContent glyphBitmap = null;\n\t\t\tif (face.Glyph.Bitmap.Width > 0 && face.Glyph.Bitmap.Rows > 0)\n {\n glyphBitmap = new PixelBitmapContent(face.Glyph.Bitmap.Width, face.Glyph.Bitmap.Rows);\n\t\t\t\tbyte[] gpixelAlphas = new byte[face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows];\n \/\/if the character bitmap has 1bpp we have to expand the buffer data to get the 8bpp pixel data\n \/\/each byte in bitmap.bufferdata contains the value of to 8 pixels in the row\n \/\/if bitmap is of width 10, each row has 2 bytes with 10 valid bits, and the last 6 bits of 2nd byte must be discarded\n if(face.Glyph.Bitmap.PixelMode == PixelMode.Mono)\n {\n \/\/variables needed for the expansion, amount of written data, length of the data to write\n int written = 0, length = face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows;\n for(int i = 0; written < length; i++)\n {\n \/\/width in pixels of each row\n int width = face.Glyph.Bitmap.Width;\n while(width > 0)\n {\n \/\/valid data in the current byte\n int stride = MathHelper.Min(8, width);\n \/\/copy the valid bytes to pixeldata\n \/\/System.Array.Copy(ExpandByte(face.Glyph.Bitmap.BufferData[i]), 0, gpixelAlphas, written, stride);\n ExpandByteAndCopy(face.Glyph.Bitmap.BufferData[i], stride, gpixelAlphas, written);\n written += stride;\n width -= stride;\n if(width > 0)\n i++;\n }\n }\n }\n else\n Marshal.Copy(face.Glyph.Bitmap.Buffer, gpixelAlphas, 0, gpixelAlphas.Length);\n glyphBitmap.SetPixelData(gpixelAlphas);\n\t\t\t}\n\n if (glyphBitmap == null) \n\t\t\t{\n\t\t\t\tvar gHA = face.Glyph.Metrics.HorizontalAdvance >> 6;\n\t\t\t\tvar gVA = face.Size.Metrics.Height >> 6;\n\n\t\t\t\tgHA = gHA > 0 ? gHA : gVA;\n\t\t\t\tgVA = gVA > 0 ? gVA : gHA;\n\n glyphBitmap = new PixelBitmapContent(gHA, gVA);\n\t\t\t}\n\n\t\t\t\/\/ not sure about this at all\n\t\t\tvar abc = new ABCFloat ();\n\t\t\tabc.A = face.Glyph.Metrics.HorizontalBearingX >> 6;\n\t\t\tabc.B = face.Glyph.Metrics.Width >> 6;\n\t\t\tabc.C = (face.Glyph.Metrics.HorizontalAdvance >> 6) - (abc.A + abc.B);\n\n\t\t\t\/\/ Construct the output Glyph object.\n\t\t\treturn new Glyph(character, glyphBitmap)\n\t\t\t{\n\t\t\t\tXOffset = -(face.Glyph.Advance.X >> 6),\n\t\t\t\tXAdvance = face.Glyph.Metrics.HorizontalAdvance >> 6,\n\t\t\t\tYOffset = -(face.Glyph.Metrics.HorizontalBearingY >> 6),\n\t\t\t\tCharacterWidths = abc\n\t\t\t};\n\t\t}\n\n\n \/\/\/ \n \/\/\/ Reads each individual bit of a byte from left to right and expands it to a full byte, \n \/\/\/ ones get byte.maxvalue, and zeros get byte.minvalue.\n \/\/\/ <\/summary>\n \/\/\/ Byte to expand and copy<\/param>\n \/\/\/ Number of Bits of the Byte to copy, from 1 to 8<\/param>\n \/\/\/ Byte array where to copy the results<\/param>\n \/\/\/ Position where to begin copying the results in destination<\/param>\n private static void ExpandByteAndCopy(byte origin, int length, byte[] destination, int startIndex)\n {\n byte tmp;\n for(int i = 7; i > 7 - length; i--)\n {\n tmp = (byte) (1 << i);\n if(origin \/ tmp == 1)\n {\n destination[startIndex + 7 - i] = byte.MaxValue;\n origin -= tmp;\n }\n else\n destination[startIndex + 7 - i] = byte.MinValue;\n }\n }\n }","smell":"large class","id":16} {"lang_cluster":"C#","source_code":"using System.IO;\nusing System.Threading;\nusing MediaBrowser.Common.Configuration;\nusing MediaBrowser.Controller.Entities.TV;\nusing MediaBrowser.Controller.Providers;\nusing MediaBrowser.Model.IO;\nusing MediaBrowser.XbmcMetadata.Parsers;\nusing Microsoft.Extensions.Logging;\n\nnamespace MediaBrowser.XbmcMetadata.Providers\n{\n \/\/\/ \n \/\/\/ Nfo provider for episodes.\n \/\/\/ <\/summary>\n public class EpisodeNfoProvider : BaseNfoProvider\n {\n private readonly ILogger _logger;\n private readonly IConfigurationManager _config;\n private readonly IProviderManager _providerManager;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The logger.<\/param>\n \/\/\/ The file system.<\/param>\n \/\/\/ the configuration manager.<\/param>\n \/\/\/ The provider manager.<\/param>\n public EpisodeNfoProvider(\n ILogger logger,\n IFileSystem fileSystem,\n IConfigurationManager config,\n IProviderManager providerManager)\n : base(fileSystem)\n {\n _logger = logger;\n _config = config;\n _providerManager = providerManager;\n }\n\n \/\/\/ \n protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken)\n {\n new EpisodeNfoParser(_logger, _config, _providerManager).Fetch(result, path, cancellationToken);\n }\n\n \/\/\/ \n protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)\n {\n var path = Path.ChangeExtension(info.Path, \".nfo\");\n\n return directoryService.GetFile(path);\n }\n }\n}","smell_code":" public class EpisodeNfoProvider : BaseNfoProvider\n {\n private readonly ILogger _logger;\n private readonly IConfigurationManager _config;\n private readonly IProviderManager _providerManager;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The logger.<\/param>\n \/\/\/ The file system.<\/param>\n \/\/\/ the configuration manager.<\/param>\n \/\/\/ The provider manager.<\/param>\n public EpisodeNfoProvider(\n ILogger logger,\n IFileSystem fileSystem,\n IConfigurationManager config,\n IProviderManager providerManager)\n : base(fileSystem)\n {\n _logger = logger;\n _config = config;\n _providerManager = providerManager;\n }\n\n \/\/\/ \n protected override void Fetch(MetadataResult result, string path, CancellationToken cancellationToken)\n {\n new EpisodeNfoParser(_logger, _config, _providerManager).Fetch(result, path, cancellationToken);\n }\n\n \/\/\/ \n protected override FileSystemMetadata GetXmlFile(ItemInfo info, IDirectoryService directoryService)\n {\n var path = Path.ChangeExtension(info.Path, \".nfo\");\n\n return directoryService.GetFile(path);\n }\n }","smell":"large class","id":17} {"lang_cluster":"C#","source_code":"\ufeffusing Avalonia.Controls;\nusing Avalonia.Markup.Xaml;\n\nnamespace Core2D.Views\n{\n public class EditorMenuView : UserControl\n {\n public EditorMenuView()\n {\n InitializeComponent();\n }\n\n private void InitializeComponent()\n {\n AvaloniaXamlLoader.Load(this);\n }\n }\n}","smell_code":" public class EditorMenuView : UserControl\n {\n public EditorMenuView()\n {\n InitializeComponent();\n }\n\n private void InitializeComponent()\n {\n AvaloniaXamlLoader.Load(this);\n }\n }","smell":"large class","id":18} {"lang_cluster":"C#","source_code":"\/\/ MonoGame - Copyright (C) The MonoGame Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\nnamespace MonoGame.Tools.Pipeline.Utilities\n{\n static class ProcessStartInfoExtensions\n {\n \/\/\/ \n \/\/\/ Modifies the FileName and Arguments to call the .NET Core App in the best way for the platform.\n \/\/\/ A different method may be chosen if the caller intends to wait for the process to exit\n \/\/\/ (e.g. choosing a .app's inner executable on Mac).\n \/\/\/ <\/summary>\n public static ProcessStartInfo ResolveDotnetApp(this ProcessStartInfo startInfo, IEnumerable searchPaths = null, bool waitForExit = false)\n {\n \/\/ Resolve the app.\n string appName = startInfo.FileName;\n searchPaths = GetSearchPaths(searchPaths);\n var (command, commandArgs) = ResolveCommand(appName, searchPaths, waitForExit);\n\n \/\/ Set the command and arguments.\n startInfo.FileName = command;\n if (commandArgs != null)\n {\n startInfo.Arguments = string.IsNullOrEmpty(startInfo.Arguments)\n ? commandArgs\n : $\"{commandArgs} {startInfo.Arguments}\";\n }\n\n return startInfo;\n }\n\n private static IEnumerable GetSearchPaths(IEnumerable extraSearchPaths)\n {\n var searchPaths = new List\n {\n Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)\n };\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n \/\/ In case we're running in the .app\/Contents\/MacOS folder, search back up in the root folder.\n \/\/ Since the dotnet assemblies can be unpacked from the app in different locations, use the process file instead.\n searchPaths.Add(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), \"..\/..\/..\/\"));\n }\n\n if (extraSearchPaths != null)\n {\n searchPaths.AddRange(extraSearchPaths);\n }\n\n return searchPaths;\n }\n\n private static (string, string) ResolveCommand(string fileName, IEnumerable searchPaths, bool waitForExit)\n {\n string appName = Path.ChangeExtension(fileName, null);\n\n string command = null;\n string commandArgs = null;\n foreach (string searchPath in searchPaths)\n {\n string testPath = Path.GetFullPath(Path.Combine(searchPath, appName));\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n string windowsTestPath = Path.ChangeExtension(testPath, \"exe\");\n if (File.Exists(windowsTestPath))\n {\n command = windowsTestPath;\n break;\n }\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string macTestPath = Path.ChangeExtension(testPath, \"app\");\n if (waitForExit)\n {\n \/\/ If waitForExit, get the executable out of the app bundle.\n macTestPath = Path.Combine(macTestPath, \"Contents\", \"MacOS\", appName);\n if (File.Exists(macTestPath))\n {\n command = macTestPath;\n break;\n }\n }\n else\n {\n \/\/ Otherwise use the .app itself.\n if (Directory.Exists(macTestPath))\n {\n command = \"open\";\n commandArgs = $\"-n \\\"{macTestPath}\\\" --args\";\n break;\n }\n }\n }\n else\n {\n string linuxTestPath = Path.ChangeExtension(testPath, null);\n if (File.Exists(linuxTestPath))\n {\n command = linuxTestPath;\n break;\n }\n }\n\n string dotnetTestPath = Path.ChangeExtension(testPath, \"dll\");\n if (File.Exists(dotnetTestPath))\n {\n command = DotNetMuxer.MuxerPathOrDefault();\n commandArgs = $\"\\\"{dotnetTestPath}\\\"\";\n break;\n }\n }\n\n if (command == null)\n {\n throw new FileNotFoundException($\"{appName} is not in the search path!\");\n }\n\n return (command, commandArgs);\n }\n\n \/\/\/ \n \/\/\/ Utilities for finding the \"dotnet.exe\" file from the currently running .NET Core application\n \/\/\/ \n \/\/\/ <\/summary>\n static class DotNetMuxer\n {\n private const string MuxerName = \"dotnet\";\n\n static DotNetMuxer()\n {\n MuxerPath = TryFindMuxerPath();\n }\n\n \/\/\/ \n \/\/\/ The full filepath to the .NET Core muxer.\n \/\/\/ <\/summary>\n public static string MuxerPath { get; }\n\n \/\/\/ \n \/\/\/ Finds the full filepath to the .NET Core muxer,\n \/\/\/ or returns a string containing the default name of the .NET Core muxer ('dotnet').\n \/\/\/ <\/summary>\n \/\/\/ The path or a string named 'dotnet'.<\/returns>\n public static string MuxerPathOrDefault() => MuxerPath ?? MuxerName;\n\n private static string TryFindMuxerPath()\n {\n var fileName = MuxerName;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n fileName += \".exe\";\n }\n\n var mainModule = Process.GetCurrentProcess().MainModule;\n if (!string.IsNullOrEmpty(mainModule?.FileName)\n && Path.GetFileName(mainModule.FileName).Equals(fileName, StringComparison.OrdinalIgnoreCase))\n {\n return mainModule.FileName;\n }\n\n return null;\n }\n }\n }\n}","smell_code":" static class ProcessStartInfoExtensions\n {\n \/\/\/ \n \/\/\/ Modifies the FileName and Arguments to call the .NET Core App in the best way for the platform.\n \/\/\/ A different method may be chosen if the caller intends to wait for the process to exit\n \/\/\/ (e.g. choosing a .app's inner executable on Mac).\n \/\/\/ <\/summary>\n public static ProcessStartInfo ResolveDotnetApp(this ProcessStartInfo startInfo, IEnumerable searchPaths = null, bool waitForExit = false)\n {\n \/\/ Resolve the app.\n string appName = startInfo.FileName;\n searchPaths = GetSearchPaths(searchPaths);\n var (command, commandArgs) = ResolveCommand(appName, searchPaths, waitForExit);\n\n \/\/ Set the command and arguments.\n startInfo.FileName = command;\n if (commandArgs != null)\n {\n startInfo.Arguments = string.IsNullOrEmpty(startInfo.Arguments)\n ? commandArgs\n : $\"{commandArgs} {startInfo.Arguments}\";\n }\n\n return startInfo;\n }\n\n private static IEnumerable GetSearchPaths(IEnumerable extraSearchPaths)\n {\n var searchPaths = new List\n {\n Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)\n };\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n \/\/ In case we're running in the .app\/Contents\/MacOS folder, search back up in the root folder.\n \/\/ Since the dotnet assemblies can be unpacked from the app in different locations, use the process file instead.\n searchPaths.Add(Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), \"..\/..\/..\/\"));\n }\n\n if (extraSearchPaths != null)\n {\n searchPaths.AddRange(extraSearchPaths);\n }\n\n return searchPaths;\n }\n\n private static (string, string) ResolveCommand(string fileName, IEnumerable searchPaths, bool waitForExit)\n {\n string appName = Path.ChangeExtension(fileName, null);\n\n string command = null;\n string commandArgs = null;\n foreach (string searchPath in searchPaths)\n {\n string testPath = Path.GetFullPath(Path.Combine(searchPath, appName));\n\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n string windowsTestPath = Path.ChangeExtension(testPath, \"exe\");\n if (File.Exists(windowsTestPath))\n {\n command = windowsTestPath;\n break;\n }\n }\n else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))\n {\n string macTestPath = Path.ChangeExtension(testPath, \"app\");\n if (waitForExit)\n {\n \/\/ If waitForExit, get the executable out of the app bundle.\n macTestPath = Path.Combine(macTestPath, \"Contents\", \"MacOS\", appName);\n if (File.Exists(macTestPath))\n {\n command = macTestPath;\n break;\n }\n }\n else\n {\n \/\/ Otherwise use the .app itself.\n if (Directory.Exists(macTestPath))\n {\n command = \"open\";\n commandArgs = $\"-n \\\"{macTestPath}\\\" --args\";\n break;\n }\n }\n }\n else\n {\n string linuxTestPath = Path.ChangeExtension(testPath, null);\n if (File.Exists(linuxTestPath))\n {\n command = linuxTestPath;\n break;\n }\n }\n\n string dotnetTestPath = Path.ChangeExtension(testPath, \"dll\");\n if (File.Exists(dotnetTestPath))\n {\n command = DotNetMuxer.MuxerPathOrDefault();\n commandArgs = $\"\\\"{dotnetTestPath}\\\"\";\n break;\n }\n }\n\n if (command == null)\n {\n throw new FileNotFoundException($\"{appName} is not in the search path!\");\n }\n\n return (command, commandArgs);\n }\n\n \/\/\/ \n \/\/\/ Utilities for finding the \"dotnet.exe\" file from the currently running .NET Core application\n \/\/\/ \n \/\/\/ <\/summary>\n static class DotNetMuxer\n {\n private const string MuxerName = \"dotnet\";\n\n static DotNetMuxer()\n {\n MuxerPath = TryFindMuxerPath();\n }\n\n \/\/\/ \n \/\/\/ The full filepath to the .NET Core muxer.\n \/\/\/ <\/summary>\n public static string MuxerPath { get; }\n\n \/\/\/ \n \/\/\/ Finds the full filepath to the .NET Core muxer,\n \/\/\/ or returns a string containing the default name of the .NET Core muxer ('dotnet').\n \/\/\/ <\/summary>\n \/\/\/ The path or a string named 'dotnet'.<\/returns>\n public static string MuxerPathOrDefault() => MuxerPath ?? MuxerName;\n\n private static string TryFindMuxerPath()\n {\n var fileName = MuxerName;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))\n {\n fileName += \".exe\";\n }\n\n var mainModule = Process.GetCurrentProcess().MainModule;\n if (!string.IsNullOrEmpty(mainModule?.FileName)\n && Path.GetFileName(mainModule.FileName).Equals(fileName, StringComparison.OrdinalIgnoreCase))\n {\n return mainModule.FileName;\n }\n\n return null;\n }\n }\n }","smell":"large class","id":19} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Rulesets.Objects.Drawables;\nusing osu.Game.Rulesets.Osu.Objects;\nusing osu.Game.Rulesets.Osu.Objects.Drawables;\nusing osuTK;\nusing osuTK.Graphics;\n\nnamespace osu.Game.Rulesets.Osu.Skinning.Default\n{\n public class MainCirclePiece : CompositeDrawable\n {\n private readonly CirclePiece circle;\n private readonly RingPiece ring;\n private readonly FlashPiece flash;\n private readonly ExplodePiece explode;\n private readonly NumberPiece number;\n private readonly GlowPiece glow;\n\n public MainCirclePiece()\n {\n Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);\n\n Anchor = Anchor.Centre;\n Origin = Anchor.Centre;\n\n InternalChildren = new Drawable[]\n {\n glow = new GlowPiece(),\n circle = new CirclePiece(),\n number = new NumberPiece(),\n ring = new RingPiece(),\n flash = new FlashPiece(),\n explode = new ExplodePiece(),\n };\n }\n\n private readonly IBindable accentColour = new Bindable();\n private readonly IBindable indexInCurrentCombo = new Bindable();\n\n [Resolved]\n private DrawableHitObject drawableObject { get; set; }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n var drawableOsuObject = (DrawableOsuHitObject)drawableObject;\n\n accentColour.BindTo(drawableObject.AccentColour);\n indexInCurrentCombo.BindTo(drawableOsuObject.IndexInCurrentComboBindable);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n accentColour.BindValueChanged(colour =>\n {\n explode.Colour = colour.NewValue;\n glow.Colour = colour.NewValue;\n circle.Colour = colour.NewValue;\n }, true);\n\n indexInCurrentCombo.BindValueChanged(index => number.Text = (index.NewValue + 1).ToString(), true);\n\n drawableObject.ApplyCustomUpdateState += updateState;\n updateState(drawableObject, drawableObject.State.Value);\n }\n\n private void updateState(DrawableHitObject drawableObject, ArmedState state)\n {\n using (BeginAbsoluteSequence(drawableObject.HitStateUpdateTime, true))\n {\n glow.FadeOut(400);\n\n switch (state)\n {\n case ArmedState.Hit:\n const double flash_in = 40;\n const double flash_out = 100;\n\n flash.FadeTo(0.8f, flash_in)\n .Then()\n .FadeOut(flash_out);\n\n explode.FadeIn(flash_in);\n this.ScaleTo(1.5f, 400, Easing.OutQuad);\n\n using (BeginDelayedSequence(flash_in, true))\n {\n \/\/ after the flash, we can hide some elements that were behind it\n ring.FadeOut();\n circle.FadeOut();\n number.FadeOut();\n\n this.FadeOut(800);\n }\n\n break;\n }\n }\n }\n }\n}","smell_code":" public class MainCirclePiece : CompositeDrawable\n {\n private readonly CirclePiece circle;\n private readonly RingPiece ring;\n private readonly FlashPiece flash;\n private readonly ExplodePiece explode;\n private readonly NumberPiece number;\n private readonly GlowPiece glow;\n\n public MainCirclePiece()\n {\n Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);\n\n Anchor = Anchor.Centre;\n Origin = Anchor.Centre;\n\n InternalChildren = new Drawable[]\n {\n glow = new GlowPiece(),\n circle = new CirclePiece(),\n number = new NumberPiece(),\n ring = new RingPiece(),\n flash = new FlashPiece(),\n explode = new ExplodePiece(),\n };\n }\n\n private readonly IBindable accentColour = new Bindable();\n private readonly IBindable indexInCurrentCombo = new Bindable();\n\n [Resolved]\n private DrawableHitObject drawableObject { get; set; }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n var drawableOsuObject = (DrawableOsuHitObject)drawableObject;\n\n accentColour.BindTo(drawableObject.AccentColour);\n indexInCurrentCombo.BindTo(drawableOsuObject.IndexInCurrentComboBindable);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n accentColour.BindValueChanged(colour =>\n {\n explode.Colour = colour.NewValue;\n glow.Colour = colour.NewValue;\n circle.Colour = colour.NewValue;\n }, true);\n\n indexInCurrentCombo.BindValueChanged(index => number.Text = (index.NewValue + 1).ToString(), true);\n\n drawableObject.ApplyCustomUpdateState += updateState;\n updateState(drawableObject, drawableObject.State.Value);\n }\n\n private void updateState(DrawableHitObject drawableObject, ArmedState state)\n {\n using (BeginAbsoluteSequence(drawableObject.HitStateUpdateTime, true))\n {\n glow.FadeOut(400);\n\n switch (state)\n {\n case ArmedState.Hit:\n const double flash_in = 40;\n const double flash_out = 100;\n\n flash.FadeTo(0.8f, flash_in)\n .Then()\n .FadeOut(flash_out);\n\n explode.FadeIn(flash_in);\n this.ScaleTo(1.5f, 400, Easing.OutQuad);\n\n using (BeginDelayedSequence(flash_in, true))\n {\n \/\/ after the flash, we can hide some elements that were behind it\n ring.FadeOut();\n circle.FadeOut();\n number.FadeOut();\n\n this.FadeOut(800);\n }\n\n break;\n }\n }\n }\n }","smell":"large class","id":20} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Game.Configuration;\nusing osu.Game.Graphics.Sprites;\n\nnamespace osu.Game.Screens.Play.PlayerSettings\n{\n public class VisualSettings : PlayerSettingsGroup\n {\n private readonly PlayerSliderBar dimSliderBar;\n private readonly PlayerSliderBar blurSliderBar;\n private readonly PlayerCheckbox showStoryboardToggle;\n private readonly PlayerCheckbox beatmapSkinsToggle;\n private readonly PlayerCheckbox beatmapColorsToggle;\n private readonly PlayerCheckbox beatmapHitsoundsToggle;\n\n public VisualSettings()\n : base(\"Visual Settings\")\n {\n Children = new Drawable[]\n {\n new OsuSpriteText\n {\n Text = \"Background dim:\"\n },\n dimSliderBar = new PlayerSliderBar\n {\n DisplayAsPercentage = true\n },\n new OsuSpriteText\n {\n Text = \"Background blur:\"\n },\n blurSliderBar = new PlayerSliderBar\n {\n DisplayAsPercentage = true\n },\n new OsuSpriteText\n {\n Text = \"Toggles:\"\n },\n showStoryboardToggle = new PlayerCheckbox { LabelText = \"Storyboard \/ Video\" },\n beatmapSkinsToggle = new PlayerCheckbox { LabelText = \"Beatmap skins\" },\n beatmapColorsToggle = new PlayerCheckbox { LabelText = \"Beatmap colours\" },\n beatmapHitsoundsToggle = new PlayerCheckbox { LabelText = \"Beatmap hitsounds\" }\n };\n }\n\n [BackgroundDependencyLoader]\n private void load(OsuConfigManager config)\n {\n dimSliderBar.Current = config.GetBindable(OsuSetting.DimLevel);\n blurSliderBar.Current = config.GetBindable(OsuSetting.BlurLevel);\n showStoryboardToggle.Current = config.GetBindable(OsuSetting.ShowStoryboard);\n beatmapSkinsToggle.Current = config.GetBindable(OsuSetting.BeatmapSkins);\n beatmapColorsToggle.Current = config.GetBindable(OsuSetting.BeatmapColours);\n beatmapHitsoundsToggle.Current = config.GetBindable(OsuSetting.BeatmapHitsounds);\n }\n }\n}","smell_code":" public class VisualSettings : PlayerSettingsGroup\n {\n private readonly PlayerSliderBar dimSliderBar;\n private readonly PlayerSliderBar blurSliderBar;\n private readonly PlayerCheckbox showStoryboardToggle;\n private readonly PlayerCheckbox beatmapSkinsToggle;\n private readonly PlayerCheckbox beatmapColorsToggle;\n private readonly PlayerCheckbox beatmapHitsoundsToggle;\n\n public VisualSettings()\n : base(\"Visual Settings\")\n {\n Children = new Drawable[]\n {\n new OsuSpriteText\n {\n Text = \"Background dim:\"\n },\n dimSliderBar = new PlayerSliderBar\n {\n DisplayAsPercentage = true\n },\n new OsuSpriteText\n {\n Text = \"Background blur:\"\n },\n blurSliderBar = new PlayerSliderBar\n {\n DisplayAsPercentage = true\n },\n new OsuSpriteText\n {\n Text = \"Toggles:\"\n },\n showStoryboardToggle = new PlayerCheckbox { LabelText = \"Storyboard \/ Video\" },\n beatmapSkinsToggle = new PlayerCheckbox { LabelText = \"Beatmap skins\" },\n beatmapColorsToggle = new PlayerCheckbox { LabelText = \"Beatmap colours\" },\n beatmapHitsoundsToggle = new PlayerCheckbox { LabelText = \"Beatmap hitsounds\" }\n };\n }\n\n [BackgroundDependencyLoader]\n private void load(OsuConfigManager config)\n {\n dimSliderBar.Current = config.GetBindable(OsuSetting.DimLevel);\n blurSliderBar.Current = config.GetBindable(OsuSetting.BlurLevel);\n showStoryboardToggle.Current = config.GetBindable(OsuSetting.ShowStoryboard);\n beatmapSkinsToggle.Current = config.GetBindable(OsuSetting.BeatmapSkins);\n beatmapColorsToggle.Current = config.GetBindable(OsuSetting.BeatmapColours);\n beatmapHitsoundsToggle.Current = config.GetBindable(OsuSetting.BeatmapHitsounds);\n }\n }","smell":"large class","id":21} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Collections.Generic;\nusing OpenRA.Support;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t\/\/\/ Use as base class for *Info to subclass of ConditionalTrait. (See ConditionalTrait.)<\/summary>\n\tpublic abstract class ConditionalTraitInfo : TraitInfo, IObservesVariablesInfo, IRulesetLoaded\n\t{\n\t\t[ConsumedConditionReference]\n\t\t[Desc(\"Boolean expression defining the condition to enable this trait.\")]\n\t\tpublic readonly BooleanExpression RequiresCondition = null;\n\n\t\t\/\/ HACK: A shim for all the ActorPreview code that used to query UpgradeMinEnabledLevel directly\n\t\t\/\/ This can go away after we introduce an InitialConditions ActorInit and have the traits query the\n\t\t\/\/ condition directly\n\t\tpublic bool EnabledByDefault { get; private set; }\n\n\t\tpublic virtual void RulesetLoaded(Ruleset rules, ActorInfo ai)\n\t\t{\n\t\t\tEnabledByDefault = RequiresCondition == null || RequiresCondition.Evaluate(VariableExpression.NoVariables);\n\t\t}\n\t}\n\n\t\/\/\/ \n\t\/\/\/ Abstract base for enabling and disabling trait using conditions.\n\t\/\/\/ Requires basing *Info on ConditionalTraitInfo and using base(info) constructor.\n\t\/\/\/ TraitEnabled will be called at creation if the trait starts enabled or does not use conditions.\n\t\/\/\/ <\/summary>\n\tpublic abstract class ConditionalTrait : IObservesVariables, IDisabledTrait, INotifyCreated, ISync where InfoType : ConditionalTraitInfo\n\t{\n\t\tpublic readonly InfoType Info;\n\n\t\t\/\/ Overrides must call `base.GetVariableObservers()` to avoid breaking RequiresCondition.\n\t\tpublic virtual IEnumerable GetVariableObservers()\n\t\t{\n\t\t\tif (Info.RequiresCondition != null)\n\t\t\t\tyield return new VariableObserver(RequiredConditionsChanged, Info.RequiresCondition.Variables);\n\t\t}\n\n\t\t[Sync]\n\t\tpublic bool IsTraitDisabled { get; private set; }\n\n\t\tpublic ConditionalTrait(InfoType info)\n\t\t{\n\t\t\tInfo = info;\n\n\t\t\t\/\/ Conditional traits will be enabled (if appropriate) by the ConditionManager\n\t\t\t\/\/ calling ConditionConsumers at the end of INotifyCreated.\n\t\t\tIsTraitDisabled = Info.RequiresCondition != null;\n\t\t}\n\n\t\tprotected virtual void Created(Actor self)\n\t\t{\n\t\t\tif (Info.RequiresCondition == null)\n\t\t\t\tTraitEnabled(self);\n\t\t}\n\n\t\tvoid INotifyCreated.Created(Actor self) { Created(self); }\n\n\t\tvoid RequiredConditionsChanged(Actor self, IReadOnlyDictionary conditions)\n\t\t{\n\t\t\tif (Info.RequiresCondition == null)\n\t\t\t\treturn;\n\n\t\t\tvar wasDisabled = IsTraitDisabled;\n\t\t\tIsTraitDisabled = !Info.RequiresCondition.Evaluate(conditions);\n\n\t\t\tif (IsTraitDisabled != wasDisabled)\n\t\t\t{\n\t\t\t\tif (wasDisabled)\n\t\t\t\t\tTraitEnabled(self);\n\t\t\t\telse\n\t\t\t\t\tTraitDisabled(self);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Subclasses can add condition support by querying IsTraitDisabled and\/or overriding these methods.\n\t\tprotected virtual void TraitEnabled(Actor self) { }\n\t\tprotected virtual void TraitDisabled(Actor self) { }\n\t}\n}","smell_code":"\tpublic abstract class ConditionalTraitInfo : TraitInfo, IObservesVariablesInfo, IRulesetLoaded\n\t{\n\t\t[ConsumedConditionReference]\n\t\t[Desc(\"Boolean expression defining the condition to enable this trait.\")]\n\t\tpublic readonly BooleanExpression RequiresCondition = null;\n\n\t\t\/\/ HACK: A shim for all the ActorPreview code that used to query UpgradeMinEnabledLevel directly\n\t\t\/\/ This can go away after we introduce an InitialConditions ActorInit and have the traits query the\n\t\t\/\/ condition directly\n\t\tpublic bool EnabledByDefault { get; private set; }\n\n\t\tpublic virtual void RulesetLoaded(Ruleset rules, ActorInfo ai)\n\t\t{\n\t\t\tEnabledByDefault = RequiresCondition == null || RequiresCondition.Evaluate(VariableExpression.NoVariables);\n\t\t}\n\t}","smell":"large class","id":22} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Game.Beatmaps;\nusing osu.Game.Beatmaps.ControlPoints;\nusing osu.Game.Rulesets.Judgements;\nusing osu.Game.Rulesets.Osu.Judgements;\nusing osu.Game.Rulesets.Scoring;\n\nnamespace osu.Game.Rulesets.Osu.Objects\n{\n public class SliderTick : OsuHitObject\n {\n public int SpanIndex { get; set; }\n public double SpanStartTime { get; set; }\n\n protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)\n {\n base.ApplyDefaultsToSelf(controlPointInfo, difficulty);\n\n double offset;\n\n if (SpanIndex > 0)\n \/\/ Adding 200 to include the offset stable used.\n \/\/ This is so on repeats ticks don't appear too late to be visually processed by the player.\n offset = 200;\n else\n offset = TimeFadeIn * 0.66f;\n\n TimePreempt = (StartTime - SpanStartTime) \/ 2 + offset;\n }\n\n protected override HitWindows CreateHitWindows() => HitWindows.Empty;\n\n public override Judgement CreateJudgement() => new SliderTickJudgement();\n\n public class SliderTickJudgement : OsuJudgement\n {\n public override HitResult MaxResult => HitResult.LargeTickHit;\n }\n }\n}","smell_code":" public class SliderTick : OsuHitObject\n {\n public int SpanIndex { get; set; }\n public double SpanStartTime { get; set; }\n\n protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)\n {\n base.ApplyDefaultsToSelf(controlPointInfo, difficulty);\n\n double offset;\n\n if (SpanIndex > 0)\n \/\/ Adding 200 to include the offset stable used.\n \/\/ This is so on repeats ticks don't appear too late to be visually processed by the player.\n offset = 200;\n else\n offset = TimeFadeIn * 0.66f;\n\n TimePreempt = (StartTime - SpanStartTime) \/ 2 + offset;\n }\n\n protected override HitWindows CreateHitWindows() => HitWindows.Empty;\n\n public override Judgement CreateJudgement() => new SliderTickJudgement();\n\n public class SliderTickJudgement : OsuJudgement\n {\n public override HitResult MaxResult => HitResult.LargeTickHit;\n }\n }","smell":"large class","id":23} {"lang_cluster":"C#","source_code":"#nullable disable\nusing MediaBrowser.Model.Dto;\nusing MediaBrowser.Model.Entities;\n\nnamespace MediaBrowser.Model.Providers\n{\n \/\/\/ \n \/\/\/ Class RemoteImageInfo.\n \/\/\/ <\/summary>\n public class RemoteImageInfo\n {\n \/\/\/ \n \/\/\/ Gets or sets the name of the provider.\n \/\/\/ <\/summary>\n \/\/\/ The name of the provider.<\/value>\n public string ProviderName { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the URL.\n \/\/\/ <\/summary>\n \/\/\/ The URL.<\/value>\n public string Url { get; set; }\n\n \/\/\/ \n \/\/\/ Gets a url used for previewing a smaller version.\n \/\/\/ <\/summary>\n public string ThumbnailUrl { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the height.\n \/\/\/ <\/summary>\n \/\/\/ The height.<\/value>\n public int? Height { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the width.\n \/\/\/ <\/summary>\n \/\/\/ The width.<\/value>\n public int? Width { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the community rating.\n \/\/\/ <\/summary>\n \/\/\/ The community rating.<\/value>\n public double? CommunityRating { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the vote count.\n \/\/\/ <\/summary>\n \/\/\/ The vote count.<\/value>\n public int? VoteCount { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the language.\n \/\/\/ <\/summary>\n \/\/\/ The language.<\/value>\n public string Language { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type.\n \/\/\/ <\/summary>\n \/\/\/ The type.<\/value>\n public ImageType Type { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type of the rating.\n \/\/\/ <\/summary>\n \/\/\/ The type of the rating.<\/value>\n public RatingType RatingType { get; set; }\n }\n}","smell_code":" public class RemoteImageInfo\n {\n \/\/\/ \n \/\/\/ Gets or sets the name of the provider.\n \/\/\/ <\/summary>\n \/\/\/ The name of the provider.<\/value>\n public string ProviderName { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the URL.\n \/\/\/ <\/summary>\n \/\/\/ The URL.<\/value>\n public string Url { get; set; }\n\n \/\/\/ \n \/\/\/ Gets a url used for previewing a smaller version.\n \/\/\/ <\/summary>\n public string ThumbnailUrl { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the height.\n \/\/\/ <\/summary>\n \/\/\/ The height.<\/value>\n public int? Height { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the width.\n \/\/\/ <\/summary>\n \/\/\/ The width.<\/value>\n public int? Width { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the community rating.\n \/\/\/ <\/summary>\n \/\/\/ The community rating.<\/value>\n public double? CommunityRating { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the vote count.\n \/\/\/ <\/summary>\n \/\/\/ The vote count.<\/value>\n public int? VoteCount { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the language.\n \/\/\/ <\/summary>\n \/\/\/ The language.<\/value>\n public string Language { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type.\n \/\/\/ <\/summary>\n \/\/\/ The type.<\/value>\n public ImageType Type { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type of the rating.\n \/\/\/ <\/summary>\n \/\/\/ The type of the rating.<\/value>\n public RatingType RatingType { get; set; }\n }","smell":"large class","id":24} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Diagnostics;\nusing osu.Game.Rulesets.Scoring;\n\nnamespace osu.Game.Rulesets.Mania.Objects.Drawables\n{\n \/\/\/ \n \/\/\/ The tail of a .\n \/\/\/ <\/summary>\n public class DrawableHoldNoteTail : DrawableNote\n {\n \/\/\/ \n \/\/\/ Lenience of release hit windows. This is to make cases where the hold note release\n \/\/\/ is timed alongside presses of other hit objects less awkward.\n \/\/\/ Todo: This shouldn't exist for non-LegacyBeatmapDecoder beatmaps\n \/\/\/ <\/summary>\n private const double release_window_lenience = 1.5;\n\n protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteTail;\n\n private readonly DrawableHoldNote holdNote;\n\n public DrawableHoldNoteTail(DrawableHoldNote holdNote)\n : base(holdNote.HitObject.Tail)\n {\n this.holdNote = holdNote;\n }\n\n public void UpdateResult() => base.UpdateResult(true);\n\n protected override double MaximumJudgementOffset => base.MaximumJudgementOffset * release_window_lenience;\n\n protected override void CheckForResult(bool userTriggered, double timeOffset)\n {\n Debug.Assert(HitObject.HitWindows != null);\n\n \/\/ Factor in the release lenience\n timeOffset \/= release_window_lenience;\n\n if (!userTriggered)\n {\n if (!HitObject.HitWindows.CanBeHit(timeOffset))\n ApplyResult(r => r.Type = r.Judgement.MinResult);\n\n return;\n }\n\n var result = HitObject.HitWindows.ResultFor(timeOffset);\n if (result == HitResult.None)\n return;\n\n ApplyResult(r =>\n {\n \/\/ If the head wasn't hit or the hold note was broken, cap the max score to Meh.\n if (result > HitResult.Meh && (!holdNote.Head.IsHit || holdNote.HoldBrokenTime != null))\n result = HitResult.Meh;\n\n r.Type = result;\n });\n }\n\n public override bool OnPressed(ManiaAction action) => false; \/\/ Handled by the hold note\n\n public override void OnReleased(ManiaAction action)\n {\n }\n }\n}","smell_code":" public class DrawableHoldNoteTail : DrawableNote\n {\n \/\/\/ \n \/\/\/ Lenience of release hit windows. This is to make cases where the hold note release\n \/\/\/ is timed alongside presses of other hit objects less awkward.\n \/\/\/ Todo: This shouldn't exist for non-LegacyBeatmapDecoder beatmaps\n \/\/\/ <\/summary>\n private const double release_window_lenience = 1.5;\n\n protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteTail;\n\n private readonly DrawableHoldNote holdNote;\n\n public DrawableHoldNoteTail(DrawableHoldNote holdNote)\n : base(holdNote.HitObject.Tail)\n {\n this.holdNote = holdNote;\n }\n\n public void UpdateResult() => base.UpdateResult(true);\n\n protected override double MaximumJudgementOffset => base.MaximumJudgementOffset * release_window_lenience;\n\n protected override void CheckForResult(bool userTriggered, double timeOffset)\n {\n Debug.Assert(HitObject.HitWindows != null);\n\n \/\/ Factor in the release lenience\n timeOffset \/= release_window_lenience;\n\n if (!userTriggered)\n {\n if (!HitObject.HitWindows.CanBeHit(timeOffset))\n ApplyResult(r => r.Type = r.Judgement.MinResult);\n\n return;\n }\n\n var result = HitObject.HitWindows.ResultFor(timeOffset);\n if (result == HitResult.None)\n return;\n\n ApplyResult(r =>\n {\n \/\/ If the head wasn't hit or the hold note was broken, cap the max score to Meh.\n if (result > HitResult.Meh && (!holdNote.Head.IsHit || holdNote.HoldBrokenTime != null))\n result = HitResult.Meh;\n\n r.Type = result;\n });\n }\n\n public override bool OnPressed(ManiaAction action) => false; \/\/ Handled by the hold note\n\n public override void OnReleased(ManiaAction action)\n {\n }\n }","smell":"large class","id":25} {"lang_cluster":"C#","source_code":"using Lens.entity;\n\nnamespace BurningKnight.entity.events {\n\tpublic class SaveStartedEvent : Event {\n\t\t\n\t}\n}","smell_code":"\tpublic class SaveStartedEvent : Event {\n\t\t\n\t}","smell":"large class","id":26} {"lang_cluster":"C#","source_code":"\ufeff\/\/ MonoGame - Copyright (C) The MonoGame Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing Microsoft.Xna.Framework.Graphics;\n\nnamespace Microsoft.Xna.Framework.Content.Pipeline.Graphics\n{\n public class AlphaTestMaterialContent : MaterialContent\n {\n public const string AlphaKey = \"Alpha\";\n public const string AlphaFunctionKey = \"AlphaFunction\";\n public const string DiffuseColorKey = \"DiffuseColor\";\n public const string ReferenceAlphaKey = \"ReferenceAlpha\";\n public const string TextureKey = \"Texture\";\n public const string VertexColorEnabledKey = \"VertexColorEnabled\";\n\n public float? Alpha\n {\n get { return GetValueTypeProperty(AlphaKey); }\n set { SetProperty(AlphaKey, value); }\n }\n \n public CompareFunction? AlphaFunction\n {\n get { return GetValueTypeProperty(AlphaFunctionKey); }\n set { SetProperty(AlphaFunctionKey, value); }\n }\n\n public Vector3? DiffuseColor\n {\n get { return GetValueTypeProperty(DiffuseColorKey); }\n set { SetProperty(DiffuseColorKey, value); }\n }\n\n public int? ReferenceAlpha\n {\n get { return GetValueTypeProperty(ReferenceAlphaKey); }\n set { SetProperty(ReferenceAlphaKey, value); }\n }\n\n public ExternalReference Texture\n {\n get { return GetTexture(TextureKey); }\n set { SetTexture(TextureKey, value); }\n }\n\n public bool? VertexColorEnabled\n {\n get { return GetValueTypeProperty(VertexColorEnabledKey); }\n set { SetProperty(VertexColorEnabledKey, value); }\n }\n }\n}","smell_code":" public class AlphaTestMaterialContent : MaterialContent\n {\n public const string AlphaKey = \"Alpha\";\n public const string AlphaFunctionKey = \"AlphaFunction\";\n public const string DiffuseColorKey = \"DiffuseColor\";\n public const string ReferenceAlphaKey = \"ReferenceAlpha\";\n public const string TextureKey = \"Texture\";\n public const string VertexColorEnabledKey = \"VertexColorEnabled\";\n\n public float? Alpha\n {\n get { return GetValueTypeProperty(AlphaKey); }\n set { SetProperty(AlphaKey, value); }\n }\n \n public CompareFunction? AlphaFunction\n {\n get { return GetValueTypeProperty(AlphaFunctionKey); }\n set { SetProperty(AlphaFunctionKey, value); }\n }\n\n public Vector3? DiffuseColor\n {\n get { return GetValueTypeProperty(DiffuseColorKey); }\n set { SetProperty(DiffuseColorKey, value); }\n }\n\n public int? ReferenceAlpha\n {\n get { return GetValueTypeProperty(ReferenceAlphaKey); }\n set { SetProperty(ReferenceAlphaKey, value); }\n }\n\n public ExternalReference Texture\n {\n get { return GetTexture(TextureKey); }\n set { SetTexture(TextureKey, value); }\n }\n\n public bool? VertexColorEnabled\n {\n get { return GetValueTypeProperty(VertexColorEnabledKey); }\n set { SetProperty(VertexColorEnabledKey, value); }\n }\n }","smell":"large class","id":27} {"lang_cluster":"C#","source_code":"#pragma warning disable CS1591\n\nusing System;\nusing System.Collections.Generic;\nusing System.Xml;\nusing Emby.Dlna.Service;\nusing MediaBrowser.Common.Extensions;\nusing MediaBrowser.Controller.Configuration;\nusing MediaBrowser.Model.Dlna;\nusing Microsoft.Extensions.Logging;\n\nnamespace Emby.Dlna.ConnectionManager\n{\n \/\/\/ \n \/\/\/ Defines the .\n \/\/\/ <\/summary>\n public class ControlHandler : BaseControlHandler\n {\n private readonly DeviceProfile _profile;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The for use with the instance.<\/param>\n \/\/\/ The for use with the instance.<\/param>\n \/\/\/ The for use with the instance.<\/param>\n public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile)\n : base(config, logger)\n {\n _profile = profile;\n }\n\n \/\/\/ \n protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter)\n {\n if (string.Equals(methodName, \"GetProtocolInfo\", StringComparison.OrdinalIgnoreCase))\n {\n HandleGetProtocolInfo(xmlWriter);\n return;\n }\n\n throw new ResourceNotFoundException(\"Unexpected control request name: \" + methodName);\n }\n\n \/\/\/ \n \/\/\/ Builds the response to the GetProtocolInfo request.\n \/\/\/ <\/summary>\n \/\/\/ The .<\/param>\n private void HandleGetProtocolInfo(XmlWriter xmlWriter)\n {\n xmlWriter.WriteElementString(\"Source\", _profile.ProtocolInfo);\n xmlWriter.WriteElementString(\"Sink\", string.Empty);\n }\n }\n}","smell_code":" public class ControlHandler : BaseControlHandler\n {\n private readonly DeviceProfile _profile;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ The for use with the instance.<\/param>\n \/\/\/ The for use with the instance.<\/param>\n \/\/\/ The for use with the instance.<\/param>\n public ControlHandler(IServerConfigurationManager config, ILogger logger, DeviceProfile profile)\n : base(config, logger)\n {\n _profile = profile;\n }\n\n \/\/\/ \n protected override void WriteResult(string methodName, IDictionary methodParams, XmlWriter xmlWriter)\n {\n if (string.Equals(methodName, \"GetProtocolInfo\", StringComparison.OrdinalIgnoreCase))\n {\n HandleGetProtocolInfo(xmlWriter);\n return;\n }\n\n throw new ResourceNotFoundException(\"Unexpected control request name: \" + methodName);\n }\n\n \/\/\/ \n \/\/\/ Builds the response to the GetProtocolInfo request.\n \/\/\/ <\/summary>\n \/\/\/ The .<\/param>\n private void HandleGetProtocolInfo(XmlWriter xmlWriter)\n {\n xmlWriter.WriteElementString(\"Source\", _profile.ProtocolInfo);\n xmlWriter.WriteElementString(\"Sink\", string.Empty);\n }\n }","smell":"large class","id":28} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Collections.Generic;\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Online.API;\nusing osu.Game.Online.API.Requests;\nusing osu.Game.Online.API.Requests.Responses;\nusing osu.Game.Users;\n\nnamespace osu.Game.Overlays.Profile.Sections.Historical\n{\n public class PaginatedMostPlayedBeatmapContainer : PaginatedProfileSubsection\n {\n public PaginatedMostPlayedBeatmapContainer(Bindable user)\n : base(user, \"Most Played Beatmaps\", \"No records. :(\", CounterVisibilityState.AlwaysVisible)\n {\n ItemsPerPage = 5;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n ItemsContainer.Direction = FillDirection.Vertical;\n }\n\n protected override int GetCount(User user) => user.BeatmapPlaycountsCount;\n\n protected override APIRequest> CreateRequest() =>\n new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage);\n\n protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) =>\n new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount);\n }\n}","smell_code":" public class PaginatedMostPlayedBeatmapContainer : PaginatedProfileSubsection\n {\n public PaginatedMostPlayedBeatmapContainer(Bindable user)\n : base(user, \"Most Played Beatmaps\", \"No records. :(\", CounterVisibilityState.AlwaysVisible)\n {\n ItemsPerPage = 5;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n ItemsContainer.Direction = FillDirection.Vertical;\n }\n\n protected override int GetCount(User user) => user.BeatmapPlaycountsCount;\n\n protected override APIRequest> CreateRequest() =>\n new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage);\n\n protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) =>\n new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount);\n }","smell":"large class","id":29} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Linq;\nusing OpenRA.Graphics;\nusing OpenRA.Mods.Common.Traits;\n\nnamespace OpenRA.Mods.Common.Widgets\n{\n\tpublic sealed class EditorActorBrush : IEditorBrush\n\t{\n\t\treadonly World world;\n\t\treadonly EditorActorLayer editorLayer;\n\t\treadonly EditorCursorLayer editorCursor;\n\t\treadonly EditorActionManager editorActionManager;\n\t\treadonly EditorViewportControllerWidget editorWidget;\n\t\treadonly int cursorToken;\n\n\t\tpublic EditorActorBrush(EditorViewportControllerWidget editorWidget, ActorInfo actor, PlayerReference owner, WorldRenderer wr)\n\t\t{\n\t\t\tthis.editorWidget = editorWidget;\n\t\t\tworld = wr.World;\n\t\t\teditorLayer = world.WorldActor.Trait();\n\t\t\teditorCursor = world.WorldActor.Trait();\n\t\t\teditorActionManager = world.WorldActor.Trait();\n\n\t\t\tcursorToken = editorCursor.SetActor(wr, actor, owner);\n\t\t}\n\n\t\tpublic bool HandleMouseInput(MouseInput mi)\n\t\t{\n\t\t\t\/\/ Exclusively uses left and right mouse buttons, but nothing else\n\t\t\tif (mi.Button != MouseButton.Left && mi.Button != MouseButton.Right)\n\t\t\t\treturn false;\n\n\t\t\tif (mi.Button == MouseButton.Right)\n\t\t\t{\n\t\t\t\tif (mi.Event == MouseInputEvent.Up)\n\t\t\t\t{\n\t\t\t\t\teditorWidget.ClearBrush();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (editorCursor.CurrentToken != cursorToken)\n\t\t\t\treturn false;\n\n\t\t\tif (mi.Button == MouseButton.Left && mi.Event == MouseInputEvent.Down)\n\t\t\t{\n\t\t\t\t\/\/ Check the actor is inside the map\n\t\t\t\tvar actor = editorCursor.Actor;\n\t\t\t\tif (!actor.Footprint.All(c => world.Map.Tiles.Contains(c.Key)))\n\t\t\t\t\treturn true;\n\n\t\t\t\tvar action = new AddActorAction(editorLayer, actor.Export());\n\t\t\t\teditorActionManager.Add(action);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic void Tick() { }\n\n\t\tpublic void Dispose()\n\t\t{\n\t\t\teditorCursor.Clear(cursorToken);\n\t\t}\n\t}\n\n\tclass AddActorAction : IEditorAction\n\t{\n\t\tpublic string Text { get; private set; }\n\n\t\treadonly EditorActorLayer editorLayer;\n\t\treadonly ActorReference actor;\n\n\t\tEditorActorPreview editorActorPreview;\n\n\t\tpublic AddActorAction(EditorActorLayer editorLayer, ActorReference actor)\n\t\t{\n\t\t\tthis.editorLayer = editorLayer;\n\n\t\t\t\/\/ Take an immutable copy of the reference\n\t\t\tthis.actor = actor.Clone();\n\t\t}\n\n\t\tpublic void Execute()\n\t\t{\n\t\t\tDo();\n\t\t}\n\n\t\tpublic void Do()\n\t\t{\n\t\t\teditorActorPreview = editorLayer.Add(actor);\n\t\t\tText = \"Added {0} ({1})\".F(editorActorPreview.Info.Name, editorActorPreview.ID);\n\t\t}\n\n\t\tpublic void Undo()\n\t\t{\n\t\t\teditorLayer.Remove(editorActorPreview);\n\t\t}\n\t}\n}","smell_code":"\tclass AddActorAction : IEditorAction\n\t{\n\t\tpublic string Text { get; private set; }\n\n\t\treadonly EditorActorLayer editorLayer;\n\t\treadonly ActorReference actor;\n\n\t\tEditorActorPreview editorActorPreview;\n\n\t\tpublic AddActorAction(EditorActorLayer editorLayer, ActorReference actor)\n\t\t{\n\t\t\tthis.editorLayer = editorLayer;\n\n\t\t\t\/\/ Take an immutable copy of the reference\n\t\t\tthis.actor = actor.Clone();\n\t\t}\n\n\t\tpublic void Execute()\n\t\t{\n\t\t\tDo();\n\t\t}\n\n\t\tpublic void Do()\n\t\t{\n\t\t\teditorActorPreview = editorLayer.Add(actor);\n\t\t\tText = \"Added {0} ({1})\".F(editorActorPreview.Info.Name, editorActorPreview.ID);\n\t\t}\n\n\t\tpublic void Undo()\n\t\t{\n\t\t\teditorLayer.Remove(editorActorPreview);\n\t\t}\n\t}","smell":"large class","id":30} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Framework.Graphics.UserInterface;\nusing osu.Framework.Graphics;\nusing osuTK.Graphics;\nusing osuTK;\nusing osu.Framework.Input.Events;\n\nnamespace osu.Game.Overlays.BeatmapListing\n{\n public class BeatmapListingSortTabControl : OverlaySortTabControl\n {\n public readonly Bindable SortDirection = new Bindable(Overlays.SortDirection.Descending);\n\n public BeatmapListingSortTabControl()\n {\n Current.Value = SortCriteria.Ranked;\n }\n\n protected override SortTabControl CreateControl() => new BeatmapSortTabControl\n {\n SortDirection = { BindTarget = SortDirection }\n };\n\n private class BeatmapSortTabControl : SortTabControl\n {\n public readonly Bindable SortDirection = new Bindable();\n\n protected override TabItem CreateTabItem(SortCriteria value) => new BeatmapSortTabItem(value)\n {\n SortDirection = { BindTarget = SortDirection }\n };\n }\n\n private class BeatmapSortTabItem : SortTabItem\n {\n public readonly Bindable SortDirection = new Bindable();\n\n public BeatmapSortTabItem(SortCriteria value)\n : base(value)\n {\n }\n\n protected override TabButton CreateTabButton(SortCriteria value) => new BeatmapTabButton(value)\n {\n Active = { BindTarget = Active },\n SortDirection = { BindTarget = SortDirection }\n };\n }\n\n private class BeatmapTabButton : TabButton\n {\n public readonly Bindable SortDirection = new Bindable();\n\n protected override Color4 ContentColour\n {\n set\n {\n base.ContentColour = value;\n icon.Colour = value;\n }\n }\n\n private readonly SpriteIcon icon;\n\n public BeatmapTabButton(SortCriteria value)\n : base(value)\n {\n Add(icon = new SpriteIcon\n {\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n AlwaysPresent = true,\n Alpha = 0,\n Size = new Vector2(6)\n });\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n SortDirection.BindValueChanged(direction =>\n {\n icon.Icon = direction.NewValue == Overlays.SortDirection.Ascending ? FontAwesome.Solid.CaretUp : FontAwesome.Solid.CaretDown;\n }, true);\n }\n\n protected override void UpdateState()\n {\n base.UpdateState();\n icon.FadeTo(Active.Value || IsHovered ? 1 : 0, 200, Easing.OutQuint);\n }\n\n protected override bool OnClick(ClickEvent e)\n {\n if (Active.Value)\n SortDirection.Value = SortDirection.Value == Overlays.SortDirection.Ascending ? Overlays.SortDirection.Descending : Overlays.SortDirection.Ascending;\n\n return base.OnClick(e);\n }\n }\n }\n}","smell_code":" private class BeatmapTabButton : TabButton\n {\n public readonly Bindable SortDirection = new Bindable();\n\n protected override Color4 ContentColour\n {\n set\n {\n base.ContentColour = value;\n icon.Colour = value;\n }\n }\n\n private readonly SpriteIcon icon;\n\n public BeatmapTabButton(SortCriteria value)\n : base(value)\n {\n Add(icon = new SpriteIcon\n {\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n AlwaysPresent = true,\n Alpha = 0,\n Size = new Vector2(6)\n });\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n SortDirection.BindValueChanged(direction =>\n {\n icon.Icon = direction.NewValue == Overlays.SortDirection.Ascending ? FontAwesome.Solid.CaretUp : FontAwesome.Solid.CaretDown;\n }, true);\n }\n\n protected override void UpdateState()\n {\n base.UpdateState();\n icon.FadeTo(Active.Value || IsHovered ? 1 : 0, 200, Easing.OutQuint);\n }\n\n protected override bool OnClick(ClickEvent e)\n {\n if (Active.Value)\n SortDirection.Value = SortDirection.Value == Overlays.SortDirection.Ascending ? Overlays.SortDirection.Descending : Overlays.SortDirection.Ascending;\n\n return base.OnClick(e);\n }\n }","smell":"large class","id":31} {"lang_cluster":"C#","source_code":"\ufeffusing BurningKnight.entity.item;\nusing Lens.entity;\n\nnamespace BurningKnight.entity.events {\n\tpublic class ConsumableRemovedEvent : Event {\n\t\tpublic int Amount;\n\t\tpublic int TotalNow;\n\t\tpublic ItemType Type;\n\t}\n}","smell_code":"\tpublic class ConsumableRemovedEvent : Event {\n\t\tpublic int Amount;\n\t\tpublic int TotalNow;\n\t\tpublic ItemType Type;\n\t}","smell":"large class","id":32} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Linq;\nusing osuTK;\nusing osuTK.Graphics;\nusing osu.Framework.Allocation;\nusing osu.Framework.Audio;\nusing osu.Framework.Bindables;\nusing osu.Framework.Extensions.IEnumerableExtensions;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Framework.Graphics.UserInterface;\nusing osu.Framework.Input.Events;\nusing osu.Game.Graphics;\nusing osu.Game.Graphics.Sprites;\nusing osu.Game.Graphics.UserInterface;\nusing osuTK.Input;\n\nnamespace osu.Game.Screens.Edit.Components\n{\n public class PlaybackControl : BottomBarContainer\n {\n private IconButton playButton;\n\n [Resolved]\n private EditorClock editorClock { get; set; }\n\n private readonly BindableNumber tempo = new BindableDouble(1);\n\n [BackgroundDependencyLoader]\n private void load()\n {\n Children = new Drawable[]\n {\n playButton = new IconButton\n {\n Anchor = Anchor.CentreLeft,\n Origin = Anchor.CentreLeft,\n Scale = new Vector2(1.4f),\n IconScale = new Vector2(1.4f),\n Icon = FontAwesome.Regular.PlayCircle,\n Action = togglePause,\n },\n new OsuSpriteText\n {\n Origin = Anchor.BottomLeft,\n Text = \"Playback speed\",\n RelativePositionAxes = Axes.Y,\n Y = 0.5f,\n Padding = new MarginPadding { Left = 45 }\n },\n new Container\n {\n Anchor = Anchor.BottomLeft,\n Origin = Anchor.BottomLeft,\n RelativeSizeAxes = Axes.Both,\n Height = 0.5f,\n Padding = new MarginPadding { Left = 45 },\n Child = new PlaybackTabControl { Current = tempo },\n }\n };\n\n Track.BindValueChanged(tr => tr.NewValue?.AddAdjustment(AdjustableProperty.Tempo, tempo), true);\n }\n\n protected override void Dispose(bool isDisposing)\n {\n Track.Value?.RemoveAdjustment(AdjustableProperty.Tempo, tempo);\n\n base.Dispose(isDisposing);\n }\n\n protected override bool OnKeyDown(KeyDownEvent e)\n {\n switch (e.Key)\n {\n case Key.Space:\n togglePause();\n return true;\n }\n\n return base.OnKeyDown(e);\n }\n\n private void togglePause()\n {\n if (editorClock.IsRunning)\n editorClock.Stop();\n else\n editorClock.Start();\n }\n\n protected override void Update()\n {\n base.Update();\n\n playButton.Icon = editorClock.IsRunning ? FontAwesome.Regular.PauseCircle : FontAwesome.Regular.PlayCircle;\n }\n\n private class PlaybackTabControl : OsuTabControl\n {\n private static readonly double[] tempo_values = { 0.5, 0.75, 1 };\n\n protected override TabItem CreateTabItem(double value) => new PlaybackTabItem(value);\n\n protected override Dropdown CreateDropdown() => null;\n\n public PlaybackTabControl()\n {\n RelativeSizeAxes = Axes.Both;\n TabContainer.Spacing = Vector2.Zero;\n\n tempo_values.ForEach(AddItem);\n\n Current.Value = tempo_values.Last();\n }\n\n public class PlaybackTabItem : TabItem\n {\n private const float fade_duration = 200;\n\n private readonly OsuSpriteText text;\n private readonly OsuSpriteText textBold;\n\n public PlaybackTabItem(double value)\n : base(value)\n {\n RelativeSizeAxes = Axes.Both;\n\n Width = 1f \/ tempo_values.Length;\n\n Children = new Drawable[]\n {\n text = new OsuSpriteText\n {\n Origin = Anchor.TopCentre,\n Anchor = Anchor.TopCentre,\n Text = $\"{value:0%}\",\n Font = OsuFont.GetFont(size: 14)\n },\n textBold = new OsuSpriteText\n {\n Origin = Anchor.TopCentre,\n Anchor = Anchor.TopCentre,\n Text = $\"{value:0%}\",\n Font = OsuFont.GetFont(size: 14, weight: FontWeight.Bold),\n Alpha = 0,\n },\n };\n }\n\n private Color4 hoveredColour;\n private Color4 normalColour;\n\n [BackgroundDependencyLoader]\n private void load(OsuColour colours)\n {\n text.Colour = normalColour = colours.YellowDarker;\n textBold.Colour = hoveredColour = colours.Yellow;\n }\n\n protected override bool OnHover(HoverEvent e)\n {\n updateState();\n return true;\n }\n\n protected override void OnHoverLost(HoverLostEvent e) => updateState();\n protected override void OnActivated() => updateState();\n protected override void OnDeactivated() => updateState();\n\n private void updateState()\n {\n text.FadeColour(Active.Value || IsHovered ? hoveredColour : normalColour, fade_duration, Easing.OutQuint);\n text.FadeTo(Active.Value ? 0 : 1, fade_duration, Easing.OutQuint);\n textBold.FadeTo(Active.Value ? 1 : 0, fade_duration, Easing.OutQuint);\n }\n }\n }\n }\n}","smell_code":" public class PlaybackTabItem : TabItem\n {\n private const float fade_duration = 200;\n\n private readonly OsuSpriteText text;\n private readonly OsuSpriteText textBold;\n\n public PlaybackTabItem(double value)\n : base(value)\n {\n RelativeSizeAxes = Axes.Both;\n\n Width = 1f \/ tempo_values.Length;\n\n Children = new Drawable[]\n {\n text = new OsuSpriteText\n {\n Origin = Anchor.TopCentre,\n Anchor = Anchor.TopCentre,\n Text = $\"{value:0%}\",\n Font = OsuFont.GetFont(size: 14)\n },\n textBold = new OsuSpriteText\n {\n Origin = Anchor.TopCentre,\n Anchor = Anchor.TopCentre,\n Text = $\"{value:0%}\",\n Font = OsuFont.GetFont(size: 14, weight: FontWeight.Bold),\n Alpha = 0,\n },\n };\n }\n\n private Color4 hoveredColour;\n private Color4 normalColour;\n\n [BackgroundDependencyLoader]\n private void load(OsuColour colours)\n {\n text.Colour = normalColour = colours.YellowDarker;\n textBold.Colour = hoveredColour = colours.Yellow;\n }\n\n protected override bool OnHover(HoverEvent e)\n {\n updateState();\n return true;\n }\n\n protected override void OnHoverLost(HoverLostEvent e) => updateState();\n protected override void OnActivated() => updateState();\n protected override void OnDeactivated() => updateState();\n\n private void updateState()\n {\n text.FadeColour(Active.Value || IsHovered ? hoveredColour : normalColour, fade_duration, Easing.OutQuint);\n text.FadeTo(Active.Value ? 0 : 1, fade_duration, Easing.OutQuint);\n textBold.FadeTo(Active.Value ? 1 : 0, fade_duration, Easing.OutQuint);\n }\n }","smell":"large class","id":33} {"lang_cluster":"C#","source_code":"using Lens.entity;\n\nnamespace BurningKnight {\n\tpublic class Tags {\n\t\tpublic static int Player = new BitTag(\"player\");\n\t\tpublic static int PlayerTarget = new BitTag(\"player_target\");\n\t\tpublic static int Cursor = new BitTag(\"cursor\");\n\t\tpublic static int Mob = new BitTag(\"mob\");\n\t\tpublic static int Boss = new BitTag(\"boss\");\n\t\tpublic static int BurningKnight = new BitTag(\"burning_knight\");\n\t\tpublic static int PlayerSave = new BitTag(\"player_save\");\n\t\tpublic static int LevelSave = new BitTag(\"level_save\");\n\t\tpublic static int Bomb = new BitTag(\"bomb\");\n\t\t\n\t\tpublic static int Room = new BitTag(\"room\");\n\t\tpublic static int TeleportTrigger = new BitTag(\"teleport_trigger\");\n\t\tpublic static int Lock = new BitTag(\"lock\");\n\t\tpublic static int MustBeKilled = new BitTag(\"must_be_killed\");\n\t\tpublic static int Gramophone = new BitTag(\"gramophone\");\n\t\tpublic static int Teleport = new BitTag(\"teleport\");\n\t\tpublic static int Statue = new BitTag(\"statue\");\n\n\t\tpublic static int HasShadow = new BitTag(\"shadow\");\n\t\tpublic static int Mess = new BitTag(\"mess\");\n\t\t\n\t\tpublic static int Checkpoint = new BitTag(\"checkpoint\");\n\t\tpublic static int Entrance = new BitTag(\"entrance\");\n\t\tpublic static int HiddenEntrance = new BitTag(\"hidden_entrance\");\n\t\tpublic static int Item = new BitTag(\"item\");\n\t\tpublic static int ShopKeeper = new BitTag(\"shop_keeper\");\n\t\tpublic static int Npc = new BitTag(\"npc\");\n\n\t\tpublic static int Torch = new BitTag(\"torch\");\n\t\tpublic static int Button = new BitTag(\"button\");\n\t\tpublic static int Chest = new BitTag(\"chest\");\n\t\tpublic static int Projectile = new BitTag(\"projectile\");\n\t\tpublic static int Laser = new BitTag(\"laser\");\n\t\tpublic static int FireParticle = new BitTag(\"fire_particle\");\n\t\tpublic static int TextParticle = new BitTag(\"text_particle\");\n\t\tpublic static int Door = new BitTag(\"door\");\n\n\t\tpublic static string[] AllTags;\n\t\t\n\t\tstatic Tags() {\n\t\t\tAllTags = new string[BitTag.Total];\n\t\t\tvar i = 0;\n\t\t\t\n\t\t\tforeach (var t in BitTag.Tags) {\n\t\t\t\tAllTags[i] = t.Name;\n\t\t\t\t\n\t\t\t\ti++;\n\t\t\t\t\n\t\t\t\tif (i == BitTag.Total) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic class Tags {\n\t\tpublic static int Player = new BitTag(\"player\");\n\t\tpublic static int PlayerTarget = new BitTag(\"player_target\");\n\t\tpublic static int Cursor = new BitTag(\"cursor\");\n\t\tpublic static int Mob = new BitTag(\"mob\");\n\t\tpublic static int Boss = new BitTag(\"boss\");\n\t\tpublic static int BurningKnight = new BitTag(\"burning_knight\");\n\t\tpublic static int PlayerSave = new BitTag(\"player_save\");\n\t\tpublic static int LevelSave = new BitTag(\"level_save\");\n\t\tpublic static int Bomb = new BitTag(\"bomb\");\n\t\t\n\t\tpublic static int Room = new BitTag(\"room\");\n\t\tpublic static int TeleportTrigger = new BitTag(\"teleport_trigger\");\n\t\tpublic static int Lock = new BitTag(\"lock\");\n\t\tpublic static int MustBeKilled = new BitTag(\"must_be_killed\");\n\t\tpublic static int Gramophone = new BitTag(\"gramophone\");\n\t\tpublic static int Teleport = new BitTag(\"teleport\");\n\t\tpublic static int Statue = new BitTag(\"statue\");\n\n\t\tpublic static int HasShadow = new BitTag(\"shadow\");\n\t\tpublic static int Mess = new BitTag(\"mess\");\n\t\t\n\t\tpublic static int Checkpoint = new BitTag(\"checkpoint\");\n\t\tpublic static int Entrance = new BitTag(\"entrance\");\n\t\tpublic static int HiddenEntrance = new BitTag(\"hidden_entrance\");\n\t\tpublic static int Item = new BitTag(\"item\");\n\t\tpublic static int ShopKeeper = new BitTag(\"shop_keeper\");\n\t\tpublic static int Npc = new BitTag(\"npc\");\n\n\t\tpublic static int Torch = new BitTag(\"torch\");\n\t\tpublic static int Button = new BitTag(\"button\");\n\t\tpublic static int Chest = new BitTag(\"chest\");\n\t\tpublic static int Projectile = new BitTag(\"projectile\");\n\t\tpublic static int Laser = new BitTag(\"laser\");\n\t\tpublic static int FireParticle = new BitTag(\"fire_particle\");\n\t\tpublic static int TextParticle = new BitTag(\"text_particle\");\n\t\tpublic static int Door = new BitTag(\"door\");\n\n\t\tpublic static string[] AllTags;\n\t\t\n\t\tstatic Tags() {\n\t\t\tAllTags = new string[BitTag.Total];\n\t\t\tvar i = 0;\n\t\t\t\n\t\t\tforeach (var t in BitTag.Tags) {\n\t\t\t\tAllTags[i] = t.Name;\n\t\t\t\t\n\t\t\t\ti++;\n\t\t\t\t\n\t\t\t\tif (i == BitTag.Total) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":34} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing OpenRA.Primitives;\n\nnamespace OpenRA\n{\n\tpublic class WorldViewportSizes : IGlobalModData\n\t{\n\t\tpublic readonly int2 CloseWindowHeights = new int2(480, 600);\n\t\tpublic readonly int2 MediumWindowHeights = new int2(600, 900);\n\t\tpublic readonly int2 FarWindowHeights = new int2(900, 1300);\n\n\t\tpublic readonly float MaxZoomScale = 2.0f;\n\t\tpublic readonly int MaxZoomWindowHeight = 240;\n\t\tpublic readonly bool AllowNativeZoom = true;\n\n\t\tpublic readonly Size MinEffectiveResolution = new Size(1024, 720);\n\n\t\tpublic int2 GetSizeRange(WorldViewport distance)\n\t\t{\n\t\t\treturn distance == WorldViewport.Close ? CloseWindowHeights\n\t\t\t\t: distance == WorldViewport.Medium ? MediumWindowHeights\n\t\t\t\t: FarWindowHeights;\n\t\t}\n\t}\n}","smell_code":"\tpublic class WorldViewportSizes : IGlobalModData\n\t{\n\t\tpublic readonly int2 CloseWindowHeights = new int2(480, 600);\n\t\tpublic readonly int2 MediumWindowHeights = new int2(600, 900);\n\t\tpublic readonly int2 FarWindowHeights = new int2(900, 1300);\n\n\t\tpublic readonly float MaxZoomScale = 2.0f;\n\t\tpublic readonly int MaxZoomWindowHeight = 240;\n\t\tpublic readonly bool AllowNativeZoom = true;\n\n\t\tpublic readonly Size MinEffectiveResolution = new Size(1024, 720);\n\n\t\tpublic int2 GetSizeRange(WorldViewport distance)\n\t\t{\n\t\t\treturn distance == WorldViewport.Close ? CloseWindowHeights\n\t\t\t\t: distance == WorldViewport.Medium ? MediumWindowHeights\n\t\t\t\t: FarWindowHeights;\n\t\t}\n\t}","smell":"large class","id":35} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Linq;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t[Desc(\"Hides the entire map in shroud.\")]\n\tclass HideMapCrateActionInfo : CrateActionInfo\n\t{\n\t\t[Desc(\"Should the map also be hidden for the allies of the collector's owner?\")]\n\t\tpublic readonly bool IncludeAllies = false;\n\n\t\tpublic override object Create(ActorInitializer init) { return new HideMapCrateAction(init.Self, this); }\n\t}\n\n\tclass HideMapCrateAction : CrateAction\n\t{\n\t\treadonly HideMapCrateActionInfo info;\n\n\t\tpublic HideMapCrateAction(Actor self, HideMapCrateActionInfo info)\n\t\t\t: base(self, info)\n\t\t{\n\t\t\tthis.info = info;\n\t\t}\n\n\t\tpublic override int GetSelectionShares(Actor collector)\n\t\t{\n\t\t\t\/\/ Don't hide the map if the shroud is force-revealed\n\t\t\tvar preventReset = collector.Owner.PlayerActor.TraitsImplementing()\n\t\t\t\t.Any(p => p.PreventShroudReset(collector.Owner.PlayerActor));\n\t\t\tif (preventReset || collector.Owner.Shroud.ExploreMapEnabled)\n\t\t\t\treturn 0;\n\n\t\t\treturn base.GetSelectionShares(collector);\n\t\t}\n\n\t\tpublic override void Activate(Actor collector)\n\t\t{\n\t\t\tif (info.IncludeAllies)\n\t\t\t{\n\t\t\t\tforeach (var player in collector.World.Players)\n\t\t\t\t\tif (player.IsAlliedWith(collector.Owner))\n\t\t\t\t\t\tplayer.Shroud.ResetExploration();\n\t\t\t}\n\t\t\telse\n\t\t\t\tcollector.Owner.Shroud.ResetExploration();\n\n\t\t\tbase.Activate(collector);\n\t\t}\n\t}\n}","smell_code":"\tclass HideMapCrateAction : CrateAction\n\t{\n\t\treadonly HideMapCrateActionInfo info;\n\n\t\tpublic HideMapCrateAction(Actor self, HideMapCrateActionInfo info)\n\t\t\t: base(self, info)\n\t\t{\n\t\t\tthis.info = info;\n\t\t}\n\n\t\tpublic override int GetSelectionShares(Actor collector)\n\t\t{\n\t\t\t\/\/ Don't hide the map if the shroud is force-revealed\n\t\t\tvar preventReset = collector.Owner.PlayerActor.TraitsImplementing()\n\t\t\t\t.Any(p => p.PreventShroudReset(collector.Owner.PlayerActor));\n\t\t\tif (preventReset || collector.Owner.Shroud.ExploreMapEnabled)\n\t\t\t\treturn 0;\n\n\t\t\treturn base.GetSelectionShares(collector);\n\t\t}\n\n\t\tpublic override void Activate(Actor collector)\n\t\t{\n\t\t\tif (info.IncludeAllies)\n\t\t\t{\n\t\t\t\tforeach (var player in collector.World.Players)\n\t\t\t\t\tif (player.IsAlliedWith(collector.Owner))\n\t\t\t\t\t\tplayer.Shroud.ResetExploration();\n\t\t\t}\n\t\t\telse\n\t\t\t\tcollector.Owner.Shroud.ResetExploration();\n\n\t\t\tbase.Activate(collector);\n\t\t}\n\t}","smell":"large class","id":36} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing System.Linq;\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Input.Events;\nusing osu.Game.Configuration;\nusing osuTK;\nusing osuTK.Graphics;\n\nnamespace osu.Game.Screens.Play\n{\n public class KeyCounterDisplay : Container\n {\n private const int duration = 100;\n private const double key_fade_time = 80;\n\n private readonly Bindable configVisibility = new Bindable();\n\n protected readonly FillFlowContainer KeyFlow;\n\n protected override Container Content => KeyFlow;\n\n \/\/\/ \n \/\/\/ Whether the key counter should be visible regardless of the configuration value.\n \/\/\/ This is true by default, but can be changed.\n \/\/\/ <\/summary>\n public readonly Bindable AlwaysVisible = new Bindable(true);\n\n public KeyCounterDisplay()\n {\n AutoSizeAxes = Axes.Both;\n\n InternalChild = KeyFlow = new FillFlowContainer\n {\n Direction = FillDirection.Horizontal,\n AutoSizeAxes = Axes.Both,\n };\n }\n\n public override void Add(KeyCounter key)\n {\n if (key == null) throw new ArgumentNullException(nameof(key));\n\n base.Add(key);\n key.IsCounting = IsCounting;\n key.FadeTime = key_fade_time;\n key.KeyDownTextColor = KeyDownTextColor;\n key.KeyUpTextColor = KeyUpTextColor;\n }\n\n [BackgroundDependencyLoader]\n private void load(OsuConfigManager config)\n {\n config.BindWith(OsuSetting.KeyOverlay, configVisibility);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n AlwaysVisible.BindValueChanged(_ => updateVisibility());\n configVisibility.BindValueChanged(_ => updateVisibility(), true);\n }\n\n private bool isCounting = true;\n\n public bool IsCounting\n {\n get => isCounting;\n set\n {\n if (value == isCounting) return;\n\n isCounting = value;\n foreach (var child in Children)\n child.IsCounting = value;\n }\n }\n\n private Color4 keyDownTextColor = Color4.DarkGray;\n\n public Color4 KeyDownTextColor\n {\n get => keyDownTextColor;\n set\n {\n if (value != keyDownTextColor)\n {\n keyDownTextColor = value;\n foreach (var child in Children)\n child.KeyDownTextColor = value;\n }\n }\n }\n\n private Color4 keyUpTextColor = Color4.White;\n\n public Color4 KeyUpTextColor\n {\n get => keyUpTextColor;\n set\n {\n if (value != keyUpTextColor)\n {\n keyUpTextColor = value;\n foreach (var child in Children)\n child.KeyUpTextColor = value;\n }\n }\n }\n\n private void updateVisibility() =>\n \/\/ Isolate changing visibility of the key counters from fading this component.\n KeyFlow.FadeTo(AlwaysVisible.Value || configVisibility.Value ? 1 : 0, duration);\n\n public override bool HandleNonPositionalInput => receptor == null;\n public override bool HandlePositionalInput => receptor == null;\n\n private Receptor receptor;\n\n public void SetReceptor(Receptor receptor)\n {\n if (this.receptor != null)\n throw new InvalidOperationException(\"Cannot set a new receptor when one is already active\");\n\n this.receptor = receptor;\n }\n\n public class Receptor : Drawable\n {\n protected readonly KeyCounterDisplay Target;\n\n public Receptor(KeyCounterDisplay target)\n {\n RelativeSizeAxes = Axes.Both;\n Depth = float.MinValue;\n Target = target;\n }\n\n public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;\n\n protected override bool Handle(UIEvent e)\n {\n switch (e)\n {\n case KeyDownEvent _:\n case KeyUpEvent _:\n case MouseDownEvent _:\n case MouseUpEvent _:\n return Target.Children.Any(c => c.TriggerEvent(e));\n }\n\n return base.Handle(e);\n }\n }\n }\n}","smell_code":" public class KeyCounterDisplay : Container\n {\n private const int duration = 100;\n private const double key_fade_time = 80;\n\n private readonly Bindable configVisibility = new Bindable();\n\n protected readonly FillFlowContainer KeyFlow;\n\n protected override Container Content => KeyFlow;\n\n \/\/\/ \n \/\/\/ Whether the key counter should be visible regardless of the configuration value.\n \/\/\/ This is true by default, but can be changed.\n \/\/\/ <\/summary>\n public readonly Bindable AlwaysVisible = new Bindable(true);\n\n public KeyCounterDisplay()\n {\n AutoSizeAxes = Axes.Both;\n\n InternalChild = KeyFlow = new FillFlowContainer\n {\n Direction = FillDirection.Horizontal,\n AutoSizeAxes = Axes.Both,\n };\n }\n\n public override void Add(KeyCounter key)\n {\n if (key == null) throw new ArgumentNullException(nameof(key));\n\n base.Add(key);\n key.IsCounting = IsCounting;\n key.FadeTime = key_fade_time;\n key.KeyDownTextColor = KeyDownTextColor;\n key.KeyUpTextColor = KeyUpTextColor;\n }\n\n [BackgroundDependencyLoader]\n private void load(OsuConfigManager config)\n {\n config.BindWith(OsuSetting.KeyOverlay, configVisibility);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n AlwaysVisible.BindValueChanged(_ => updateVisibility());\n configVisibility.BindValueChanged(_ => updateVisibility(), true);\n }\n\n private bool isCounting = true;\n\n public bool IsCounting\n {\n get => isCounting;\n set\n {\n if (value == isCounting) return;\n\n isCounting = value;\n foreach (var child in Children)\n child.IsCounting = value;\n }\n }\n\n private Color4 keyDownTextColor = Color4.DarkGray;\n\n public Color4 KeyDownTextColor\n {\n get => keyDownTextColor;\n set\n {\n if (value != keyDownTextColor)\n {\n keyDownTextColor = value;\n foreach (var child in Children)\n child.KeyDownTextColor = value;\n }\n }\n }\n\n private Color4 keyUpTextColor = Color4.White;\n\n public Color4 KeyUpTextColor\n {\n get => keyUpTextColor;\n set\n {\n if (value != keyUpTextColor)\n {\n keyUpTextColor = value;\n foreach (var child in Children)\n child.KeyUpTextColor = value;\n }\n }\n }\n\n private void updateVisibility() =>\n \/\/ Isolate changing visibility of the key counters from fading this component.\n KeyFlow.FadeTo(AlwaysVisible.Value || configVisibility.Value ? 1 : 0, duration);\n\n public override bool HandleNonPositionalInput => receptor == null;\n public override bool HandlePositionalInput => receptor == null;\n\n private Receptor receptor;\n\n public void SetReceptor(Receptor receptor)\n {\n if (this.receptor != null)\n throw new InvalidOperationException(\"Cannot set a new receptor when one is already active\");\n\n this.receptor = receptor;\n }\n\n public class Receptor : Drawable\n {\n protected readonly KeyCounterDisplay Target;\n\n public Receptor(KeyCounterDisplay target)\n {\n RelativeSizeAxes = Axes.Both;\n Depth = float.MinValue;\n Target = target;\n }\n\n public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;\n\n protected override bool Handle(UIEvent e)\n {\n switch (e)\n {\n case KeyDownEvent _:\n case KeyUpEvent _:\n case MouseDownEvent _:\n case MouseUpEvent _:\n return Target.Children.Any(c => c.TriggerEvent(e));\n }\n\n return base.Handle(e);\n }\n }\n }","smell":"large class","id":37} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Tournament.Components;\nusing osu.Game.Tournament.Models;\nusing osuTK;\n\nnamespace osu.Game.Tournament.Screens.Gameplay.Components\n{\n public class MatchHeader : Container\n {\n private TeamScoreDisplay teamDisplay1;\n private TeamScoreDisplay teamDisplay2;\n private DrawableTournamentHeaderLogo logo;\n\n private bool showScores = true;\n\n public bool ShowScores\n {\n get => showScores;\n set\n {\n if (value == showScores)\n return;\n\n showScores = value;\n\n if (IsLoaded)\n updateDisplay();\n }\n }\n\n private bool showLogo = true;\n\n public bool ShowLogo\n {\n get => showLogo;\n set\n {\n if (value == showLogo)\n return;\n\n showLogo = value;\n\n if (IsLoaded)\n updateDisplay();\n }\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n Height = 95;\n Children = new Drawable[]\n {\n new FillFlowContainer\n {\n RelativeSizeAxes = Axes.Both,\n Direction = FillDirection.Vertical,\n Padding = new MarginPadding(20),\n Spacing = new Vector2(5),\n Children = new Drawable[]\n {\n logo = new DrawableTournamentHeaderLogo\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Alpha = showLogo ? 1 : 0\n },\n new DrawableTournamentHeaderText\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n },\n new MatchRoundDisplay\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Scale = new Vector2(0.4f)\n },\n }\n },\n teamDisplay1 = new TeamScoreDisplay(TeamColour.Red)\n {\n Anchor = Anchor.TopLeft,\n Origin = Anchor.TopLeft,\n },\n teamDisplay2 = new TeamScoreDisplay(TeamColour.Blue)\n {\n Anchor = Anchor.TopRight,\n Origin = Anchor.TopRight,\n },\n };\n\n updateDisplay();\n }\n\n private void updateDisplay()\n {\n teamDisplay1.ShowScore = showScores;\n teamDisplay2.ShowScore = showScores;\n\n logo.Alpha = showLogo ? 1 : 0;\n }\n }\n}","smell_code":" public class MatchHeader : Container\n {\n private TeamScoreDisplay teamDisplay1;\n private TeamScoreDisplay teamDisplay2;\n private DrawableTournamentHeaderLogo logo;\n\n private bool showScores = true;\n\n public bool ShowScores\n {\n get => showScores;\n set\n {\n if (value == showScores)\n return;\n\n showScores = value;\n\n if (IsLoaded)\n updateDisplay();\n }\n }\n\n private bool showLogo = true;\n\n public bool ShowLogo\n {\n get => showLogo;\n set\n {\n if (value == showLogo)\n return;\n\n showLogo = value;\n\n if (IsLoaded)\n updateDisplay();\n }\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n Height = 95;\n Children = new Drawable[]\n {\n new FillFlowContainer\n {\n RelativeSizeAxes = Axes.Both,\n Direction = FillDirection.Vertical,\n Padding = new MarginPadding(20),\n Spacing = new Vector2(5),\n Children = new Drawable[]\n {\n logo = new DrawableTournamentHeaderLogo\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Alpha = showLogo ? 1 : 0\n },\n new DrawableTournamentHeaderText\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n },\n new MatchRoundDisplay\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Scale = new Vector2(0.4f)\n },\n }\n },\n teamDisplay1 = new TeamScoreDisplay(TeamColour.Red)\n {\n Anchor = Anchor.TopLeft,\n Origin = Anchor.TopLeft,\n },\n teamDisplay2 = new TeamScoreDisplay(TeamColour.Blue)\n {\n Anchor = Anchor.TopRight,\n Origin = Anchor.TopRight,\n },\n };\n\n updateDisplay();\n }\n\n private void updateDisplay()\n {\n teamDisplay1.ShowScore = showScores;\n teamDisplay2.ShowScore = showScores;\n\n logo.Alpha = showLogo ? 1 : 0;\n }\n }","smell":"large class","id":38} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Graphics;\nusing osu.Framework.Bindables;\nusing osu.Game.Rulesets;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Online.API.Requests.Responses;\nusing osuTK;\nusing osu.Framework.Allocation;\nusing osu.Game.Online.API;\nusing osu.Game.Online.API.Requests;\nusing osu.Game.Overlays.Rankings.Tables;\nusing System.Linq;\nusing System.Threading;\nusing osu.Game.Graphics.Containers;\nusing osu.Game.Graphics.UserInterface;\nusing osu.Game.Overlays.BeatmapListing.Panels;\n\nnamespace osu.Game.Overlays.Rankings\n{\n public class SpotlightsLayout : CompositeDrawable\n {\n public readonly Bindable Ruleset = new Bindable();\n\n private readonly Bindable selectedSpotlight = new Bindable();\n private readonly Bindable sort = new Bindable();\n\n [Resolved]\n private IAPIProvider api { get; set; }\n\n [Resolved]\n private RulesetStore rulesets { get; set; }\n\n private CancellationTokenSource cancellationToken;\n private GetSpotlightRankingsRequest getRankingsRequest;\n private GetSpotlightsRequest spotlightsRequest;\n\n private SpotlightSelector selector;\n private Container content;\n private LoadingLayer loading;\n\n [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n AutoSizeAxes = Axes.Y;\n\n InternalChild = new ReverseChildIDFillFlowContainer\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Children = new Drawable[]\n {\n selector = new SpotlightSelector\n {\n Current = selectedSpotlight,\n },\n new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Children = new Drawable[]\n {\n content = new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Margin = new MarginPadding { Vertical = 10 }\n },\n loading = new LoadingLayer(true)\n }\n }\n }\n };\n\n sort.BindTo(selector.Sort);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n selectedSpotlight.BindValueChanged(_ => onSpotlightChanged());\n sort.BindValueChanged(_ => onSpotlightChanged());\n Ruleset.BindValueChanged(onRulesetChanged);\n\n getSpotlights();\n }\n\n private void getSpotlights()\n {\n spotlightsRequest = new GetSpotlightsRequest();\n spotlightsRequest.Success += response => Schedule(() => selector.Spotlights = response.Spotlights);\n api.Queue(spotlightsRequest);\n }\n\n private void onRulesetChanged(ValueChangedEvent ruleset)\n {\n if (!selector.Spotlights.Any())\n return;\n\n selectedSpotlight.TriggerChange();\n }\n\n private void onSpotlightChanged()\n {\n loading.Show();\n\n cancellationToken?.Cancel();\n getRankingsRequest?.Cancel();\n\n getRankingsRequest = new GetSpotlightRankingsRequest(Ruleset.Value, selectedSpotlight.Value.Id, sort.Value);\n getRankingsRequest.Success += onSuccess;\n api.Queue(getRankingsRequest);\n }\n\n private void onSuccess(GetSpotlightRankingsResponse response)\n {\n LoadComponentAsync(createContent(response), loaded =>\n {\n selector.ShowInfo(response);\n\n content.Clear();\n content.Add(loaded);\n\n loading.Hide();\n }, (cancellationToken = new CancellationTokenSource()).Token);\n }\n\n private Drawable createContent(GetSpotlightRankingsResponse response) => new FillFlowContainer\n {\n AutoSizeAxes = Axes.Y,\n RelativeSizeAxes = Axes.X,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 20),\n Children = new Drawable[]\n {\n new ScoresTable(1, response.Users),\n new FillFlowContainer\n {\n AutoSizeAxes = Axes.Y,\n RelativeSizeAxes = Axes.X,\n Spacing = new Vector2(10),\n Children = response.BeatmapSets.Select(b => new GridBeatmapPanel(b.ToBeatmapSet(rulesets))\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n }).ToList()\n }\n }\n };\n\n protected override void Dispose(bool isDisposing)\n {\n spotlightsRequest?.Cancel();\n getRankingsRequest?.Cancel();\n cancellationToken?.Cancel();\n\n base.Dispose(isDisposing);\n }\n }\n}","smell_code":" public class SpotlightsLayout : CompositeDrawable\n {\n public readonly Bindable Ruleset = new Bindable();\n\n private readonly Bindable selectedSpotlight = new Bindable();\n private readonly Bindable sort = new Bindable();\n\n [Resolved]\n private IAPIProvider api { get; set; }\n\n [Resolved]\n private RulesetStore rulesets { get; set; }\n\n private CancellationTokenSource cancellationToken;\n private GetSpotlightRankingsRequest getRankingsRequest;\n private GetSpotlightsRequest spotlightsRequest;\n\n private SpotlightSelector selector;\n private Container content;\n private LoadingLayer loading;\n\n [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n AutoSizeAxes = Axes.Y;\n\n InternalChild = new ReverseChildIDFillFlowContainer\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Children = new Drawable[]\n {\n selector = new SpotlightSelector\n {\n Current = selectedSpotlight,\n },\n new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Children = new Drawable[]\n {\n content = new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Margin = new MarginPadding { Vertical = 10 }\n },\n loading = new LoadingLayer(true)\n }\n }\n }\n };\n\n sort.BindTo(selector.Sort);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n selectedSpotlight.BindValueChanged(_ => onSpotlightChanged());\n sort.BindValueChanged(_ => onSpotlightChanged());\n Ruleset.BindValueChanged(onRulesetChanged);\n\n getSpotlights();\n }\n\n private void getSpotlights()\n {\n spotlightsRequest = new GetSpotlightsRequest();\n spotlightsRequest.Success += response => Schedule(() => selector.Spotlights = response.Spotlights);\n api.Queue(spotlightsRequest);\n }\n\n private void onRulesetChanged(ValueChangedEvent ruleset)\n {\n if (!selector.Spotlights.Any())\n return;\n\n selectedSpotlight.TriggerChange();\n }\n\n private void onSpotlightChanged()\n {\n loading.Show();\n\n cancellationToken?.Cancel();\n getRankingsRequest?.Cancel();\n\n getRankingsRequest = new GetSpotlightRankingsRequest(Ruleset.Value, selectedSpotlight.Value.Id, sort.Value);\n getRankingsRequest.Success += onSuccess;\n api.Queue(getRankingsRequest);\n }\n\n private void onSuccess(GetSpotlightRankingsResponse response)\n {\n LoadComponentAsync(createContent(response), loaded =>\n {\n selector.ShowInfo(response);\n\n content.Clear();\n content.Add(loaded);\n\n loading.Hide();\n }, (cancellationToken = new CancellationTokenSource()).Token);\n }\n\n private Drawable createContent(GetSpotlightRankingsResponse response) => new FillFlowContainer\n {\n AutoSizeAxes = Axes.Y,\n RelativeSizeAxes = Axes.X,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 20),\n Children = new Drawable[]\n {\n new ScoresTable(1, response.Users),\n new FillFlowContainer\n {\n AutoSizeAxes = Axes.Y,\n RelativeSizeAxes = Axes.X,\n Spacing = new Vector2(10),\n Children = response.BeatmapSets.Select(b => new GridBeatmapPanel(b.ToBeatmapSet(rulesets))\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n }).ToList()\n }\n }\n };\n\n protected override void Dispose(bool isDisposing)\n {\n spotlightsRequest?.Cancel();\n getRankingsRequest?.Cancel();\n cancellationToken?.Cancel();\n\n base.Dispose(isDisposing);\n }\n }","smell":"large class","id":39} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Framework.Graphics.Textures;\nusing osu.Framework.Utils;\n\nnamespace osu.Game.Tournament.Screens.Drawings.Components\n{\n public class VisualiserContainer : Container\n {\n \/\/\/ \n \/\/\/ Number of lines in the visualiser.\n \/\/\/ <\/summary>\n public int Lines\n {\n get => allLines.Count;\n set\n {\n while (value > allLines.Count)\n addLine();\n\n while (value < allLines.Count)\n removeLine();\n }\n }\n\n private readonly List allLines = new List();\n\n private float offset;\n\n private void addLine()\n {\n VisualiserLine newLine = new VisualiserLine\n {\n RelativeSizeAxes = Axes.Both,\n\n Offset = offset,\n CycleTime = RNG.Next(10000, 12000),\n };\n\n allLines.Add(newLine);\n Add(newLine);\n\n offset += RNG.Next(100, 5000);\n }\n\n private void removeLine()\n {\n if (allLines.Count == 0)\n return;\n\n Remove(allLines.First());\n allLines.Remove(allLines.First());\n }\n\n private class VisualiserLine : Container\n {\n \/\/\/ \n \/\/\/ Time offset.\n \/\/\/ <\/summary>\n public float Offset;\n\n public double CycleTime;\n\n private float leftPos => -(float)((Time.Current + Offset) \/ CycleTime) + expiredCount;\n\n private Texture texture;\n\n private int expiredCount;\n\n [BackgroundDependencyLoader]\n private void load(TextureStore textures)\n {\n texture = textures.Get(\"Drawings\/visualiser-line\");\n }\n\n protected override void UpdateAfterChildren()\n {\n base.UpdateAfterChildren();\n\n while (Children.Count < 3)\n addLine();\n\n float pos = leftPos;\n\n foreach (var c in Children)\n {\n if (c.Position.X < -1)\n {\n c.ClearTransforms();\n c.Expire();\n expiredCount++;\n }\n else\n c.MoveToX(pos, 100);\n\n pos += 1;\n }\n }\n\n private void addLine()\n {\n Add(new Sprite\n {\n Anchor = Anchor.CentreLeft,\n Origin = Anchor.CentreLeft,\n\n RelativePositionAxes = Axes.Both,\n RelativeSizeAxes = Axes.Both,\n\n Texture = texture,\n\n X = leftPos + 1\n });\n }\n }\n }\n}","smell_code":" private class VisualiserLine : Container\n {\n \/\/\/ \n \/\/\/ Time offset.\n \/\/\/ <\/summary>\n public float Offset;\n\n public double CycleTime;\n\n private float leftPos => -(float)((Time.Current + Offset) \/ CycleTime) + expiredCount;\n\n private Texture texture;\n\n private int expiredCount;\n\n [BackgroundDependencyLoader]\n private void load(TextureStore textures)\n {\n texture = textures.Get(\"Drawings\/visualiser-line\");\n }\n\n protected override void UpdateAfterChildren()\n {\n base.UpdateAfterChildren();\n\n while (Children.Count < 3)\n addLine();\n\n float pos = leftPos;\n\n foreach (var c in Children)\n {\n if (c.Position.X < -1)\n {\n c.ClearTransforms();\n c.Expire();\n expiredCount++;\n }\n else\n c.MoveToX(pos, 100);\n\n pos += 1;\n }\n }\n\n private void addLine()\n {\n Add(new Sprite\n {\n Anchor = Anchor.CentreLeft,\n Origin = Anchor.CentreLeft,\n\n RelativePositionAxes = Axes.Both,\n RelativeSizeAxes = Axes.Both,\n\n Texture = texture,\n\n X = leftPos + 1\n });\n }\n }","smell":"large class","id":40} {"lang_cluster":"C#","source_code":"#nullable disable\nusing System.Collections.Generic;\nusing System.Text.Json.Serialization;\nusing MediaBrowser.Model.Entities;\n\nnamespace MediaBrowser.Model.Dto\n{\n \/\/\/ \n \/\/\/ This is used by the api to get information about a Person within a BaseItem.\n \/\/\/ <\/summary>\n public class BaseItemPerson\n {\n \/\/\/ \n \/\/\/ Gets or sets the name.\n \/\/\/ <\/summary>\n \/\/\/ The name.<\/value>\n public string Name { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the identifier.\n \/\/\/ <\/summary>\n \/\/\/ The identifier.<\/value>\n public string Id { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the role.\n \/\/\/ <\/summary>\n \/\/\/ The role.<\/value>\n public string Role { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type.\n \/\/\/ <\/summary>\n \/\/\/ The type.<\/value>\n public string Type { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the primary image tag.\n \/\/\/ <\/summary>\n \/\/\/ The primary image tag.<\/value>\n public string PrimaryImageTag { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the primary image blurhash.\n \/\/\/ <\/summary>\n \/\/\/ The primary image blurhash.<\/value>\n public Dictionary> ImageBlurHashes { get; set; }\n\n \/\/\/ \n \/\/\/ Gets a value indicating whether this instance has primary image.\n \/\/\/ <\/summary>\n \/\/\/ true<\/c> if this instance has primary image; otherwise, false<\/c>.<\/value>\n [JsonIgnore]\n public bool HasPrimaryImage => PrimaryImageTag != null;\n }\n}","smell_code":" public class BaseItemPerson\n {\n \/\/\/ \n \/\/\/ Gets or sets the name.\n \/\/\/ <\/summary>\n \/\/\/ The name.<\/value>\n public string Name { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the identifier.\n \/\/\/ <\/summary>\n \/\/\/ The identifier.<\/value>\n public string Id { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the role.\n \/\/\/ <\/summary>\n \/\/\/ The role.<\/value>\n public string Role { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type.\n \/\/\/ <\/summary>\n \/\/\/ The type.<\/value>\n public string Type { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the primary image tag.\n \/\/\/ <\/summary>\n \/\/\/ The primary image tag.<\/value>\n public string PrimaryImageTag { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the primary image blurhash.\n \/\/\/ <\/summary>\n \/\/\/ The primary image blurhash.<\/value>\n public Dictionary> ImageBlurHashes { get; set; }\n\n \/\/\/ \n \/\/\/ Gets a value indicating whether this instance has primary image.\n \/\/\/ <\/summary>\n \/\/\/ true<\/c> if this instance has primary image; otherwise, false<\/c>.<\/value>\n [JsonIgnore]\n public bool HasPrimaryImage => PrimaryImageTag != null;\n }","smell":"large class","id":41} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Game.Graphics.Sprites;\nusing System;\nusing System.Collections.Generic;\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics.UserInterface;\n\nnamespace osu.Game.Graphics.UserInterface\n{\n public abstract class RollingCounter : Container, IHasCurrentValue\n where T : struct, IEquatable\n {\n private readonly BindableWithCurrent current = new BindableWithCurrent();\n\n public Bindable Current\n {\n get => current.Current;\n set => current.Current = value;\n }\n\n private SpriteText displayedCountSpriteText;\n\n \/\/\/ \n \/\/\/ If true, the roll-up duration will be proportional to change in value.\n \/\/\/ <\/summary>\n protected virtual bool IsRollingProportional => false;\n\n \/\/\/ \n \/\/\/ If IsRollingProportional = false, duration in milliseconds for the counter roll-up animation for each\n \/\/\/ element; else duration in milliseconds for the counter roll-up animation in total.\n \/\/\/ <\/summary>\n protected virtual double RollingDuration => 0;\n\n \/\/\/ \n \/\/\/ Easing for the counter rollover animation.\n \/\/\/ <\/summary>\n protected virtual Easing RollingEasing => Easing.OutQuint;\n\n private T displayedCount;\n\n \/\/\/ \n \/\/\/ Value shown at the current moment.\n \/\/\/ <\/summary>\n public virtual T DisplayedCount\n {\n get => displayedCount;\n set\n {\n if (EqualityComparer.Default.Equals(displayedCount, value))\n return;\n\n displayedCount = value;\n UpdateDisplay();\n }\n }\n\n \/\/\/ \n \/\/\/ Skeleton of a numeric counter which value rolls over time.\n \/\/\/ <\/summary>\n protected RollingCounter()\n {\n AutoSizeAxes = Axes.Both;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n displayedCountSpriteText = CreateSpriteText();\n\n UpdateDisplay();\n Child = displayedCountSpriteText;\n }\n\n protected void UpdateDisplay()\n {\n if (displayedCountSpriteText != null)\n displayedCountSpriteText.Text = FormatCount(DisplayedCount);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n Current.BindValueChanged(val => TransformCount(DisplayedCount, val.NewValue), true);\n }\n\n \/\/\/ \n \/\/\/ Sets count value, bypassing rollover animation.\n \/\/\/ <\/summary>\n \/\/\/ New count value.<\/param>\n public virtual void SetCountWithoutRolling(T count)\n {\n Current.Value = count;\n StopRolling();\n }\n\n \/\/\/ \n \/\/\/ Stops rollover animation, forcing the displayed count to be the actual count.\n \/\/\/ <\/summary>\n public virtual void StopRolling()\n {\n FinishTransforms(false, nameof(DisplayedCount));\n DisplayedCount = Current.Value;\n }\n\n \/\/\/ \n \/\/\/ Resets count to default value.\n \/\/\/ <\/summary>\n public virtual void ResetCount()\n {\n SetCountWithoutRolling(default);\n }\n\n \/\/\/ \n \/\/\/ Calculates the duration of the roll-up animation by using the difference between the current visible value\n \/\/\/ and the new final value.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ To be used in conjunction with IsRollingProportional = true.\n \/\/\/ Unless a derived class needs to have a proportional rolling, it is not necessary to override this function.\n \/\/\/ <\/remarks>\n \/\/\/ Current visible value.<\/param>\n \/\/\/ New final value.<\/param>\n \/\/\/ Calculated rollover duration in milliseconds.<\/returns>\n protected virtual double GetProportionalDuration(T currentValue, T newValue)\n {\n return RollingDuration;\n }\n\n \/\/\/ \n \/\/\/ Used to format counts.\n \/\/\/ <\/summary>\n \/\/\/ Count to format.<\/param>\n \/\/\/ Count formatted as a string.<\/returns>\n protected virtual string FormatCount(T count)\n {\n return count.ToString();\n }\n\n \/\/\/ \n \/\/\/ Called when the count is updated to add a transformer that changes the value of the visible count (i.e.\n \/\/\/ implement the rollover animation).\n \/\/\/ <\/summary>\n \/\/\/ Count value before modification.<\/param>\n \/\/\/ Expected count value after modification.<\/param>\n protected virtual void TransformCount(T currentValue, T newValue)\n {\n double rollingTotalDuration =\n IsRollingProportional\n ? GetProportionalDuration(currentValue, newValue)\n : RollingDuration;\n\n this.TransformTo(nameof(DisplayedCount), newValue, rollingTotalDuration, RollingEasing);\n }\n\n protected virtual OsuSpriteText CreateSpriteText() => new OsuSpriteText\n {\n Font = OsuFont.Numeric.With(size: 40f),\n };\n }\n}","smell_code":" public abstract class RollingCounter : Container, IHasCurrentValue\n where T : struct, IEquatable\n {\n private readonly BindableWithCurrent current = new BindableWithCurrent();\n\n public Bindable Current\n {\n get => current.Current;\n set => current.Current = value;\n }\n\n private SpriteText displayedCountSpriteText;\n\n \/\/\/ \n \/\/\/ If true, the roll-up duration will be proportional to change in value.\n \/\/\/ <\/summary>\n protected virtual bool IsRollingProportional => false;\n\n \/\/\/ \n \/\/\/ If IsRollingProportional = false, duration in milliseconds for the counter roll-up animation for each\n \/\/\/ element; else duration in milliseconds for the counter roll-up animation in total.\n \/\/\/ <\/summary>\n protected virtual double RollingDuration => 0;\n\n \/\/\/ \n \/\/\/ Easing for the counter rollover animation.\n \/\/\/ <\/summary>\n protected virtual Easing RollingEasing => Easing.OutQuint;\n\n private T displayedCount;\n\n \/\/\/ \n \/\/\/ Value shown at the current moment.\n \/\/\/ <\/summary>\n public virtual T DisplayedCount\n {\n get => displayedCount;\n set\n {\n if (EqualityComparer.Default.Equals(displayedCount, value))\n return;\n\n displayedCount = value;\n UpdateDisplay();\n }\n }\n\n \/\/\/ \n \/\/\/ Skeleton of a numeric counter which value rolls over time.\n \/\/\/ <\/summary>\n protected RollingCounter()\n {\n AutoSizeAxes = Axes.Both;\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n displayedCountSpriteText = CreateSpriteText();\n\n UpdateDisplay();\n Child = displayedCountSpriteText;\n }\n\n protected void UpdateDisplay()\n {\n if (displayedCountSpriteText != null)\n displayedCountSpriteText.Text = FormatCount(DisplayedCount);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n Current.BindValueChanged(val => TransformCount(DisplayedCount, val.NewValue), true);\n }\n\n \/\/\/ \n \/\/\/ Sets count value, bypassing rollover animation.\n \/\/\/ <\/summary>\n \/\/\/ New count value.<\/param>\n public virtual void SetCountWithoutRolling(T count)\n {\n Current.Value = count;\n StopRolling();\n }\n\n \/\/\/ \n \/\/\/ Stops rollover animation, forcing the displayed count to be the actual count.\n \/\/\/ <\/summary>\n public virtual void StopRolling()\n {\n FinishTransforms(false, nameof(DisplayedCount));\n DisplayedCount = Current.Value;\n }\n\n \/\/\/ \n \/\/\/ Resets count to default value.\n \/\/\/ <\/summary>\n public virtual void ResetCount()\n {\n SetCountWithoutRolling(default);\n }\n\n \/\/\/ \n \/\/\/ Calculates the duration of the roll-up animation by using the difference between the current visible value\n \/\/\/ and the new final value.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ To be used in conjunction with IsRollingProportional = true.\n \/\/\/ Unless a derived class needs to have a proportional rolling, it is not necessary to override this function.\n \/\/\/ <\/remarks>\n \/\/\/ Current visible value.<\/param>\n \/\/\/ New final value.<\/param>\n \/\/\/ Calculated rollover duration in milliseconds.<\/returns>\n protected virtual double GetProportionalDuration(T currentValue, T newValue)\n {\n return RollingDuration;\n }\n\n \/\/\/ \n \/\/\/ Used to format counts.\n \/\/\/ <\/summary>\n \/\/\/ Count to format.<\/param>\n \/\/\/ Count formatted as a string.<\/returns>\n protected virtual string FormatCount(T count)\n {\n return count.ToString();\n }\n\n \/\/\/ \n \/\/\/ Called when the count is updated to add a transformer that changes the value of the visible count (i.e.\n \/\/\/ implement the rollover animation).\n \/\/\/ <\/summary>\n \/\/\/ Count value before modification.<\/param>\n \/\/\/ Expected count value after modification.<\/param>\n protected virtual void TransformCount(T currentValue, T newValue)\n {\n double rollingTotalDuration =\n IsRollingProportional\n ? GetProportionalDuration(currentValue, newValue)\n : RollingDuration;\n\n this.TransformTo(nameof(DisplayedCount), newValue, rollingTotalDuration, RollingEasing);\n }\n\n protected virtual OsuSpriteText CreateSpriteText() => new OsuSpriteText\n {\n Font = OsuFont.Numeric.With(size: 40f),\n };\n }","smell":"large class","id":42} {"lang_cluster":"C#","source_code":"using BurningKnight.assets.lighting;\nusing BurningKnight.entity.component;\nusing BurningKnight.level.biome;\nusing BurningKnight.save;\nusing BurningKnight.state;\nusing ImGuiNET;\nusing Lens.util.file;\nusing Lens.util.math;\nusing Microsoft.Xna.Framework;\n\nnamespace BurningKnight.level.entities.plant {\n\tpublic class Plant : Prop {\n\t\tprivate static string[] variants = {\n\t\t\t\"plant_a\", \"plant_b\", \"plant_c\", \"plant_d\", \"plant_e\", \"plant_f\",\n\t\t\t\"plant_i\", \"plant_j\", \"plant_k\", \"plant_l\", \"plant_m\", \"plant_n\", \"plant_o\" \n\t\t};\n\n\t\tpublic byte Variant;\n\t\t\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\n\t\t\tif (GraphicsComponent == null) {\n\t\t\t\tvar s = variants[Variant % variants.Length];\n\t\t\t\tvar g = Variant == 255 ? new PlantGraphicsComponent(\"props\", Events.Halloween ? \"pumpkin\" : \"cabbadge\")\n\t\t\t\t\t: new PlantGraphicsComponent($\"{Run.Level.Biome.Id}_biome\", $\"{s}{(Variant >= variants.Length ? \"s\" : \"\")}\");\n\t\t\t\t\n\t\t\t\tAddComponent(g);\n\t\t\t\tg.Flipped = Rnd.Chance();\n\n\t\t\t\tWidth = g.Sprite.Width;\n\t\t\t\tHeight = g.Sprite.Height;\n\n\t\t\t\tvar caves = Run.Level.Biome is CaveBiome;\n\n\t\t\t\tif (Variant != 255 && (caves || Run.Depth != 0 || (s != \"plant_k\" && s != \"plant_m\"))) {\n\t\t\t\t\tif (caves) {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, Rnd.Int(16, 32), new Color(0.4f, 0.1f, 0.4f, 1f)));\n\t\t\t\t\t} else if (s == \"plant_m\") {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, 24, new Color(0.4f, 0.4f, 1f, 1f)));\n\t\t\t\t\t} else if (s == \"plant_k\") {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, 24, new Color(1f, 0.4f, 0.4f, 1f)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t\tAddComponent(new ShadowComponent());\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Init() {\n\t\t\tbase.Init();\n\t\t\tVariant = (byte) Rnd.Int(variants.Length * 2);\n\n\t\t\tif (Events.Halloween && Rnd.Chance(10)) {\n\t\t\t\tVariant = 255;\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic override void Load(FileReader stream) {\n\t\t\tbase.Load(stream);\n\t\t\tVariant = stream.ReadByte();\n\t\t}\n\n\t\tpublic override void Save(FileWriter stream) {\n\t\t\tbase.Save(stream);\n\t\t\tstream.WriteByte(Variant);\n\t\t}\n\n\t\tpublic override void RenderImDebug() {\n\t\t\tbase.RenderImDebug();\n\t\t\tvar v = (int) Variant;\n\n\t\t\tif (ImGui.InputInt(\"Id\", ref v)) {\n\t\t\t\tVariant = (byte) v;\n\t\t\t\tRemoveComponent();\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic class Plant : Prop {\n\t\tprivate static string[] variants = {\n\t\t\t\"plant_a\", \"plant_b\", \"plant_c\", \"plant_d\", \"plant_e\", \"plant_f\",\n\t\t\t\"plant_i\", \"plant_j\", \"plant_k\", \"plant_l\", \"plant_m\", \"plant_n\", \"plant_o\" \n\t\t};\n\n\t\tpublic byte Variant;\n\t\t\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\n\t\t\tif (GraphicsComponent == null) {\n\t\t\t\tvar s = variants[Variant % variants.Length];\n\t\t\t\tvar g = Variant == 255 ? new PlantGraphicsComponent(\"props\", Events.Halloween ? \"pumpkin\" : \"cabbadge\")\n\t\t\t\t\t: new PlantGraphicsComponent($\"{Run.Level.Biome.Id}_biome\", $\"{s}{(Variant >= variants.Length ? \"s\" : \"\")}\");\n\t\t\t\t\n\t\t\t\tAddComponent(g);\n\t\t\t\tg.Flipped = Rnd.Chance();\n\n\t\t\t\tWidth = g.Sprite.Width;\n\t\t\t\tHeight = g.Sprite.Height;\n\n\t\t\t\tvar caves = Run.Level.Biome is CaveBiome;\n\n\t\t\t\tif (Variant != 255 && (caves || Run.Depth != 0 || (s != \"plant_k\" && s != \"plant_m\"))) {\n\t\t\t\t\tif (caves) {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, Rnd.Int(16, 32), new Color(0.4f, 0.1f, 0.4f, 1f)));\n\t\t\t\t\t} else if (s == \"plant_m\") {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, 24, new Color(0.4f, 0.4f, 1f, 1f)));\n\t\t\t\t\t} else if (s == \"plant_k\") {\n\t\t\t\t\t\tAddComponent(new LightComponent(this, 24, new Color(1f, 0.4f, 0.4f, 1f)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\n\t\t\t\tAddComponent(new ShadowComponent());\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Init() {\n\t\t\tbase.Init();\n\t\t\tVariant = (byte) Rnd.Int(variants.Length * 2);\n\n\t\t\tif (Events.Halloween && Rnd.Chance(10)) {\n\t\t\t\tVariant = 255;\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic override void Load(FileReader stream) {\n\t\t\tbase.Load(stream);\n\t\t\tVariant = stream.ReadByte();\n\t\t}\n\n\t\tpublic override void Save(FileWriter stream) {\n\t\t\tbase.Save(stream);\n\t\t\tstream.WriteByte(Variant);\n\t\t}\n\n\t\tpublic override void RenderImDebug() {\n\t\t\tbase.RenderImDebug();\n\t\t\tvar v = (int) Variant;\n\n\t\t\tif (ImGui.InputInt(\"Id\", ref v)) {\n\t\t\t\tVariant = (byte) v;\n\t\t\t\tRemoveComponent();\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":43} {"lang_cluster":"C#","source_code":"\ufeffusing Avalonia.Controls;\nusing Avalonia.Markup.Xaml;\n\nnamespace Core2D.Views.Style\n{\n public class TextStyleView : UserControl\n {\n public TextStyleView()\n {\n InitializeComponent();\n }\n\n private void InitializeComponent()\n {\n AvaloniaXamlLoader.Load(this);\n }\n }\n}","smell_code":" public class TextStyleView : UserControl\n {\n public TextStyleView()\n {\n InitializeComponent();\n }\n\n private void InitializeComponent()\n {\n AvaloniaXamlLoader.Load(this);\n }\n }","smell":"large class","id":44} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Input.Events;\nusing osu.Game.Rulesets.Edit;\nusing osu.Game.Rulesets.Mania.Edit.Blueprints.Components;\nusing osu.Game.Rulesets.Mania.Objects;\nusing osu.Game.Rulesets.UI.Scrolling;\nusing osuTK;\nusing osuTK.Input;\n\nnamespace osu.Game.Rulesets.Mania.Edit.Blueprints\n{\n public class HoldNotePlacementBlueprint : ManiaPlacementBlueprint\n {\n private readonly EditBodyPiece bodyPiece;\n private readonly EditNotePiece headPiece;\n private readonly EditNotePiece tailPiece;\n\n [Resolved]\n private IScrollingInfo scrollingInfo { get; set; }\n\n public HoldNotePlacementBlueprint()\n : base(new HoldNote())\n {\n RelativeSizeAxes = Axes.Both;\n\n InternalChildren = new Drawable[]\n {\n bodyPiece = new EditBodyPiece { Origin = Anchor.TopCentre },\n headPiece = new EditNotePiece { Origin = Anchor.Centre },\n tailPiece = new EditNotePiece { Origin = Anchor.Centre }\n };\n }\n\n protected override void Update()\n {\n base.Update();\n\n if (Column != null)\n {\n headPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.StartTime)).Y;\n tailPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.EndTime)).Y;\n\n switch (scrollingInfo.Direction.Value)\n {\n case ScrollingDirection.Down:\n headPiece.Y -= headPiece.DrawHeight \/ 2;\n tailPiece.Y -= tailPiece.DrawHeight \/ 2;\n break;\n\n case ScrollingDirection.Up:\n headPiece.Y += headPiece.DrawHeight \/ 2;\n tailPiece.Y += tailPiece.DrawHeight \/ 2;\n break;\n }\n }\n\n var topPosition = new Vector2(headPiece.DrawPosition.X, Math.Min(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));\n var bottomPosition = new Vector2(headPiece.DrawPosition.X, Math.Max(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));\n\n bodyPiece.Position = topPosition;\n bodyPiece.Width = headPiece.Width;\n bodyPiece.Height = (bottomPosition - topPosition).Y;\n }\n\n protected override void OnMouseUp(MouseUpEvent e)\n {\n if (e.Button != MouseButton.Left)\n return;\n\n base.OnMouseUp(e);\n EndPlacement(true);\n }\n\n private double originalStartTime;\n\n public override void UpdateTimeAndPosition(SnapResult result)\n {\n base.UpdateTimeAndPosition(result);\n\n if (PlacementActive)\n {\n if (result.Time is double endTime)\n {\n HitObject.StartTime = endTime < originalStartTime ? endTime : originalStartTime;\n HitObject.Duration = Math.Abs(endTime - originalStartTime);\n }\n }\n else\n {\n if (result.Playfield != null)\n {\n headPiece.Width = tailPiece.Width = result.Playfield.DrawWidth;\n headPiece.X = tailPiece.X = ToLocalSpace(result.ScreenSpacePosition).X;\n }\n\n if (result.Time is double startTime)\n originalStartTime = HitObject.StartTime = startTime;\n }\n }\n }\n}","smell_code":" public class HoldNotePlacementBlueprint : ManiaPlacementBlueprint\n {\n private readonly EditBodyPiece bodyPiece;\n private readonly EditNotePiece headPiece;\n private readonly EditNotePiece tailPiece;\n\n [Resolved]\n private IScrollingInfo scrollingInfo { get; set; }\n\n public HoldNotePlacementBlueprint()\n : base(new HoldNote())\n {\n RelativeSizeAxes = Axes.Both;\n\n InternalChildren = new Drawable[]\n {\n bodyPiece = new EditBodyPiece { Origin = Anchor.TopCentre },\n headPiece = new EditNotePiece { Origin = Anchor.Centre },\n tailPiece = new EditNotePiece { Origin = Anchor.Centre }\n };\n }\n\n protected override void Update()\n {\n base.Update();\n\n if (Column != null)\n {\n headPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.StartTime)).Y;\n tailPiece.Y = Parent.ToLocalSpace(Column.ScreenSpacePositionAtTime(HitObject.EndTime)).Y;\n\n switch (scrollingInfo.Direction.Value)\n {\n case ScrollingDirection.Down:\n headPiece.Y -= headPiece.DrawHeight \/ 2;\n tailPiece.Y -= tailPiece.DrawHeight \/ 2;\n break;\n\n case ScrollingDirection.Up:\n headPiece.Y += headPiece.DrawHeight \/ 2;\n tailPiece.Y += tailPiece.DrawHeight \/ 2;\n break;\n }\n }\n\n var topPosition = new Vector2(headPiece.DrawPosition.X, Math.Min(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));\n var bottomPosition = new Vector2(headPiece.DrawPosition.X, Math.Max(headPiece.DrawPosition.Y, tailPiece.DrawPosition.Y));\n\n bodyPiece.Position = topPosition;\n bodyPiece.Width = headPiece.Width;\n bodyPiece.Height = (bottomPosition - topPosition).Y;\n }\n\n protected override void OnMouseUp(MouseUpEvent e)\n {\n if (e.Button != MouseButton.Left)\n return;\n\n base.OnMouseUp(e);\n EndPlacement(true);\n }\n\n private double originalStartTime;\n\n public override void UpdateTimeAndPosition(SnapResult result)\n {\n base.UpdateTimeAndPosition(result);\n\n if (PlacementActive)\n {\n if (result.Time is double endTime)\n {\n HitObject.StartTime = endTime < originalStartTime ? endTime : originalStartTime;\n HitObject.Duration = Math.Abs(endTime - originalStartTime);\n }\n }\n else\n {\n if (result.Playfield != null)\n {\n headPiece.Width = tailPiece.Width = result.Playfield.DrawWidth;\n headPiece.X = tailPiece.X = ToLocalSpace(result.ScreenSpacePosition).X;\n }\n\n if (result.Time is double startTime)\n originalStartTime = HitObject.StartTime = startTime;\n }\n }\n }","smell":"large class","id":45} {"lang_cluster":"C#","source_code":"#pragma warning disable CS1591\n\nusing System;\nusing Jellyfin.Data.Entities;\nusing MediaBrowser.Model.Notifications;\n\nnamespace MediaBrowser.Controller.Notifications\n{\n public class UserNotification\n {\n public string Name { get; set; }\n\n public string Description { get; set; }\n\n public string Url { get; set; }\n\n public NotificationLevel Level { get; set; }\n\n public DateTime Date { get; set; }\n\n public User User { get; set; }\n }\n}","smell_code":" public class UserNotification\n {\n public string Name { get; set; }\n\n public string Description { get; set; }\n\n public string Url { get; set; }\n\n public NotificationLevel Level { get; set; }\n\n public DateTime Date { get; set; }\n\n public User User { get; set; }\n }","smell":"large class","id":46} {"lang_cluster":"C#","source_code":"\/\/ MIT License - Copyright (C) The Mono.Xna Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing System;\nusing System.Collections.Generic;\nusing MonoGame.Framework.Utilities;\n\nnamespace Microsoft.Xna.Framework\n{\n \/\/\/ \n \/\/\/ A container for services for a .\n \/\/\/ <\/summary>\n public class GameServiceContainer : IServiceProvider\n {\n Dictionary services;\n\n \/\/\/ \n \/\/\/ Create an empty .\n \/\/\/ <\/summary>\n public GameServiceContainer()\n {\n services = new Dictionary();\n }\n\n \/\/\/ \n \/\/\/ Add a service provider to this container.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/param>\n \/\/\/ The provider of the service.<\/param>\n \/\/\/ \n \/\/\/ If or is null<\/code>.\n \/\/\/ <\/exception>\n \/\/\/ \n \/\/\/ If cannot be assigned to .\n \/\/\/ <\/exception>\n public void AddService(Type type, object provider)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n if (provider == null)\n throw new ArgumentNullException(\"provider\");\n if (!ReflectionHelpers.IsAssignableFrom(type, provider))\n throw new ArgumentException(\"The provider does not match the specified service type!\");\n\n services.Add(type, provider);\n }\n\n \/\/\/ \n \/\/\/ Get a service provider for the service of the specified type.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/param>\n \/\/\/ \n \/\/\/ A service provider for the service of the specified type or null<\/code> if\n \/\/\/ no suitable service provider is registered in this container.\n \/\/\/ <\/returns>\n \/\/\/ If the specified type is null<\/code>.<\/exception>\n public object GetService(Type type)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n\t\t\t\t\t\t\n object service;\n if (services.TryGetValue(type, out service))\n return service;\n\n return null;\n }\n\n \/\/\/ \n \/\/\/ Remove the service with the specified type. Does nothing no service of the specified type is registered.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service to remove.<\/param>\n \/\/\/ If the specified type is null<\/code>.<\/exception>\n public void RemoveService(Type type)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n\n services.Remove(type);\n }\n \n \/\/\/ \n \/\/\/ Add a service provider to this container.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/typeparam>\n \/\/\/ The provider of the service.<\/param>\n \/\/\/ \n \/\/\/ If is null<\/code>.\n \/\/\/ <\/exception>\n public void AddService(T provider)\n {\n AddService(typeof(T), provider);\n }\n\n \/\/\/ \n \/\/\/ Get a service provider of the specified type.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service provider.<\/typeparam>\n \/\/\/ \n \/\/\/ A service provider of the specified type or null<\/code> if\n \/\/\/ no suitable service provider is registered in this container.\n \/\/\/ <\/returns>\n \tpublic T GetService() where T : class\n {\n var service = GetService(typeof(T));\n\n if (service == null)\n return null;\n\n return (T)service;\n }\n }\n}","smell_code":" public class GameServiceContainer : IServiceProvider\n {\n Dictionary services;\n\n \/\/\/ \n \/\/\/ Create an empty .\n \/\/\/ <\/summary>\n public GameServiceContainer()\n {\n services = new Dictionary();\n }\n\n \/\/\/ \n \/\/\/ Add a service provider to this container.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/param>\n \/\/\/ The provider of the service.<\/param>\n \/\/\/ \n \/\/\/ If or is null<\/code>.\n \/\/\/ <\/exception>\n \/\/\/ \n \/\/\/ If cannot be assigned to .\n \/\/\/ <\/exception>\n public void AddService(Type type, object provider)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n if (provider == null)\n throw new ArgumentNullException(\"provider\");\n if (!ReflectionHelpers.IsAssignableFrom(type, provider))\n throw new ArgumentException(\"The provider does not match the specified service type!\");\n\n services.Add(type, provider);\n }\n\n \/\/\/ \n \/\/\/ Get a service provider for the service of the specified type.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/param>\n \/\/\/ \n \/\/\/ A service provider for the service of the specified type or null<\/code> if\n \/\/\/ no suitable service provider is registered in this container.\n \/\/\/ <\/returns>\n \/\/\/ If the specified type is null<\/code>.<\/exception>\n public object GetService(Type type)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n\t\t\t\t\t\t\n object service;\n if (services.TryGetValue(type, out service))\n return service;\n\n return null;\n }\n\n \/\/\/ \n \/\/\/ Remove the service with the specified type. Does nothing no service of the specified type is registered.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service to remove.<\/param>\n \/\/\/ If the specified type is null<\/code>.<\/exception>\n public void RemoveService(Type type)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n\n services.Remove(type);\n }\n \n \/\/\/ \n \/\/\/ Add a service provider to this container.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service.<\/typeparam>\n \/\/\/ The provider of the service.<\/param>\n \/\/\/ \n \/\/\/ If is null<\/code>.\n \/\/\/ <\/exception>\n public void AddService(T provider)\n {\n AddService(typeof(T), provider);\n }\n\n \/\/\/ \n \/\/\/ Get a service provider of the specified type.\n \/\/\/ <\/summary>\n \/\/\/ The type of the service provider.<\/typeparam>\n \/\/\/ \n \/\/\/ A service provider of the specified type or null<\/code> if\n \/\/\/ no suitable service provider is registered in this container.\n \/\/\/ <\/returns>\n \tpublic T GetService() where T : class\n {\n var service = GetService(typeof(T));\n\n if (service == null)\n return null;\n\n return (T)service;\n }\n }","smell":"large class","id":47} {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Mvc.ModelBinding;\nusing Microsoft.Extensions.Logging;\n\nnamespace Jellyfin.Api.ModelBinders\n{\n \/\/\/ \n \/\/\/ Comma delimited array model binder.\n \/\/\/ Returns an empty array of specified type if there is no query parameter.\n \/\/\/ <\/summary>\n public class CommaDelimitedArrayModelBinder : IModelBinder\n {\n private readonly ILogger _logger;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ Instance of the interface.<\/param>\n public CommaDelimitedArrayModelBinder(ILogger logger)\n {\n _logger = logger;\n }\n\n \/\/\/ \n public Task BindModelAsync(ModelBindingContext bindingContext)\n {\n var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];\n var converter = TypeDescriptor.GetConverter(elementType);\n\n if (valueProviderResult.Length > 1)\n {\n var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);\n bindingContext.Result = ModelBindingResult.Success(typedValues);\n }\n else\n {\n var value = valueProviderResult.FirstValue;\n\n if (value != null)\n {\n var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries);\n var typedValues = GetParsedResult(splitValues, elementType, converter);\n bindingContext.Result = ModelBindingResult.Success(typedValues);\n }\n else\n {\n var emptyResult = Array.CreateInstance(elementType, 0);\n bindingContext.Result = ModelBindingResult.Success(emptyResult);\n }\n }\n\n return Task.CompletedTask;\n }\n\n private Array GetParsedResult(IReadOnlyList values, Type elementType, TypeConverter converter)\n {\n var parsedValues = new object?[values.Count];\n var convertedCount = 0;\n for (var i = 0; i < values.Count; i++)\n {\n try\n {\n parsedValues[i] = converter.ConvertFromString(values[i].Trim());\n convertedCount++;\n }\n catch (FormatException e)\n {\n _logger.LogDebug(e, \"Error converting value.\");\n }\n }\n\n var typedValues = Array.CreateInstance(elementType, convertedCount);\n var typedValueIndex = 0;\n for (var i = 0; i < parsedValues.Length; i++)\n {\n if (parsedValues[i] != null)\n {\n typedValues.SetValue(parsedValues[i], typedValueIndex);\n typedValueIndex++;\n }\n }\n\n return typedValues;\n }\n }\n}","smell_code":" public class CommaDelimitedArrayModelBinder : IModelBinder\n {\n private readonly ILogger _logger;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ Instance of the interface.<\/param>\n public CommaDelimitedArrayModelBinder(ILogger logger)\n {\n _logger = logger;\n }\n\n \/\/\/ \n public Task BindModelAsync(ModelBindingContext bindingContext)\n {\n var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];\n var converter = TypeDescriptor.GetConverter(elementType);\n\n if (valueProviderResult.Length > 1)\n {\n var typedValues = GetParsedResult(valueProviderResult.Values, elementType, converter);\n bindingContext.Result = ModelBindingResult.Success(typedValues);\n }\n else\n {\n var value = valueProviderResult.FirstValue;\n\n if (value != null)\n {\n var splitValues = value.Split(',', StringSplitOptions.RemoveEmptyEntries);\n var typedValues = GetParsedResult(splitValues, elementType, converter);\n bindingContext.Result = ModelBindingResult.Success(typedValues);\n }\n else\n {\n var emptyResult = Array.CreateInstance(elementType, 0);\n bindingContext.Result = ModelBindingResult.Success(emptyResult);\n }\n }\n\n return Task.CompletedTask;\n }\n\n private Array GetParsedResult(IReadOnlyList values, Type elementType, TypeConverter converter)\n {\n var parsedValues = new object?[values.Count];\n var convertedCount = 0;\n for (var i = 0; i < values.Count; i++)\n {\n try\n {\n parsedValues[i] = converter.ConvertFromString(values[i].Trim());\n convertedCount++;\n }\n catch (FormatException e)\n {\n _logger.LogDebug(e, \"Error converting value.\");\n }\n }\n\n var typedValues = Array.CreateInstance(elementType, convertedCount);\n var typedValueIndex = 0;\n for (var i = 0; i < parsedValues.Length; i++)\n {\n if (parsedValues[i] != null)\n {\n typedValues.SetValue(parsedValues[i], typedValueIndex);\n typedValueIndex++;\n }\n }\n\n return typedValues;\n }\n }","smell":"large class","id":48} {"lang_cluster":"C#","source_code":"#pragma warning disable CS1591\n\nusing System;\nusing MediaBrowser.Controller.Entities;\nusing MediaBrowser.Controller.Sorting;\nusing MediaBrowser.Model.Querying;\n\nnamespace Emby.Server.Implementations.Sorting\n{\n public class SeriesSortNameComparer : IBaseItemComparer\n {\n \/\/\/ \n \/\/\/ Gets the name.\n \/\/\/ <\/summary>\n \/\/\/ The name.<\/value>\n public string Name => ItemSortBy.SeriesSortName;\n\n \/\/\/ \n \/\/\/ Compares the specified x.\n \/\/\/ <\/summary>\n \/\/\/ The x.<\/param>\n \/\/\/ The y.<\/param>\n \/\/\/ System.Int32.<\/returns>\n public int Compare(BaseItem x, BaseItem y)\n {\n return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);\n }\n\n private static string GetValue(BaseItem item)\n {\n var hasSeries = item as IHasSeries;\n\n return hasSeries?.FindSeriesSortName();\n }\n }\n}","smell_code":" public class SeriesSortNameComparer : IBaseItemComparer\n {\n \/\/\/ \n \/\/\/ Gets the name.\n \/\/\/ <\/summary>\n \/\/\/ The name.<\/value>\n public string Name => ItemSortBy.SeriesSortName;\n\n \/\/\/ \n \/\/\/ Compares the specified x.\n \/\/\/ <\/summary>\n \/\/\/ The x.<\/param>\n \/\/\/ The y.<\/param>\n \/\/\/ System.Int32.<\/returns>\n public int Compare(BaseItem x, BaseItem y)\n {\n return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);\n }\n\n private static string GetValue(BaseItem item)\n {\n var hasSeries = item as IHasSeries;\n\n return hasSeries?.FindSeriesSortName();\n }\n }","smell":"large class","id":49} {"lang_cluster":"C#","source_code":"using System.Collections.Generic;\nusing Lens.entity;\n\nnamespace BurningKnight.entity {\n\tpublic class RenderTriggerManager {\n\t\tprivate Entity entity;\n\t\tprivate List triggers = new List();\n\t\t\n\t\tpublic RenderTriggerManager(Entity e) {\n\t\t\tentity = e;\n\t\t}\n\t\t\n\t\tpublic void Add(RenderTrigger trigger) {\n\t\t\tentity.Area.Add(trigger);\n\t\t\ttriggers.Add(trigger);\n\t\t}\n\n\t\tpublic void Update() {\n\t\t\tif (entity.Done) {\n\t\t\t\tDestroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tforeach (var t in triggers) {\n\t\t\t\tif (t.Done || t.Area != entity.Area) {\n\t\t\t\t\tt.Done = false;\n\t\t\t\t\tt.Area = null;\n\t\t\t\t\tt.Components = null;\n\t\t\t\t\tentity.Area.Add(t);\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\n\t\tpublic void Destroy() {\n\t\t\tforeach (var t in triggers) {\n\t\t\t\tt.Done = true;\n\t\t\t\tentity.Area.Remove(t);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic class RenderTriggerManager {\n\t\tprivate Entity entity;\n\t\tprivate List triggers = new List();\n\t\t\n\t\tpublic RenderTriggerManager(Entity e) {\n\t\t\tentity = e;\n\t\t}\n\t\t\n\t\tpublic void Add(RenderTrigger trigger) {\n\t\t\tentity.Area.Add(trigger);\n\t\t\ttriggers.Add(trigger);\n\t\t}\n\n\t\tpublic void Update() {\n\t\t\tif (entity.Done) {\n\t\t\t\tDestroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tforeach (var t in triggers) {\n\t\t\t\tif (t.Done || t.Area != entity.Area) {\n\t\t\t\t\tt.Done = false;\n\t\t\t\t\tt.Area = null;\n\t\t\t\t\tt.Components = null;\n\t\t\t\t\tentity.Area.Add(t);\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\n\t\tpublic void Destroy() {\n\t\t\tforeach (var t in triggers) {\n\t\t\t\tt.Done = true;\n\t\t\t\tentity.Area.Remove(t);\n\t\t\t}\n\t\t}\n\t}","smell":"large class","id":50} {"lang_cluster":"C#","source_code":"using BurningKnight.assets.particle.custom;\nusing BurningKnight.entity.component;\n\nnamespace BurningKnight.debug {\n\tpublic class GodModeCommand : ConsoleCommand {\n\t\tpublic GodModeCommand() {\n\t\t\t_Init();\n\t\t}\n\n\t\tprotected void _Init() {\n\t\t\t{\n\t\t\t\tName = \"gm\";\n\t\t\t\tShortName = \"g\";\n\t\t\t}\n\t\t}\n\n\t\tpublic override void Run(Console Console, string[] Args) {\n\t\t\tvar all = Console.GameArea.Tagged[Tags.Player];\n\t\t\t\n\t\t\tforeach (var player in all) {\n\t\t\t\tvar health = player.GetComponent();\n\t\t\t\thealth.Unhittable = !health.Unhittable;\n\t\t\t\t\n\t\t\t\tTextParticle.Add(player, \"God Mode\", 1, true, !health.Unhittable);\n\t\t\t\tConsole.Print(health.Unhittable ? \"God mode is on\" : \"God mode is off\");\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}","smell_code":"\t\tprotected void _Init() {\n\t\t\t{\n\t\t\t\tName = \"gm\";\n\t\t\t\tShortName = \"g\";\n\t\t\t}\n\t\t}","smell":"long method","id":51} {"lang_cluster":"C#","source_code":"using System;\nusing System.Threading;\nusing MediaBrowser.Controller.Session;\nusing MediaBrowser.Controller.SyncPlay.PlaybackRequests;\nusing MediaBrowser.Model.SyncPlay;\nusing Microsoft.Extensions.Logging;\n\nnamespace MediaBrowser.Controller.SyncPlay.GroupStates\n{\n \/\/\/ \n \/\/\/ Class PlayingGroupState.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ Class is not thread-safe, external locking is required when accessing methods.\n \/\/\/ <\/remarks>\n public class PlayingGroupState : AbstractGroupState\n {\n \/\/\/ \n \/\/\/ The logger.\n \/\/\/ <\/summary>\n private readonly ILogger _logger;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ Instance of the interface.<\/param>\n public PlayingGroupState(ILoggerFactory loggerFactory)\n : base(loggerFactory)\n {\n _logger = LoggerFactory.CreateLogger();\n }\n\n \/\/\/ \n public override GroupStateType Type { get; } = GroupStateType.Playing;\n\n \/\/\/ \n \/\/\/ Gets or sets a value indicating whether requests for buffering should be ignored.\n \/\/\/ <\/summary>\n public bool IgnoreBuffering { get; set; }\n\n \/\/\/ \n public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Wait for session to be ready.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.SessionJoined(context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Do nothing.\n }\n\n \/\/\/ \n public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n if (!prevState.Equals(Type))\n {\n \/\/ Pick a suitable time that accounts for latency.\n var delayMillis = Math.Max(context.GetHighestPing() * 2, context.DefaultPing);\n\n \/\/ Unpause group and set starting point in future.\n \/\/ Clients will start playback at LastActivity (datetime) from PositionTicks (playback position).\n \/\/ The added delay does not guarantee, of course, that the command will be received in time.\n \/\/ Playback synchronization will mainly happen client side.\n context.LastActivity = DateTime.UtcNow.AddMilliseconds(delayMillis);\n\n var command = context.NewSyncPlayCommand(SendCommandType.Unpause);\n context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);\n\n \/\/ Notify relevant state change event.\n SendGroupStateUpdate(context, request, session, cancellationToken);\n }\n else\n {\n \/\/ Client got lost, sending current state.\n var command = context.NewSyncPlayCommand(SendCommandType.Unpause);\n context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);\n }\n }\n\n \/\/\/ \n public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var pausedState = new PausedGroupState(LoggerFactory);\n context.SetState(pausedState);\n pausedState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var idleState = new IdleGroupState(LoggerFactory);\n context.SetState(idleState);\n idleState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n if (IgnoreBuffering)\n {\n return;\n }\n\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n if (prevState.Equals(Type))\n {\n \/\/ Group was not waiting, make sure client has latest state.\n var command = context.NewSyncPlayCommand(SendCommandType.Unpause);\n context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);\n }\n else if (prevState.Equals(GroupStateType.Waiting))\n {\n \/\/ Notify relevant state change event.\n SendGroupStateUpdate(context, request, session, cancellationToken);\n }\n }\n\n \/\/\/ \n public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n }\n}","smell_code":" public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n if (IgnoreBuffering)\n {\n return;\n }\n\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }","smell":"long method","id":52} {"lang_cluster":"C#","source_code":"\ufeffusing System.Collections.Immutable;\nusing System.Runtime.Serialization;\nusing Core2D.Bindings;\nusing Core2D.Containers;\nusing Core2D.Shapes;\n\nnamespace Core2D.Data\n{\n [DataContract(IsReference = true)]\n public class DataFlow\n {\n public void Bind(ProjectContainer project)\n {\n foreach (var document in project.Documents)\n {\n Bind(document);\n }\n }\n\n public void Bind(DocumentContainer document)\n {\n foreach (var container in document.Pages)\n {\n var db = container.Properties;\n var r = container.Record;\n\n Bind(container.Template, db, r);\n Bind(container, db, r);\n }\n }\n\n public void Bind(PageContainer container, object db, object r)\n {\n foreach (var layer in container.Layers)\n {\n Bind(layer, db, r);\n }\n }\n\n public void Bind(LayerContainer layer, object db, object r)\n {\n foreach (var shape in layer.Shapes)\n {\n shape.Bind(this, db, r);\n }\n }\n\n public void Bind(LineShape line, object db, object r)\n {\n }\n\n public void Bind(RectangleShape rectangle, object db, object r)\n {\n }\n\n public void Bind(EllipseShape ellipse, object db, object r)\n {\n }\n\n public void Bind(ArcShape arc, object db, object r)\n {\n }\n\n public void Bind(CubicBezierShape cubicBezier, object db, object r)\n {\n }\n\n public void Bind(QuadraticBezierShape quadraticBezier, object db, object r)\n {\n }\n\n public void Bind(TextShape text, object db, object r)\n {\n var properties = (ImmutableArray)db;\n var record = (Record)r;\n var tbind = TextBinding.Bind(text, properties, record);\n text.SetProperty(nameof(TextShape.Text), tbind);\n }\n\n public void Bind(ImageShape image, object db, object r)\n {\n }\n\n public void Bind(PathShape path, object db, object r)\n {\n }\n }\n}","smell_code":" public void Bind(DocumentContainer document)\n {\n foreach (var container in document.Pages)\n {\n var db = container.Properties;\n var r = container.Record;\n\n Bind(container.Template, db, r);\n Bind(container, db, r);\n }\n }","smell":"long method","id":53} {"lang_cluster":"C#","source_code":"\ufeffusing System;\nusing System.IO;\nusing Core2D;\nusing Core2D.Containers;\nusing Core2D.Data;\nusing Core2D.Renderer;\nusing Core2D.Renderer.Presenters;\nusing Core2D.Renderer.SkiaSharp;\n\nnamespace Core2D.FileWriter.SkiaSharpWebp\n{\n public sealed class WebpSkiaSharpWriter : IFileWriter\n {\n private readonly IServiceProvider _serviceProvider;\n\n public WebpSkiaSharpWriter(IServiceProvider serviceProvider)\n {\n _serviceProvider = serviceProvider;\n }\n\n public string Name { get; } = \"Webp (SkiaSharp)\";\n\n public string Extension { get; } = \"webp\";\n\n public void Save(Stream stream, object item, object options)\n {\n if (item == null)\n {\n return;\n }\n\n var ic = options as IImageCache;\n if (options == null)\n {\n return;\n }\n\n var renderer = new SkiaSharpRenderer(_serviceProvider);\n renderer.State.DrawShapeState.Flags = ShapeStateFlags.Printable;\n renderer.State.ImageCache = ic;\n\n var presenter = new ExportPresenter();\n\n IProjectExporter exporter = new WebpSkiaSharpExporter(renderer, presenter);\n\n if (item is PageContainer page)\n {\n var dataFlow = _serviceProvider.GetService();\n var db = (object)page.Properties;\n var record = (object)page.Record;\n\n dataFlow.Bind(page.Template, db, record);\n dataFlow.Bind(page, db, record);\n\n exporter.Save(stream, page);\n }\n else if (item is DocumentContainer document)\n {\n throw new NotSupportedException(\"Saving documents as webp drawing is not supported.\");\n }\n else if (item is ProjectContainer project)\n {\n throw new NotSupportedException(\"Saving projects as webp drawing is not supported.\");\n }\n }\n }\n}","smell_code":" public void Save(Stream stream, object item, object options)\n {\n if (item == null)\n {\n return;\n }\n\n var ic = options as IImageCache;\n if (options == null)\n {\n return;\n }\n\n var renderer = new SkiaSharpRenderer(_serviceProvider);\n renderer.State.DrawShapeState.Flags = ShapeStateFlags.Printable;\n renderer.State.ImageCache = ic;\n\n var presenter = new ExportPresenter();\n\n IProjectExporter exporter = new WebpSkiaSharpExporter(renderer, presenter);\n\n if (item is PageContainer page)\n {\n var dataFlow = _serviceProvider.GetService();\n var db = (object)page.Properties;\n var record = (object)page.Record;\n\n dataFlow.Bind(page.Template, db, record);\n dataFlow.Bind(page, db, record);\n\n exporter.Save(stream, page);\n }\n else if (item is DocumentContainer document)\n {\n throw new NotSupportedException(\"Saving documents as webp drawing is not supported.\");\n }\n else if (item is ProjectContainer project)\n {\n throw new NotSupportedException(\"Saving projects as webp drawing is not supported.\");\n }\n }","smell":"long method","id":54} {"lang_cluster":"C#","source_code":"#nullable disable\n#pragma warning disable CS1591\n\nusing System;\nusing MediaBrowser.Model.Dto;\n\nnamespace MediaBrowser.Model.Dlna\n{\n \/\/\/ \n \/\/\/ Class AudioOptions.\n \/\/\/ <\/summary>\n public class AudioOptions\n {\n public AudioOptions()\n {\n Context = EncodingContext.Streaming;\n\n EnableDirectPlay = true;\n EnableDirectStream = true;\n }\n\n public bool EnableDirectPlay { get; set; }\n\n public bool EnableDirectStream { get; set; }\n\n public bool ForceDirectPlay { get; set; }\n\n public bool ForceDirectStream { get; set; }\n\n public Guid ItemId { get; set; }\n\n public MediaSourceInfo[] MediaSources { get; set; }\n\n public DeviceProfile Profile { get; set; }\n\n \/\/\/ \n \/\/\/ Optional. Only needed if a specific AudioStreamIndex or SubtitleStreamIndex are requested.\n \/\/\/ <\/summary>\n public string MediaSourceId { get; set; }\n\n public string DeviceId { get; set; }\n\n \/\/\/ \n \/\/\/ Allows an override of supported number of audio channels\n \/\/\/ Example: DeviceProfile supports five channel, but user only has stereo speakers\n \/\/\/ <\/summary>\n public int? MaxAudioChannels { get; set; }\n\n \/\/\/ \n \/\/\/ The application's configured quality setting.\n \/\/\/ <\/summary>\n public int? MaxBitrate { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the context.\n \/\/\/ <\/summary>\n \/\/\/ The context.<\/value>\n public EncodingContext Context { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the audio transcoding bitrate.\n \/\/\/ <\/summary>\n \/\/\/ The audio transcoding bitrate.<\/value>\n public int? AudioTranscodingBitrate { get; set; }\n\n \/\/\/ \n \/\/\/ Gets the maximum bitrate.\n \/\/\/ <\/summary>\n \/\/\/ System.Nullable<System.Int32>.<\/returns>\n public int? GetMaxBitrate(bool isAudio)\n {\n if (MaxBitrate.HasValue)\n {\n return MaxBitrate;\n }\n\n if (Profile == null)\n {\n return null;\n }\n\n if (Context == EncodingContext.Static)\n {\n if (isAudio && Profile.MaxStaticMusicBitrate.HasValue)\n {\n return Profile.MaxStaticMusicBitrate;\n }\n\n return Profile.MaxStaticBitrate;\n }\n\n return Profile.MaxStreamingBitrate;\n }\n }\n}","smell_code":" public int? GetMaxBitrate(bool isAudio)\n {\n if (MaxBitrate.HasValue)\n {\n return MaxBitrate;\n }\n\n if (Profile == null)\n {\n return null;\n }\n\n if (Context == EncodingContext.Static)\n {\n if (isAudio && Profile.MaxStaticMusicBitrate.HasValue)\n {\n return Profile.MaxStaticMusicBitrate;\n }\n\n return Profile.MaxStaticBitrate;\n }\n\n return Profile.MaxStreamingBitrate;\n }","smell":"long method","id":55} {"lang_cluster":"C#","source_code":"using System.Threading;\nusing MediaBrowser.Controller.Session;\nusing MediaBrowser.Controller.SyncPlay.PlaybackRequests;\nusing MediaBrowser.Model.SyncPlay;\nusing Microsoft.Extensions.Logging;\n\nnamespace MediaBrowser.Controller.SyncPlay.GroupStates\n{\n \/\/\/ \n \/\/\/ Class IdleGroupState.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ Class is not thread-safe, external locking is required when accessing methods.\n \/\/\/ <\/remarks>\n public class IdleGroupState : AbstractGroupState\n {\n \/\/\/ \n \/\/\/ The logger.\n \/\/\/ <\/summary>\n private readonly ILogger _logger;\n\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ Instance of the interface.<\/param>\n public IdleGroupState(ILoggerFactory loggerFactory)\n : base(loggerFactory)\n {\n _logger = LoggerFactory.CreateLogger();\n }\n\n \/\/\/ \n public override GroupStateType Type { get; } = GroupStateType.Idle;\n\n \/\/\/ \n public override void SessionJoined(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void SessionLeaving(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Do nothing.\n }\n\n \/\/\/ \n public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(UnpauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(PauseGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, prevState, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(StopGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, prevState, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(SeekGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, prevState, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(BufferGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, prevState, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(ReadyGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n SendStopCommand(context, prevState, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(NextItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n \/\/\/ \n public override void HandleRequest(PreviousItemGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }\n\n private void SendStopCommand(IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n var command = context.NewSyncPlayCommand(SendCommandType.Stop);\n if (!prevState.Equals(Type))\n {\n context.SendCommand(session, SyncPlayBroadcastType.AllGroup, command, cancellationToken);\n }\n else\n {\n context.SendCommand(session, SyncPlayBroadcastType.CurrentSession, command, cancellationToken);\n }\n }\n }\n}","smell_code":" public override void HandleRequest(PlayGroupRequest request, IGroupStateContext context, GroupStateType prevState, SessionInfo session, CancellationToken cancellationToken)\n {\n \/\/ Change state.\n var waitingState = new WaitingGroupState(LoggerFactory);\n context.SetState(waitingState);\n waitingState.HandleRequest(request, context, Type, session, cancellationToken);\n }","smell":"long method","id":56} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Shapes;\nusing osu.Game.Online.API.Requests.Responses;\n\nnamespace osu.Game.Overlays.Changelog\n{\n public class ChangelogHeader : BreadcrumbControlOverlayHeader\n {\n public readonly Bindable Build = new Bindable();\n\n public Action ListingSelected;\n\n public ChangelogUpdateStreamControl Streams;\n\n private const string listing_string = \"listing\";\n\n private Box streamsBackground;\n\n public ChangelogHeader()\n {\n TabControl.AddItem(listing_string);\n Current.ValueChanged += e =>\n {\n if (e.NewValue == listing_string)\n ListingSelected?.Invoke();\n };\n\n Build.ValueChanged += showBuild;\n\n Streams.Current.ValueChanged += e =>\n {\n if (e.NewValue?.LatestBuild != null && !e.NewValue.Equals(Build.Value?.UpdateStream))\n Build.Value = e.NewValue.LatestBuild;\n };\n }\n\n [BackgroundDependencyLoader]\n private void load(OverlayColourProvider colourProvider)\n {\n streamsBackground.Colour = colourProvider.Background5;\n }\n\n private void showBuild(ValueChangedEvent e)\n {\n if (e.OldValue != null)\n TabControl.RemoveItem(e.OldValue.ToString());\n\n if (e.NewValue != null)\n {\n TabControl.AddItem(e.NewValue.ToString());\n Current.Value = e.NewValue.ToString();\n\n updateCurrentStream();\n }\n else\n {\n Current.Value = listing_string;\n Streams.Current.Value = null;\n }\n }\n\n protected override Drawable CreateBackground() => new OverlayHeaderBackground(@\"Headers\/changelog\");\n\n protected override Drawable CreateContent() => new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Children = new Drawable[]\n {\n streamsBackground = new Box\n {\n RelativeSizeAxes = Axes.Both\n },\n new Container\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Padding = new MarginPadding\n {\n Horizontal = 65,\n Vertical = 20\n },\n Child = Streams = new ChangelogUpdateStreamControl()\n }\n }\n };\n\n protected override OverlayTitle CreateTitle() => new ChangelogHeaderTitle();\n\n public void Populate(List streams)\n {\n Streams.Populate(streams);\n updateCurrentStream();\n }\n\n private void updateCurrentStream()\n {\n if (Build.Value == null)\n return;\n\n Streams.Current.Value = Streams.Items.FirstOrDefault(s => s.Name == Build.Value.UpdateStream.Name);\n }\n\n private class ChangelogHeaderTitle : OverlayTitle\n {\n public ChangelogHeaderTitle()\n {\n Title = \"changelog\";\n Description = \"track recent dev updates in the osu! ecosystem\";\n IconTexture = \"Icons\/Hexacons\/devtools\";\n }\n }\n }\n}","smell_code":" public ChangelogHeader()\n {\n TabControl.AddItem(listing_string);\n Current.ValueChanged += e =>\n {\n if (e.NewValue == listing_string)\n ListingSelected?.Invoke();\n };\n\n Build.ValueChanged += showBuild;\n\n Streams.Current.ValueChanged += e =>\n {\n if (e.NewValue?.LatestBuild != null && !e.NewValue.Equals(Build.Value?.UpdateStream))\n Build.Value = e.NewValue.LatestBuild;\n };\n }","smell":"long method","id":57} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Linq;\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Game.Beatmaps.ControlPoints;\nusing osu.Game.Graphics;\nusing osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations;\nusing osuTK.Graphics;\n\nnamespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts\n{\n public class GroupVisualisation : PointVisualisation\n {\n public readonly ControlPointGroup Group;\n\n private readonly IBindableList controlPoints = new BindableList();\n\n [Resolved]\n private OsuColour colours { get; set; }\n\n public GroupVisualisation(ControlPointGroup group)\n : base(group.Time)\n {\n Group = group;\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n\n controlPoints.BindTo(Group.ControlPoints);\n controlPoints.BindCollectionChanged((_, __) =>\n {\n if (controlPoints.Count == 0)\n {\n Colour = Color4.Transparent;\n return;\n }\n\n Colour = controlPoints.Any(c => c is TimingControlPoint) ? colours.YellowDark : colours.Green;\n }, true);\n }\n }\n}","smell_code":" protected override void LoadComplete()\n {\n base.LoadComplete();\n\n controlPoints.BindTo(Group.ControlPoints);\n controlPoints.BindCollectionChanged((_, __) =>\n {\n if (controlPoints.Count == 0)\n {\n Colour = Color4.Transparent;\n return;\n }\n\n Colour = controlPoints.Any(c => c is TimingControlPoint) ? colours.YellowDark : colours.Green;\n }, true);\n }","smell":"long method","id":58} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing OpenRA.Graphics;\nusing OpenRA.Primitives;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t[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.\")]\n\tpublic class SpawnMPUnitsInfo : TraitInfo, Requires, ILobbyOptions\n\t{\n\t\tpublic readonly string StartingUnitsClass = \"none\";\n\n\t\t[Translate]\n\t\t[Desc(\"Descriptive label for the starting units option in the lobby.\")]\n\t\tpublic readonly string DropdownLabel = \"Starting Units\";\n\n\t\t[Translate]\n\t\t[Desc(\"Tooltip description for the starting units option in the lobby.\")]\n\t\tpublic readonly string DropdownDescription = \"Change the units that you start the game with\";\n\n\t\t[Desc(\"Prevent the starting units option from being changed in the lobby.\")]\n\t\tpublic readonly bool DropdownLocked = false;\n\n\t\t[Desc(\"Whether to display the starting units option in the lobby.\")]\n\t\tpublic readonly bool DropdownVisible = true;\n\n\t\t[Desc(\"Display order for the starting units option in the lobby.\")]\n\t\tpublic readonly int DropdownDisplayOrder = 0;\n\n\t\tIEnumerable ILobbyOptions.LobbyOptions(Ruleset rules)\n\t\t{\n\t\t\tvar startingUnits = new Dictionary();\n\n\t\t\t\/\/ Duplicate classes are defined for different race variants\n\t\t\tforeach (var t in rules.Actors[\"world\"].TraitInfos())\n\t\t\t\tstartingUnits[t.Class] = t.ClassName;\n\n\t\t\tif (startingUnits.Any())\n\t\t\t\tyield return new LobbyOption(\"startingunits\", DropdownLabel, DropdownDescription, DropdownVisible, DropdownDisplayOrder,\n\t\t\t\t\tnew ReadOnlyDictionary(startingUnits), StartingUnitsClass, DropdownLocked);\n\t\t}\n\n\t\tpublic override object Create(ActorInitializer init) { return new SpawnMPUnits(this); }\n\t}\n\n\tpublic class SpawnMPUnits : IWorldLoaded\n\t{\n\t\treadonly SpawnMPUnitsInfo info;\n\n\t\tpublic SpawnMPUnits(SpawnMPUnitsInfo info)\n\t\t{\n\t\t\tthis.info = info;\n\t\t}\n\n\t\tpublic void WorldLoaded(World world, WorldRenderer wr)\n\t\t{\n\t\t\tforeach (var p in world.Players)\n\t\t\t\tif (p.Playable)\n\t\t\t\t\tSpawnUnitsForPlayer(world, p);\n\t\t}\n\n\t\tvoid SpawnUnitsForPlayer(World w, Player p)\n\t\t{\n\t\t\tvar spawnClass = p.PlayerReference.StartingUnitsClass ?? w.LobbyInfo.GlobalSettings\n\t\t\t\t.OptionOrDefault(\"startingunits\", info.StartingUnitsClass);\n\n\t\t\tvar unitGroup = w.Map.Rules.Actors[\"world\"].TraitInfos()\n\t\t\t\t.Where(g => g.Class == spawnClass && g.Factions != null && g.Factions.Contains(p.Faction.InternalName))\n\t\t\t\t.RandomOrDefault(w.SharedRandom);\n\n\t\t\tif (unitGroup == null)\n\t\t\t\tthrow new InvalidOperationException(\"No starting units defined for faction {0} with class {1}\".F(p.Faction.InternalName, spawnClass));\n\n\t\t\tif (unitGroup.BaseActor != null)\n\t\t\t{\n\t\t\t\tvar facing = unitGroup.BaseActorFacing.HasValue ? unitGroup.BaseActorFacing.Value : new WAngle(w.SharedRandom.Next(1024));\n\t\t\t\tw.CreateActor(unitGroup.BaseActor.ToLowerInvariant(), new TypeDictionary\n\t\t\t\t{\n\t\t\t\t\tnew LocationInit(p.HomeLocation + unitGroup.BaseActorOffset),\n\t\t\t\t\tnew OwnerInit(p),\n\t\t\t\t\tnew SkipMakeAnimsInit(),\n\t\t\t\t\tnew FacingInit(facing),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!unitGroup.SupportActors.Any())\n\t\t\t\treturn;\n\n\t\t\tvar supportSpawnCells = w.Map.FindTilesInAnnulus(p.HomeLocation, unitGroup.InnerSupportRadius + 1, unitGroup.OuterSupportRadius);\n\n\t\t\tforeach (var s in unitGroup.SupportActors)\n\t\t\t{\n\t\t\t\tvar actorRules = w.Map.Rules.Actors[s.ToLowerInvariant()];\n\t\t\t\tvar ip = actorRules.TraitInfo();\n\t\t\t\tvar validCell = supportSpawnCells.Shuffle(w.SharedRandom).FirstOrDefault(c => ip.CanEnterCell(w, null, c));\n\n\t\t\t\tif (validCell == CPos.Zero)\n\t\t\t\t{\n\t\t\t\t\tLog.Write(\"debug\", \"No cells available to spawn starting unit {0} for player {1}\".F(s, p));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar subCell = ip.SharesCell ? w.ActorMap.FreeSubCell(validCell) : 0;\n\t\t\t\tvar facing = unitGroup.SupportActorsFacing.HasValue ? unitGroup.SupportActorsFacing.Value : new WAngle(w.SharedRandom.Next(1024));\n\n\t\t\t\tw.CreateActor(s.ToLowerInvariant(), new TypeDictionary\n\t\t\t\t{\n\t\t\t\t\tnew OwnerInit(p),\n\t\t\t\t\tnew LocationInit(validCell),\n\t\t\t\t\tnew SubCellInit(subCell),\n\t\t\t\t\tnew FacingInit(facing),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t\tIEnumerable ILobbyOptions.LobbyOptions(Ruleset rules)\n\t\t{\n\t\t\tvar startingUnits = new Dictionary();\n\n\t\t\t\/\/ Duplicate classes are defined for different race variants\n\t\t\tforeach (var t in rules.Actors[\"world\"].TraitInfos())\n\t\t\t\tstartingUnits[t.Class] = t.ClassName;\n\n\t\t\tif (startingUnits.Any())\n\t\t\t\tyield return new LobbyOption(\"startingunits\", DropdownLabel, DropdownDescription, DropdownVisible, DropdownDisplayOrder,\n\t\t\t\t\tnew ReadOnlyDictionary(startingUnits), StartingUnitsClass, DropdownLocked);\n\t\t}","smell":"long method","id":59} {"lang_cluster":"C#","source_code":"using MediaBrowser.Model.Entities;\n\nnamespace Emby.Naming.Video\n{\n \/\/\/ \n \/\/\/ Represents a single video file.\n \/\/\/ <\/summary>\n public class VideoFileInfo\n {\n \/\/\/ \n \/\/\/ Initializes a new instance of the class.\n \/\/\/ <\/summary>\n \/\/\/ Name of file.<\/param>\n \/\/\/ Path to the file.<\/param>\n \/\/\/ Container type.<\/param>\n \/\/\/ Year of release.<\/param>\n \/\/\/ Extra type.<\/param>\n \/\/\/ Extra rule.<\/param>\n \/\/\/ Format 3D.<\/param>\n \/\/\/ Is 3D.<\/param>\n \/\/\/ Is Stub.<\/param>\n \/\/\/ Stub type.<\/param>\n \/\/\/ Is directory.<\/param>\n 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)\n {\n Path = path;\n Container = container;\n Name = name;\n Year = year;\n ExtraType = extraType;\n ExtraRule = extraRule;\n Format3D = format3D;\n Is3D = is3D;\n IsStub = isStub;\n StubType = stubType;\n IsDirectory = isDirectory;\n }\n\n \/\/\/ \n \/\/\/ Gets or sets the path.\n \/\/\/ <\/summary>\n \/\/\/ The path.<\/value>\n public string Path { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the container.\n \/\/\/ <\/summary>\n \/\/\/ The container.<\/value>\n public string? Container { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the name.\n \/\/\/ <\/summary>\n \/\/\/ The name.<\/value>\n public string Name { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the year.\n \/\/\/ <\/summary>\n \/\/\/ The year.<\/value>\n public int? Year { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type of the extra, e.g. trailer, theme song, behind the scenes, etc.\n \/\/\/ <\/summary>\n \/\/\/ The type of the extra.<\/value>\n public ExtraType? ExtraType { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the extra rule.\n \/\/\/ <\/summary>\n \/\/\/ The extra rule.<\/value>\n public ExtraRule? ExtraRule { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the format3 d.\n \/\/\/ <\/summary>\n \/\/\/ The format3 d.<\/value>\n public string? Format3D { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets a value indicating whether [is3 d].\n \/\/\/ <\/summary>\n \/\/\/ true<\/c> if [is3 d]; otherwise, false<\/c>.<\/value>\n public bool Is3D { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets a value indicating whether this instance is stub.\n \/\/\/ <\/summary>\n \/\/\/ true<\/c> if this instance is stub; otherwise, false<\/c>.<\/value>\n public bool IsStub { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets the type of the stub.\n \/\/\/ <\/summary>\n \/\/\/ The type of the stub.<\/value>\n public string? StubType { get; set; }\n\n \/\/\/ \n \/\/\/ Gets or sets a value indicating whether this instance is a directory.\n \/\/\/ <\/summary>\n \/\/\/ The type.<\/value>\n public bool IsDirectory { get; set; }\n\n \/\/\/ \n \/\/\/ Gets the file name without extension.\n \/\/\/ <\/summary>\n \/\/\/ The file name without extension.<\/value>\n public string FileNameWithoutExtension => !IsDirectory\n ? System.IO.Path.GetFileNameWithoutExtension(Path)\n : System.IO.Path.GetFileName(Path);\n\n \/\/\/ \n public override string ToString()\n {\n return \"VideoFileInfo(Name: '\" + Name + \"')\";\n }\n }\n}","smell_code":" 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)\n {\n Path = path;\n Container = container;\n Name = name;\n Year = year;\n ExtraType = extraType;\n ExtraRule = extraRule;\n Format3D = format3D;\n Is3D = is3D;\n IsStub = isStub;\n StubType = stubType;\n IsDirectory = isDirectory;\n }","smell":"long method","id":60} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Beatmaps;\nusing osu.Game.Rulesets.Catch.Judgements;\nusing osu.Game.Rulesets.Catch.Objects.Drawables;\nusing osu.Game.Rulesets.Catch.Replays;\nusing osu.Game.Rulesets.Judgements;\nusing osu.Game.Rulesets.Scoring;\nusing osu.Game.Rulesets.UI;\nusing osuTK;\n\nnamespace osu.Game.Rulesets.Catch.UI\n{\n public class CatcherArea : Container\n {\n public const float CATCHER_SIZE = 106.75f;\n\n public readonly Catcher MovableCatcher;\n private readonly CatchComboDisplay comboDisplay;\n\n public CatcherArea(Container droppedObjectContainer, BeatmapDifficulty difficulty = null)\n {\n Size = new Vector2(CatchPlayfield.WIDTH, CATCHER_SIZE);\n Children = new Drawable[]\n {\n comboDisplay = new CatchComboDisplay\n {\n RelativeSizeAxes = Axes.None,\n AutoSizeAxes = Axes.Both,\n Anchor = Anchor.TopLeft,\n Origin = Anchor.Centre,\n Margin = new MarginPadding { Bottom = 350f },\n X = CatchPlayfield.CENTER_X\n },\n MovableCatcher = new Catcher(this, droppedObjectContainer, difficulty) { X = CatchPlayfield.CENTER_X },\n };\n }\n\n public void OnNewResult(DrawableCatchHitObject hitObject, JudgementResult result)\n {\n MovableCatcher.OnNewResult(hitObject, result);\n\n if (!result.Type.IsScorable())\n return;\n\n if (hitObject.HitObject.LastInCombo)\n {\n if (result.Judgement is CatchJudgement catchJudgement && catchJudgement.ShouldExplodeFor(result))\n MovableCatcher.Explode();\n else\n MovableCatcher.Drop();\n }\n\n comboDisplay.OnNewResult(hitObject, result);\n }\n\n public void OnRevertResult(DrawableCatchHitObject hitObject, JudgementResult result)\n {\n comboDisplay.OnRevertResult(hitObject, result);\n MovableCatcher.OnRevertResult(hitObject, result);\n }\n\n protected override void UpdateAfterChildren()\n {\n base.UpdateAfterChildren();\n\n var state = (GetContainingInputManager().CurrentState as RulesetInputManagerInputState)?.LastReplayState as CatchFramedReplayInputHandler.CatchReplayState;\n\n if (state?.CatcherX != null)\n MovableCatcher.X = state.CatcherX.Value;\n\n comboDisplay.X = MovableCatcher.X;\n }\n }\n}","smell_code":" public void OnNewResult(DrawableCatchHitObject hitObject, JudgementResult result)\n {\n MovableCatcher.OnNewResult(hitObject, result);\n\n if (!result.Type.IsScorable())\n return;\n\n if (hitObject.HitObject.LastInCombo)\n {\n if (result.Judgement is CatchJudgement catchJudgement && catchJudgement.ShouldExplodeFor(result))\n MovableCatcher.Explode();\n else\n MovableCatcher.Drop();\n }\n\n comboDisplay.OnNewResult(hitObject, result);\n }","smell":"long method","id":61} {"lang_cluster":"C#","source_code":"\ufeffusing System;\nusing System.Collections.Generic;\nusing System.Collections.Immutable;\nusing System.Runtime.Serialization;\nusing Core2D.Shapes;\n\nnamespace Core2D.Containers\n{\n public class InvalidateLayerEventArgs : EventArgs { }\n\n public delegate void InvalidateLayerEventHandler(object sender, InvalidateLayerEventArgs e);\n\n [DataContract(IsReference = true)]\n public class LayerContainer : BaseContainer\n {\n public event InvalidateLayerEventHandler InvalidateLayerHandler;\n\n private bool _isVisible = true;\n private ImmutableArray _shapes;\n\n [DataMember(IsRequired = false, EmitDefaultValue = true)]\n public bool IsVisible\n {\n get => _isVisible;\n set\n {\n RaiseAndSetIfChanged(ref _isVisible, value);\n InvalidateLayer();\n }\n }\n\n [DataMember(IsRequired = false, EmitDefaultValue = true)]\n public ImmutableArray Shapes\n {\n get => _shapes;\n set => RaiseAndSetIfChanged(ref _shapes, value);\n }\n\n public void InvalidateLayer() => InvalidateLayerHandler?.Invoke(this, new InvalidateLayerEventArgs());\n\n public override object Copy(IDictionary shared)\n {\n throw new NotImplementedException();\n }\n\n public override bool IsDirty()\n {\n var isDirty = base.IsDirty();\n\n foreach (var shape in Shapes)\n {\n isDirty |= shape.IsDirty();\n }\n\n return isDirty;\n }\n\n public override void Invalidate()\n {\n base.Invalidate();\n\n foreach (var shape in Shapes)\n {\n shape.Invalidate();\n }\n }\n }\n}","smell_code":" public override bool IsDirty()\n {\n var isDirty = base.IsDirty();\n\n foreach (var shape in Shapes)\n {\n isDirty |= shape.IsDirty();\n }\n\n return isDirty;\n }","smell":"long method","id":62} {"lang_cluster":"C#","source_code":"\ufeff\/\/ MonoGame - Copyright (C) The MonoGame Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing System;\nusing Microsoft.Xna.Framework.Content.Pipeline.Processors;\nusing Microsoft.Xna.Framework.Graphics;\n\n\nnamespace Microsoft.Xna.Framework.Content.Pipeline.Graphics\n{\n internal class DefaultTextureProfile : TextureProfile\n {\n public override bool Supports(TargetPlatform platform)\n {\n return platform == TargetPlatform.Android ||\n platform == TargetPlatform.DesktopGL ||\n platform == TargetPlatform.MacOSX ||\n platform == TargetPlatform.NativeClient ||\n platform == TargetPlatform.RaspberryPi ||\n platform == TargetPlatform.Windows ||\n platform == TargetPlatform.WindowsPhone8 ||\n platform == TargetPlatform.WindowsStoreApp ||\n platform == TargetPlatform.iOS ||\n platform == TargetPlatform.Web;\n }\n\n private static bool IsCompressedTextureFormat(TextureProcessorOutputFormat format)\n {\n switch (format)\n {\n case TextureProcessorOutputFormat.AtcCompressed:\n case TextureProcessorOutputFormat.DxtCompressed:\n case TextureProcessorOutputFormat.Etc1Compressed:\n case TextureProcessorOutputFormat.PvrCompressed:\n return true;\n }\n return false;\n }\n\n private static TextureProcessorOutputFormat GetTextureFormatForPlatform(TextureProcessorOutputFormat format, TargetPlatform platform)\n {\n \/\/ Select the default texture compression format for the target platform\n if (format == TextureProcessorOutputFormat.Compressed)\n {\n if (platform == TargetPlatform.iOS)\n format = TextureProcessorOutputFormat.PvrCompressed;\n else if (platform == TargetPlatform.Android)\n format = TextureProcessorOutputFormat.Etc1Compressed;\n else\n format = TextureProcessorOutputFormat.DxtCompressed;\n }\n\n if (IsCompressedTextureFormat(format))\n {\n \/\/ Make sure the target platform supports the selected texture compression format\n if (platform == TargetPlatform.iOS)\n {\n if (format != TextureProcessorOutputFormat.PvrCompressed)\n throw new PlatformNotSupportedException(\"iOS platform only supports PVR texture compression\");\n }\n else if (platform == TargetPlatform.Windows ||\n platform == TargetPlatform.WindowsPhone8 ||\n platform == TargetPlatform.WindowsStoreApp ||\n platform == TargetPlatform.DesktopGL ||\n platform == TargetPlatform.MacOSX ||\n platform == TargetPlatform.NativeClient ||\n platform == TargetPlatform.Web)\n {\n if (format != TextureProcessorOutputFormat.DxtCompressed)\n throw new PlatformNotSupportedException(format + \" platform only supports DXT texture compression\");\n }\n }\n\n return format;\n }\n\n public override void Requirements(ContentProcessorContext context, TextureProcessorOutputFormat format, out bool requiresPowerOfTwo, out bool requiresSquare)\n {\n if (format == TextureProcessorOutputFormat.Compressed)\n format = GetTextureFormatForPlatform(format, context.TargetPlatform);\n\n \/\/ Does it require POT textures?\n switch (format)\n {\n default:\n requiresPowerOfTwo = false;\n break;\n\n case TextureProcessorOutputFormat.DxtCompressed:\n requiresPowerOfTwo = context.TargetProfile == GraphicsProfile.Reach;\n break;\n\n case TextureProcessorOutputFormat.PvrCompressed:\n case TextureProcessorOutputFormat.Etc1Compressed:\n requiresPowerOfTwo = true;\n break;\n }\n\n \/\/ Does it require square textures?\n switch (format)\n {\n default:\n requiresSquare = false;\n break;\n\n case TextureProcessorOutputFormat.PvrCompressed:\n requiresSquare = true;\n break;\n }\n }\n\n protected override void PlatformCompressTexture(ContentProcessorContext context, TextureContent content, TextureProcessorOutputFormat format, bool isSpriteFont)\n {\n format = GetTextureFormatForPlatform(format, context.TargetPlatform);\n\n \/\/ Make sure we're in a floating point format\n content.ConvertBitmapType(typeof(PixelBitmapContent));\n\n switch (format)\n {\n case TextureProcessorOutputFormat.AtcCompressed:\n GraphicsUtil.CompressAti(context, content, isSpriteFont);\n break;\n\n case TextureProcessorOutputFormat.Color16Bit:\n GraphicsUtil.CompressColor16Bit(context, content);\n break;\n\n case TextureProcessorOutputFormat.DxtCompressed:\n GraphicsUtil.CompressDxt(context, content, isSpriteFont);\n break;\n\n case TextureProcessorOutputFormat.Etc1Compressed:\n GraphicsUtil.CompressEtc1(context, content, isSpriteFont);\n break;\n\n case TextureProcessorOutputFormat.PvrCompressed:\n GraphicsUtil.CompressPvrtc(context, content, isSpriteFont);\n break;\n }\n }\n }\n}","smell_code":" public override bool Supports(TargetPlatform platform)\n {\n return platform == TargetPlatform.Android ||\n platform == TargetPlatform.DesktopGL ||\n platform == TargetPlatform.MacOSX ||\n platform == TargetPlatform.NativeClient ||\n platform == TargetPlatform.RaspberryPi ||\n platform == TargetPlatform.Windows ||\n platform == TargetPlatform.WindowsPhone8 ||\n platform == TargetPlatform.WindowsStoreApp ||\n platform == TargetPlatform.iOS ||\n platform == TargetPlatform.Web;\n }","smell":"long method","id":63} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Audio;\nusing osu.Game.Configuration;\nusing osu.Game.Rulesets.Scoring;\nusing osu.Game.Skinning;\n\nnamespace osu.Game.Screens.Play\n{\n public class ComboEffects : CompositeDrawable\n {\n private readonly ScoreProcessor processor;\n\n private SkinnableSound comboBreakSample;\n\n private Bindable alwaysPlayFirst;\n\n private double? firstBreakTime;\n\n public ComboEffects(ScoreProcessor processor)\n {\n this.processor = processor;\n }\n\n [BackgroundDependencyLoader]\n private void load(OsuConfigManager config)\n {\n InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo(\"Gameplay\/combobreak\"));\n alwaysPlayFirst = config.GetBindable(OsuSetting.AlwaysPlayFirstComboBreak);\n }\n\n protected override void LoadComplete()\n {\n base.LoadComplete();\n processor.Combo.BindValueChanged(onComboChange);\n }\n\n [Resolved(canBeNull: true)]\n private ISamplePlaybackDisabler samplePlaybackDisabler { get; set; }\n\n [Resolved]\n private GameplayClock gameplayClock { get; set; }\n\n private void onComboChange(ValueChangedEvent combo)\n {\n \/\/ handle the case of rewinding before the first combo break time.\n if (gameplayClock.CurrentTime < firstBreakTime)\n firstBreakTime = null;\n\n if (gameplayClock.ElapsedFrameTime < 0)\n return;\n\n if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlayFirst.Value && firstBreakTime == null)))\n {\n firstBreakTime = gameplayClock.CurrentTime;\n\n \/\/ combo break isn't a pausable sound itself as we want to let it play out.\n \/\/ we still need to disable during seeks, though.\n if (samplePlaybackDisabler?.SamplePlaybackDisabled.Value == true)\n return;\n\n comboBreakSample?.Play();\n }\n }\n }\n}","smell_code":" private void onComboChange(ValueChangedEvent combo)\n {\n \/\/ handle the case of rewinding before the first combo break time.\n if (gameplayClock.CurrentTime < firstBreakTime)\n firstBreakTime = null;\n\n if (gameplayClock.ElapsedFrameTime < 0)\n return;\n\n if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlayFirst.Value && firstBreakTime == null)))\n {\n firstBreakTime = gameplayClock.CurrentTime;\n\n \/\/ combo break isn't a pausable sound itself as we want to let it play out.\n \/\/ we still need to disable during seeks, though.\n if (samplePlaybackDisabler?.SamplePlaybackDisabled.Value == true)\n return;\n\n comboBreakSample?.Play();\n }\n }","smell":"long method","id":64} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Bindables;\nusing osu.Framework.Configuration;\nusing osu.Framework.Graphics;\nusing osu.Framework.Input;\nusing osu.Game.Configuration;\n\nnamespace osu.Game.Input\n{\n \/\/\/ \n \/\/\/ Connects with .\n \/\/\/ If is true, we should also confine the mouse cursor if it has been\n \/\/\/ requested with .\n \/\/\/ <\/summary>\n public class ConfineMouseTracker : Component\n {\n private Bindable frameworkConfineMode;\n private Bindable frameworkWindowMode;\n\n private Bindable osuConfineMode;\n private IBindable localUserPlaying;\n\n [BackgroundDependencyLoader]\n private void load(OsuGame game, FrameworkConfigManager frameworkConfigManager, OsuConfigManager osuConfigManager)\n {\n frameworkConfineMode = frameworkConfigManager.GetBindable(FrameworkSetting.ConfineMouseMode);\n frameworkWindowMode = frameworkConfigManager.GetBindable(FrameworkSetting.WindowMode);\n frameworkWindowMode.BindValueChanged(_ => updateConfineMode());\n\n osuConfineMode = osuConfigManager.GetBindable(OsuSetting.ConfineMouseMode);\n localUserPlaying = game.LocalUserPlaying.GetBoundCopy();\n\n osuConfineMode.ValueChanged += _ => updateConfineMode();\n localUserPlaying.BindValueChanged(_ => updateConfineMode(), true);\n }\n\n private void updateConfineMode()\n {\n \/\/ confine mode is unavailable on some platforms\n if (frameworkConfineMode.Disabled)\n return;\n\n if (frameworkWindowMode.Value == WindowMode.Fullscreen)\n {\n frameworkConfineMode.Value = ConfineMouseMode.Fullscreen;\n return;\n }\n\n switch (osuConfineMode.Value)\n {\n case OsuConfineMouseMode.Never:\n frameworkConfineMode.Value = ConfineMouseMode.Never;\n break;\n\n case OsuConfineMouseMode.DuringGameplay:\n frameworkConfineMode.Value = localUserPlaying.Value ? ConfineMouseMode.Always : ConfineMouseMode.Never;\n break;\n\n case OsuConfineMouseMode.Always:\n frameworkConfineMode.Value = ConfineMouseMode.Always;\n break;\n }\n }\n }\n}","smell_code":" private void updateConfineMode()\n {\n \/\/ confine mode is unavailable on some platforms\n if (frameworkConfineMode.Disabled)\n return;\n\n if (frameworkWindowMode.Value == WindowMode.Fullscreen)\n {\n frameworkConfineMode.Value = ConfineMouseMode.Fullscreen;\n return;\n }\n\n switch (osuConfineMode.Value)\n {\n case OsuConfineMouseMode.Never:\n frameworkConfineMode.Value = ConfineMouseMode.Never;\n break;\n\n case OsuConfineMouseMode.DuringGameplay:\n frameworkConfineMode.Value = localUserPlaying.Value ? ConfineMouseMode.Always : ConfineMouseMode.Never;\n break;\n\n case OsuConfineMouseMode.Always:\n frameworkConfineMode.Value = ConfineMouseMode.Always;\n break;\n }\n }","smell":"long method","id":65} {"lang_cluster":"C#","source_code":"\ufeff\/\/ MonoGame - Copyright (C) The MonoGame Team\n\/\/ This file is subject to the terms and conditions defined in\n\/\/ file 'LICENSE.txt', which is part of this source code package.\n\nusing System.Runtime.InteropServices;\nusing System;\n\nnamespace MonoGame.Framework.Utilities\n{\n internal enum OS\n {\n Windows,\n Linux,\n MacOSX,\n Unknown\n }\n\n internal static class CurrentPlatform\n {\n private static bool _init = false;\n private static OS _os;\n\n [DllImport(\"libc\")]\n static extern int uname(IntPtr buf);\n\n private static void Init()\n {\n if (_init)\n return;\n\n var pid = Environment.OSVersion.Platform;\n\n switch (pid)\n {\n case PlatformID.Win32NT:\n case PlatformID.Win32S:\n case PlatformID.Win32Windows:\n case PlatformID.WinCE:\n _os = OS.Windows;\n break;\n case PlatformID.MacOSX:\n _os = OS.MacOSX;\n break;\n case PlatformID.Unix:\n _os = OS.MacOSX;\n\n var buf = IntPtr.Zero;\n \n try\n {\n buf = Marshal.AllocHGlobal(8192);\n\n if (uname(buf) == 0 && Marshal.PtrToStringAnsi(buf) == \"Linux\")\n _os = OS.Linux;\n }\n catch\n {\n }\n finally\n {\n if (buf != IntPtr.Zero)\n Marshal.FreeHGlobal(buf);\n }\n\n break;\n default:\n _os = OS.Unknown;\n break;\n }\n\n _init = true;\n }\n\n public static OS OS\n {\n get\n {\n Init();\n return _os;\n }\n }\n\n public static string Rid\n {\n get\n {\n if (CurrentPlatform.OS == OS.Windows && Environment.Is64BitProcess)\n return \"win-x64\";\n else if (CurrentPlatform.OS == OS.Windows && !Environment.Is64BitProcess)\n return \"win-x86\";\n else if (CurrentPlatform.OS == OS.Linux)\n return \"linux-x64\";\n else if (CurrentPlatform.OS == OS.MacOSX)\n return \"osx\";\n else\n return \"unknown\";\n }\n }\n }\n}","smell_code":" private static void Init()\n {\n if (_init)\n return;\n\n var pid = Environment.OSVersion.Platform;\n\n switch (pid)\n {\n case PlatformID.Win32NT:\n case PlatformID.Win32S:\n case PlatformID.Win32Windows:\n case PlatformID.WinCE:\n _os = OS.Windows;\n break;\n case PlatformID.MacOSX:\n _os = OS.MacOSX;\n break;\n case PlatformID.Unix:\n _os = OS.MacOSX;\n\n var buf = IntPtr.Zero;\n \n try\n {\n buf = Marshal.AllocHGlobal(8192);\n\n if (uname(buf) == 0 && Marshal.PtrToStringAnsi(buf) == \"Linux\")\n _os = OS.Linux;\n }\n catch\n {\n }\n finally\n {\n if (buf != IntPtr.Zero)\n Marshal.FreeHGlobal(buf);\n }\n\n break;\n default:\n _os = OS.Unknown;\n break;\n }\n\n _init = true;\n }","smell":"long method","id":66} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.IO;\nusing OpenRA.FileFormats;\nusing OpenRA.Primitives;\n\nnamespace OpenRA.Graphics\n{\n\tpublic sealed class Sheet : IDisposable\n\t{\n\t\tbool dirty;\n\t\tbool releaseBufferOnCommit;\n\t\tITexture texture;\n\t\tbyte[] data;\n\n\t\tpublic readonly Size Size;\n\t\tpublic readonly SheetType Type;\n\n\t\tpublic byte[] GetData()\n\t\t{\n\t\t\tCreateBuffer();\n\t\t\treturn data;\n\t\t}\n\n\t\tpublic bool Buffered { get { return data != null || texture == null; } }\n\n\t\tpublic Sheet(SheetType type, Size size)\n\t\t{\n\t\t\tType = type;\n\t\t\tSize = size;\n\t\t}\n\n\t\tpublic Sheet(SheetType type, ITexture texture)\n\t\t{\n\t\t\tType = type;\n\t\t\tthis.texture = texture;\n\t\t\tSize = texture.Size;\n\t\t}\n\n\t\tpublic Sheet(SheetType type, Stream stream)\n\t\t{\n\t\t\tvar png = new Png(stream);\n\t\t\tSize = new Size(png.Width, png.Height);\n\t\t\tdata = new byte[4 * Size.Width * Size.Height];\n\t\t\tUtil.FastCopyIntoSprite(new Sprite(this, new Rectangle(0, 0, png.Width, png.Height), TextureChannel.Red), png);\n\n\t\t\tType = type;\n\t\t\tReleaseBuffer();\n\t\t}\n\n\t\tpublic ITexture GetTexture()\n\t\t{\n\t\t\tif (texture == null)\n\t\t\t{\n\t\t\t\ttexture = Game.Renderer.Context.CreateTexture();\n\t\t\t\tdirty = true;\n\t\t\t}\n\n\t\t\tif (data != null && dirty)\n\t\t\t{\n\t\t\t\ttexture.SetData(data, Size.Width, Size.Height);\n\t\t\t\tdirty = false;\n\t\t\t\tif (releaseBufferOnCommit)\n\t\t\t\t\tdata = null;\n\t\t\t}\n\n\t\t\treturn texture;\n\t\t}\n\n\t\tpublic Png AsPng()\n\t\t{\n\t\t\tvar data = GetData();\n\n\t\t\t\/\/ Convert BGRA to RGBA\n\t\t\tfor (var i = 0; i < Size.Width * Size.Height; i++)\n\t\t\t{\n\t\t\t\tvar temp = data[i * 4];\n\t\t\t\tdata[i * 4] = data[i * 4 + 2];\n\t\t\t\tdata[i * 4 + 2] = temp;\n\t\t\t}\n\n\t\t\treturn new Png(data, Size.Width, Size.Height);\n\t\t}\n\n\t\tpublic Png AsPng(TextureChannel channel, IPalette pal)\n\t\t{\n\t\t\tvar d = GetData();\n\t\t\tvar plane = new byte[Size.Width * Size.Height];\n\t\t\tvar dataStride = 4 * Size.Width;\n\t\t\tvar channelOffset = (int)channel;\n\n\t\t\tfor (var y = 0; y < Size.Height; y++)\n\t\t\t\tfor (var x = 0; x < Size.Width; x++)\n\t\t\t\t\tplane[y * Size.Width + x] = d[y * dataStride + channelOffset + 4 * x];\n\n\t\t\tvar palColors = new Color[Palette.Size];\n\t\t\tfor (var i = 0; i < Palette.Size; i++)\n\t\t\t\tpalColors[i] = pal.GetColor(i);\n\n\t\t\treturn new Png(plane, Size.Width, Size.Height, palColors);\n\t\t}\n\n\t\tpublic void CreateBuffer()\n\t\t{\n\t\t\tif (data != null)\n\t\t\t\treturn;\n\t\t\tif (texture == null)\n\t\t\t\tdata = new byte[4 * Size.Width * Size.Height];\n\t\t\telse\n\t\t\t\tdata = texture.GetData();\n\t\t\treleaseBufferOnCommit = false;\n\t\t}\n\n\t\tpublic void CommitBufferedData()\n\t\t{\n\t\t\tif (!Buffered)\n\t\t\t\tthrow new InvalidOperationException(\n\t\t\t\t\t\"This sheet is unbuffered. You cannot call CommitBufferedData on an unbuffered sheet. \" +\n\t\t\t\t\t\"If you need to completely replace the texture data you should set data into the texture directly. \" +\n\t\t\t\t\t\"If you need to make only small changes to the texture data consider creating a buffered sheet instead.\");\n\n\t\t\tdirty = true;\n\t\t}\n\n\t\tpublic void ReleaseBuffer()\n\t\t{\n\t\t\tif (!Buffered)\n\t\t\t\treturn;\n\t\t\tdirty = true;\n\t\t\treleaseBufferOnCommit = true;\n\n\t\t\t\/\/ Commit data from the buffer to the texture, allowing the buffer to be released and reclaimed by GC.\n\t\t\tif (Game.Renderer != null)\n\t\t\t\tGetTexture();\n\t\t}\n\n\t\tpublic void Dispose()\n\t\t{\n\t\t\ttexture?.Dispose();\n\t\t}\n\t}\n}","smell_code":"\t\tpublic Sheet(SheetType type, Stream stream)\n\t\t{\n\t\t\tvar png = new Png(stream);\n\t\t\tSize = new Size(png.Width, png.Height);\n\t\t\tdata = new byte[4 * Size.Width * Size.Height];\n\t\t\tUtil.FastCopyIntoSprite(new Sprite(this, new Rectangle(0, 0, png.Width, png.Height), TextureChannel.Red), png);\n\n\t\t\tType = type;\n\t\t\tReleaseBuffer();\n\t\t}","smell":"long method","id":67} {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\nusing BurningKnight.level;\nusing Lens.entity;\nusing Lens.util;\nusing Lens.util.file;\n\nnamespace BurningKnight.save {\n\tpublic class PrefabSaver : LevelSave {\n\t\tpublic List Datas = new List();\n\n\t\tpublic override void Load(Area area, FileReader reader) {\n\t\t\tDatas.Clear();\n\t\t\tbase.Load(area, reader);\n\t\t}\n\n\t\tprotected override void ReadEntity(Area area, FileReader reader, string type, bool post) {\n\t\t\tif (type == \"level.rooms.Room\") {\n\t\t\t\ttype = \"entity.room.Room\";\n\t\t\t} else if (type == \"entity.item.ItemStand\") {\n\t\t\t\ttype = \"entity.item.stand.ItemStand\";\n\t\t\t}\n\t\t\n\t\t\tvar t = Type.GetType($\"BurningKnight.{type}\", true, false);\n\n\t\t\tif (typeof(Level).IsAssignableFrom(t)) {\n\t\t\t\tbase.ReadEntity(area, reader, type, post);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar prefab = new PrefabData();\n\t\t\tprefab.Type = t;\n\n\t\t\tvar size = reader.ReadInt16();\n\t\t\tprefab.Data = new byte[size];\n\t\t\t\n\t\t\tfor (var i = 0; i < size; i++) {\n\t\t\t\tprefab.Data[i] = reader.ReadByte();\n\t\t\t}\n\t\t\t\n\t\t\tDatas.Add(prefab);\n\t\t}\n\t}\n}","smell_code":"\t\tprotected override void ReadEntity(Area area, FileReader reader, string type, bool post) {\n\t\t\tif (type == \"level.rooms.Room\") {\n\t\t\t\ttype = \"entity.room.Room\";\n\t\t\t} else if (type == \"entity.item.ItemStand\") {\n\t\t\t\ttype = \"entity.item.stand.ItemStand\";\n\t\t\t}\n\t\t\n\t\t\tvar t = Type.GetType($\"BurningKnight.{type}\", true, false);\n\n\t\t\tif (typeof(Level).IsAssignableFrom(t)) {\n\t\t\t\tbase.ReadEntity(area, reader, type, post);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tvar prefab = new PrefabData();\n\t\t\tprefab.Type = t;\n\n\t\t\tvar size = reader.ReadInt16();\n\t\t\tprefab.Data = new byte[size];\n\t\t\t\n\t\t\tfor (var i = 0; i < size; i++) {\n\t\t\t\tprefab.Data[i] = reader.ReadByte();\n\t\t\t}\n\t\t\t\n\t\t\tDatas.Add(prefab);\n\t\t}","smell":"long method","id":68} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Linq;\nusing osu.Game.Rulesets.Difficulty.Preprocessing;\nusing osu.Game.Rulesets.Difficulty.Skills;\nusing osu.Game.Rulesets.Difficulty.Utils;\nusing osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;\nusing osu.Game.Rulesets.Taiko.Objects;\n\nnamespace osu.Game.Rulesets.Taiko.Difficulty.Skills\n{\n \/\/\/ \n \/\/\/ Calculates the stamina coefficient of taiko difficulty.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ The reference play style chosen uses two hands, with full alternating (the hand changes after every hit).\n \/\/\/ <\/remarks>\n public class Stamina : Skill\n {\n protected override double SkillMultiplier => 1;\n protected override double StrainDecayBase => 0.4;\n\n \/\/\/ \n \/\/\/ Maximum number of entries to keep in .\n \/\/\/ <\/summary>\n private const int max_history_length = 2;\n\n \/\/\/ \n \/\/\/ The index of the hand this instance is associated with.\n \/\/\/ <\/summary>\n \/\/\/ \n \/\/\/ The value of 0 indicates the left hand (full alternating gameplay starting with left hand is assumed).\n \/\/\/ This naturally translates onto index offsets of the objects in the map.\n \/\/\/ <\/remarks>\n private readonly int hand;\n\n \/\/\/ \n \/\/\/ Stores the last durations between notes hit with the hand indicated by .\n \/\/\/ <\/summary>\n private readonly LimitedCapacityQueue notePairDurationHistory = new LimitedCapacityQueue(max_history_length);\n\n \/\/\/ \n \/\/\/ Stores the of the last object that was hit by the other<\/i> hand.\n \/\/\/ <\/summary>\n private double offhandObjectDuration = double.MaxValue;\n\n \/\/\/ \n \/\/\/ Creates a skill.\n \/\/\/ <\/summary>\n \/\/\/ Whether this instance is performing calculations for the right hand.<\/param>\n public Stamina(bool rightHand)\n {\n hand = rightHand ? 1 : 0;\n }\n\n protected override double StrainValueOf(DifficultyHitObject current)\n {\n if (!(current.BaseObject is Hit))\n {\n return 0.0;\n }\n\n TaikoDifficultyHitObject hitObject = (TaikoDifficultyHitObject)current;\n\n if (hitObject.ObjectIndex % 2 == hand)\n {\n double objectStrain = 1;\n\n if (hitObject.ObjectIndex == 1)\n return 1;\n\n notePairDurationHistory.Enqueue(hitObject.DeltaTime + offhandObjectDuration);\n\n double shortestRecentNote = notePairDurationHistory.Min();\n objectStrain += speedBonus(shortestRecentNote);\n\n if (hitObject.StaminaCheese)\n objectStrain *= cheesePenalty(hitObject.DeltaTime + offhandObjectDuration);\n\n return objectStrain;\n }\n\n offhandObjectDuration = hitObject.DeltaTime;\n return 0;\n }\n\n \/\/\/ \n \/\/\/ Applies a penalty for hit objects marked with .\n \/\/\/ <\/summary>\n \/\/\/ The duration between the current and previous note hit using the hand indicated by .<\/param>\n private double cheesePenalty(double notePairDuration)\n {\n if (notePairDuration > 125) return 1;\n if (notePairDuration < 100) return 0.6;\n\n return 0.6 + (notePairDuration - 100) * 0.016;\n }\n\n \/\/\/ \n \/\/\/ Applies a speed bonus dependent on the time since the last hit performed using this hand.\n \/\/\/ <\/summary>\n \/\/\/ The duration between the current and previous note hit using the hand indicated by .<\/param>\n private double speedBonus(double notePairDuration)\n {\n if (notePairDuration >= 200) return 0;\n\n double bonus = 200 - notePairDuration;\n bonus *= bonus;\n return bonus \/ 100000;\n }\n }\n}","smell_code":" protected override double StrainValueOf(DifficultyHitObject current)\n {\n if (!(current.BaseObject is Hit))\n {\n return 0.0;\n }\n\n TaikoDifficultyHitObject hitObject = (TaikoDifficultyHitObject)current;\n\n if (hitObject.ObjectIndex % 2 == hand)\n {\n double objectStrain = 1;\n\n if (hitObject.ObjectIndex == 1)\n return 1;\n\n notePairDurationHistory.Enqueue(hitObject.DeltaTime + offhandObjectDuration);\n\n double shortestRecentNote = notePairDurationHistory.Min();\n objectStrain += speedBonus(shortestRecentNote);\n\n if (hitObject.StaminaCheese)\n objectStrain *= cheesePenalty(hitObject.DeltaTime + offhandObjectDuration);\n\n return objectStrain;\n }\n\n offhandObjectDuration = hitObject.DeltaTime;\n return 0;\n }","smell":"long method","id":69} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing OpenRA.FileSystem;\nusing OpenRA.Primitives;\nusing FS = OpenRA.FileSystem.FileSystem;\n\nnamespace OpenRA.Mods.Cnc.FileSystem\n{\n\tpublic class BigLoader : IPackageLoader\n\t{\n\t\tsealed class BigFile : IReadOnlyPackage\n\t\t{\n\t\t\tpublic string Name { get; private set; }\n\t\t\tpublic IEnumerable Contents { get { return index.Keys; } }\n\n\t\t\treadonly Dictionary index = new Dictionary();\n\t\t\treadonly Stream s;\n\n\t\t\tpublic BigFile(Stream s, string filename)\n\t\t\t{\n\t\t\t\tName = filename;\n\t\t\t\tthis.s = s;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t\/* var signature = *\/ s.ReadASCII(4);\n\n\t\t\t\t\t\/\/ Total archive size.\n\t\t\t\t\ts.ReadUInt32();\n\n\t\t\t\t\tvar entryCount = s.ReadUInt32();\n\t\t\t\t\tif (BitConverter.IsLittleEndian)\n\t\t\t\t\t\tentryCount = int2.Swap(entryCount);\n\n\t\t\t\t\t\/\/ First entry offset? This is apparently bogus for EA's .big files\n\t\t\t\t\t\/\/ and we don't have to try seeking there since the entries typically start next in EA's .big files.\n\t\t\t\t\ts.ReadUInt32();\n\n\t\t\t\t\tfor (var i = 0; i < entryCount; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar entry = new Entry(s);\n\t\t\t\t\t\tindex.Add(entry.Path, entry);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch\n\t\t\t\t{\n\t\t\t\t\tDispose();\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tclass Entry\n\t\t\t{\n\t\t\t\tpublic readonly uint Offset;\n\t\t\t\tpublic readonly uint Size;\n\t\t\t\tpublic readonly string Path;\n\n\t\t\t\tpublic Entry(Stream s)\n\t\t\t\t{\n\t\t\t\t\tOffset = s.ReadUInt32();\n\t\t\t\t\tSize = s.ReadUInt32();\n\t\t\t\t\tif (BitConverter.IsLittleEndian)\n\t\t\t\t\t{\n\t\t\t\t\t\tOffset = int2.Swap(Offset);\n\t\t\t\t\t\tSize = int2.Swap(Size);\n\t\t\t\t\t}\n\n\t\t\t\t\tPath = s.ReadASCIIZ();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpublic Stream GetStream(string filename)\n\t\t\t{\n\t\t\t\tvar entry = index[filename];\n\t\t\t\treturn SegmentStream.CreateWithoutOwningStream(s, entry.Offset, (int)entry.Size);\n\t\t\t}\n\n\t\t\tpublic bool Contains(string filename)\n\t\t\t{\n\t\t\t\treturn index.ContainsKey(filename);\n\t\t\t}\n\n\t\t\tpublic IReadOnlyPackage OpenPackage(string filename, FS context)\n\t\t\t{\n\t\t\t\t\/\/ Not implemented\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tpublic void Dispose()\n\t\t\t{\n\t\t\t\ts.Dispose();\n\t\t\t}\n\t\t}\n\n\t\tbool IPackageLoader.TryParsePackage(Stream s, string filename, FS context, out IReadOnlyPackage package)\n\t\t{\n\t\t\t\/\/ Take a peek at the file signature\n\t\t\tvar signature = s.ReadASCII(4);\n\t\t\ts.Position -= 4;\n\n\t\t\tif (signature != \"BIGF\")\n\t\t\t{\n\t\t\t\tpackage = null;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpackage = new BigFile(s, filename);\n\t\t\treturn true;\n\t\t}\n\t}\n}","smell_code":"\t\t\t\tpublic Entry(Stream s)\n\t\t\t\t{\n\t\t\t\t\tOffset = s.ReadUInt32();\n\t\t\t\t\tSize = s.ReadUInt32();\n\t\t\t\t\tif (BitConverter.IsLittleEndian)\n\t\t\t\t\t{\n\t\t\t\t\t\tOffset = int2.Swap(Offset);\n\t\t\t\t\t\tSize = int2.Swap(Size);\n\t\t\t\t\t}\n\n\t\t\t\t\tPath = s.ReadASCIIZ();\n\t\t\t\t}","smell":"long method","id":70} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.IO;\nusing OpenRA.Mods.Common.FileFormats;\n\nnamespace OpenRA.Mods.Common.AudioLoaders\n{\n\tpublic class WavLoader : ISoundLoader\n\t{\n\t\tbool IsWave(Stream s)\n\t\t{\n\t\t\tvar start = s.Position;\n\t\t\tvar type = s.ReadASCII(4);\n\t\t\ts.Position += 4;\n\t\t\tvar format = s.ReadASCII(4);\n\t\t\ts.Position = start;\n\n\t\t\treturn type == \"RIFF\" && format == \"WAVE\";\n\t\t}\n\n\t\tbool ISoundLoader.TryParseSound(Stream stream, out ISoundFormat sound)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (IsWave(stream))\n\t\t\t\t{\n\t\t\t\t\tsound = new WavFormat(stream);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\t\/\/ Not a (supported) WAV\n\t\t\t}\n\n\t\t\tsound = null;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic sealed class WavFormat : ISoundFormat\n\t{\n\t\tpublic int Channels { get { return channels; } }\n\t\tpublic int SampleBits { get { return sampleBits; } }\n\t\tpublic int SampleRate { get { return sampleRate; } }\n\t\tpublic float LengthInSeconds { get { return WavReader.WaveLength(sourceStream); } }\n\t\tpublic Stream GetPCMInputStream() { return wavStreamFactory(); }\n\t\tpublic void Dispose() { sourceStream.Dispose(); }\n\n\t\treadonly Stream sourceStream;\n\t\treadonly Func wavStreamFactory;\n\t\treadonly short channels;\n\t\treadonly int sampleBits;\n\t\treadonly int sampleRate;\n\n\t\tpublic WavFormat(Stream stream)\n\t\t{\n\t\t\tsourceStream = stream;\n\n\t\t\tif (!WavReader.LoadSound(stream, out wavStreamFactory, out channels, out sampleBits, out sampleRate))\n\t\t\t\tthrow new InvalidDataException();\n\t\t}\n\t}\n}","smell_code":"\t\tpublic WavFormat(Stream stream)\n\t\t{\n\t\t\tsourceStream = stream;\n\n\t\t\tif (!WavReader.LoadSound(stream, out wavStreamFactory, out channels, out sampleBits, out sampleRate))\n\t\t\t\tthrow new InvalidDataException();\n\t\t}","smell":"long method","id":71} {"lang_cluster":"C#","source_code":"namespace BurningKnight.debug {\n\tpublic class TileCommand : ConsoleCommand {\n\t\tpublic TileCommand() {\n\t\t\tName = \"tile\";\n\t\t\tShortName = \"t\";\n\t\t}\n\t\t\n\t\tpublic override void Run(Console Console, string[] Args) {\n\t\t\tvar level = state.Run.Level;\n\n\t\t\tif (level != null) {\n\t\t\t\t\/\/ level.Resize(level.Width, level.Height);\n\t\t\t\tlevel.RefreshSurfaces();\n\t\t\t\tlevel.TileUp(true);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t\tpublic override void Run(Console Console, string[] Args) {\n\t\t\tvar level = state.Run.Level;\n\n\t\t\tif (level != null) {\n\t\t\t\t\/\/ level.Resize(level.Width, level.Height);\n\t\t\t\tlevel.RefreshSurfaces();\n\t\t\t\tlevel.TileUp(true);\n\t\t\t}\n\t\t}","smell":"long method","id":72} {"lang_cluster":"C#","source_code":"using BurningKnight.entity.component;\nusing Lens.util.timer;\n\nnamespace BurningKnight.entity.projectile.controller {\n\tpublic static class SlowdownProjectileController {\n\t\tpublic static ProjectileUpdateCallback Make(float speed = 1, float time = 1f, float vmin = 0.1f) {\n\t\t\tvar stopped = false;\n\t\t\t\n\t\t\treturn (p, dt) => {\n\t\t\t\tif (stopped) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar b = p.GetAnyComponent();\n\t\t\t\tvar v = b.Velocity;\n\n\t\t\t\tb.Velocity -= v * (speed * dt * 2);\n\n\t\t\t\tif (b.Velocity.Length() < vmin) {\n\t\t\t\t\tstopped = true;\n\t\t\t\t\tTimer.Add(() => { p.Break(); }, time);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}\n}","smell_code":"\t\tpublic static ProjectileUpdateCallback Make(float speed = 1, float time = 1f, float vmin = 0.1f) {\n\t\t\tvar stopped = false;\n\t\t\t\n\t\t\treturn (p, dt) => {\n\t\t\t\tif (stopped) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvar b = p.GetAnyComponent();\n\t\t\t\tvar v = b.Velocity;\n\n\t\t\t\tb.Velocity -= v * (speed * dt * 2);\n\n\t\t\t\tif (b.Velocity.Length() < vmin) {\n\t\t\t\t\tstopped = true;\n\t\t\t\t\tTimer.Add(() => { p.Break(); }, time);\n\t\t\t\t}\n\t\t\t};\n\t\t}","smell":"long method","id":73} {"lang_cluster":"C#","source_code":"using BurningKnight.entity.component;\nusing BurningKnight.entity.events;\nusing BurningKnight.level;\nusing BurningKnight.level.entities;\nusing BurningKnight.physics;\nusing BurningKnight.util;\nusing Lens.entity;\nusing Lens.graphics;\nusing Lens.util.camera;\nusing Lens.util.tween;\nusing Microsoft.Xna.Framework;\nusing MonoGame.Extended;\nusing MonoGame.Extended.Sprites;\n\nnamespace BurningKnight.entity.projectile {\n\tpublic class Missile : Projectile {\n\t\tprivate const float MinUpTime = 2f;\n\t\t\n\t\tprivate Entity target;\n\t\tprivate bool goingDown;\n\t\tprivate float toY;\n\t\tprivate float shadowSize;\n\t\tprivate bool exploded;\n\t\tpublic bool HurtOwner = true;\n\t\t\n\t\tpublic Missile(Entity owner, Entity tar) {\n\t\t\ttarget = tar;\n\t\t\tOwner = owner;\n\t\t}\n\n\t\tpublic override void AddComponents() {\n\t\t\tSlice = \"missile\";\n\t\t\tbase.AddComponents();\n\n\t\t\tAlwaysVisible = true;\n\t\t\tAlwaysActive = true;\n\t\t\t\n\t\t\tvar graphics = new ProjectileGraphicsComponent(\"projectiles\", Slice);\n\t\t\tAddComponent(graphics);\n\n\t\t\tvar w = graphics.Sprite.Source.Width;\n\t\t\tvar h = graphics.Sprite.Source.Height;\n\n\t\t\tWidth = w;\n\t\t\tHeight = h;\n\t\t\tCenter = Owner.Center;\n\t\t\t\n\t\t\tAddComponent(BodyComponent = new RectBodyComponent(0, 0, w, h));\n\t\t\t\n\t\t\tBodyComponent.Body.IsBullet = true;\n\t\t\tBodyComponent.Body.LinearVelocity = new Vector2(0, -100f);\n\n\t\t\tOwner.HandleEvent(new ProjectileCreatedEvent {\n\t\t\t\tOwner = Owner,\n\t\t\t\tProjectile = this\n\t\t\t});\n\n\t\t\tDepth = Layers.TileLights;\n\t\t\t\n\t\t\tCollisionFilterComponent.Add(this, (p, e) => {\n\t\t\t\tif (e is Level || e is Prop) {\n\t\t\t\t\treturn CollisionResult.Disable;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn CollisionResult.Default;\n\t\t\t});\n\t\t}\n\n\t\tpublic override bool HandleEvent(Event e) {\n\t\t\tif (e is CollisionStartedEvent) {\n\t\t\t\treturn false; \/\/ Ignore all collision\n\t\t\t}\n\t\t\t\n\t\t\treturn base.HandleEvent(e);\n\t\t}\n\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\t\t\tPosition += BodyComponent.Velocity * dt;\n\n\t\t\tif (goingDown) {\n\t\t\t\tif (Bottom >= toY && !exploded) {\n\t\t\t\t\tAnimateDeath(null);\n\t\t\t\t}\n\t\t\t} else if (T >= MinUpTime && Bottom < Camera.Instance.Y) {\n\t\t\t\tgoingDown = true;\n\t\t\t\tCenterX = target.CenterX;\n\t\t\t\ttoY = target.Bottom;\n\t\t\t\tGraphicsComponent.FlippedVerticaly = true;\n\t\t\t\tBodyComponent.Body.LinearVelocity = new Vector2(0, 100f);\n\n\t\t\t\tTween.To(16, 0, x => shadowSize = x, 1f);\n\t\t\t}\n\t\t}\n\n\t\tprotected override void AnimateDeath(Entity e, bool timeout = false) {\n\t\t\tbase.AnimateDeath(e, timeout);\n\t\t\t\n\t\t\tExplosionMaker.Make(this, damageOwner: HurtOwner);\n\t\t\texploded = true;\n\t\t}\n\n\t\tprotected override void RenderShadow() {\n\t\t\tif (goingDown) {\n\t\t\t\tGraphics.Batch.DrawCircle(CenterX, toY, shadowSize, 16, ColorUtils.WhiteColor, 2f);\n\t\t\t\tGraphics.Batch.DrawCircle(CenterX, toY, shadowSize * 0.5f, 16, ColorUtils.WhiteColor, 2f);\n\t\t\t}\n\t\t}\n\n\t\tpublic override bool BreaksFrom(Entity entity, BodyComponent body) {\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic override bool ShouldCollide(Entity entity) {\n\t\t\treturn false;\n\t\t}\n\t}\n}","smell_code":"\t\tpublic override bool HandleEvent(Event e) {\n\t\t\tif (e is CollisionStartedEvent) {\n\t\t\t\treturn false; \/\/ Ignore all collision\n\t\t\t}\n\t\t\t\n\t\t\treturn base.HandleEvent(e);\n\t\t}","smell":"long method","id":74} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Collections.Specialized;\nusing System.Linq;\nusing osu.Framework.Allocation;\nusing osu.Framework.Caching;\nusing osu.Framework.Extensions.Color4Extensions;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Lines;\nusing osu.Framework.Platform;\nusing osu.Game.Graphics;\nusing osu.Game.Tournament.Components;\nusing osu.Game.Tournament.Models;\nusing osu.Game.Tournament.Screens.Editors;\nusing osu.Game.Tournament.Screens.Ladder.Components;\nusing osuTK.Graphics;\n\nnamespace osu.Game.Tournament.Screens.Ladder\n{\n public class LadderScreen : TournamentScreen, IProvideVideo\n {\n protected Container MatchesContainer;\n private Container paths;\n private Container headings;\n\n protected LadderDragContainer ScrollContent;\n\n protected Container Content;\n\n [BackgroundDependencyLoader]\n private void load(OsuColour colours, Storage storage)\n {\n normalPathColour = Color4Extensions.FromHex(\"#66D1FF\");\n losersPathColour = Color4Extensions.FromHex(\"#FFC700\");\n\n RelativeSizeAxes = Axes.Both;\n\n InternalChild = Content = new Container\n {\n RelativeSizeAxes = Axes.Both,\n Children = new Drawable[]\n {\n new TourneyVideo(\"ladder\")\n {\n RelativeSizeAxes = Axes.Both,\n Loop = true,\n },\n new DrawableTournamentHeaderText\n {\n Y = 100,\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n },\n ScrollContent = new LadderDragContainer\n {\n RelativeSizeAxes = Axes.Both,\n Children = new Drawable[]\n {\n paths = new Container { RelativeSizeAxes = Axes.Both },\n headings = new Container { RelativeSizeAxes = Axes.Both },\n MatchesContainer = new Container { RelativeSizeAxes = Axes.Both },\n }\n },\n }\n };\n\n void addMatch(TournamentMatch match) =>\n MatchesContainer.Add(new DrawableTournamentMatch(match, this is LadderEditorScreen)\n {\n Changed = () => layout.Invalidate()\n });\n\n foreach (var match in LadderInfo.Matches)\n addMatch(match);\n\n LadderInfo.Rounds.CollectionChanged += (_, __) => layout.Invalidate();\n LadderInfo.Matches.CollectionChanged += (_, args) =>\n {\n switch (args.Action)\n {\n case NotifyCollectionChangedAction.Add:\n foreach (var p in args.NewItems.Cast())\n addMatch(p);\n break;\n\n case NotifyCollectionChangedAction.Remove:\n foreach (var p in args.OldItems.Cast())\n {\n foreach (var d in MatchesContainer.Where(d => d.Match == p))\n d.Expire();\n }\n\n break;\n }\n\n layout.Invalidate();\n };\n }\n\n private readonly Cached layout = new Cached();\n\n protected override void Update()\n {\n base.Update();\n\n if (!layout.IsValid)\n UpdateLayout();\n }\n\n private Color4 normalPathColour;\n private Color4 losersPathColour;\n\n protected virtual bool DrawLoserPaths => false;\n\n protected virtual void UpdateLayout()\n {\n paths.Clear();\n headings.Clear();\n\n int id = 1;\n\n foreach (var match in MatchesContainer.OrderBy(d => d.Y).ThenBy(d => d.X))\n {\n match.Match.ID = id++;\n\n if (match.Match.Progression.Value != null)\n {\n var dest = MatchesContainer.FirstOrDefault(p => p.Match == match.Match.Progression.Value);\n\n if (dest == null)\n \/\/ clean up outdated progressions.\n match.Match.Progression.Value = null;\n else\n paths.Add(new ProgressionPath(match, dest) { Colour = match.Match.Losers.Value ? losersPathColour : normalPathColour });\n }\n\n if (DrawLoserPaths)\n {\n if (match.Match.LosersProgression.Value != null)\n {\n var dest = MatchesContainer.FirstOrDefault(p => p.Match == match.Match.LosersProgression.Value);\n\n if (dest == null)\n \/\/ clean up outdated progressions.\n match.Match.LosersProgression.Value = null;\n else\n paths.Add(new ProgressionPath(match, dest) { Colour = losersPathColour.Opacity(0.1f) });\n }\n }\n }\n\n foreach (var round in LadderInfo.Rounds)\n {\n var topMatch = MatchesContainer.Where(p => !p.Match.Losers.Value && p.Match.Round.Value == round).OrderBy(p => p.Y).FirstOrDefault();\n\n if (topMatch == null) continue;\n\n headings.Add(new DrawableTournamentRound(round)\n {\n Position = headings.ToLocalSpace((topMatch.ScreenSpaceDrawQuad.TopLeft + topMatch.ScreenSpaceDrawQuad.TopRight) \/ 2),\n Margin = new MarginPadding { Bottom = 10 },\n Origin = Anchor.BottomCentre,\n });\n }\n\n foreach (var round in LadderInfo.Rounds)\n {\n var topMatch = MatchesContainer.Where(p => p.Match.Losers.Value && p.Match.Round.Value == round).OrderBy(p => p.Y).FirstOrDefault();\n\n if (topMatch == null) continue;\n\n headings.Add(new DrawableTournamentRound(round, true)\n {\n Position = headings.ToLocalSpace((topMatch.ScreenSpaceDrawQuad.TopLeft + topMatch.ScreenSpaceDrawQuad.TopRight) \/ 2),\n Margin = new MarginPadding { Bottom = 10 },\n Origin = Anchor.BottomCentre,\n });\n }\n\n layout.Validate();\n }\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load(OsuColour colours, Storage storage)\n {\n normalPathColour = Color4Extensions.FromHex(\"#66D1FF\");\n losersPathColour = Color4Extensions.FromHex(\"#FFC700\");\n\n RelativeSizeAxes = Axes.Both;\n\n InternalChild = Content = new Container\n {\n RelativeSizeAxes = Axes.Both,\n Children = new Drawable[]\n {\n new TourneyVideo(\"ladder\")\n {\n RelativeSizeAxes = Axes.Both,\n Loop = true,\n },\n new DrawableTournamentHeaderText\n {\n Y = 100,\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n },\n ScrollContent = new LadderDragContainer\n {\n RelativeSizeAxes = Axes.Both,\n Children = new Drawable[]\n {\n paths = new Container { RelativeSizeAxes = Axes.Both },\n headings = new Container { RelativeSizeAxes = Axes.Both },\n MatchesContainer = new Container { RelativeSizeAxes = Axes.Both },\n }\n },\n }\n };\n\n void addMatch(TournamentMatch match) =>\n MatchesContainer.Add(new DrawableTournamentMatch(match, this is LadderEditorScreen)\n {\n Changed = () => layout.Invalidate()\n });\n\n foreach (var match in LadderInfo.Matches)\n addMatch(match);\n\n LadderInfo.Rounds.CollectionChanged += (_, __) => layout.Invalidate();\n LadderInfo.Matches.CollectionChanged += (_, args) =>\n {\n switch (args.Action)\n {\n case NotifyCollectionChangedAction.Add:\n foreach (var p in args.NewItems.Cast())\n addMatch(p);\n break;\n\n case NotifyCollectionChangedAction.Remove:\n foreach (var p in args.OldItems.Cast())\n {\n foreach (var d in MatchesContainer.Where(d => d.Match == p))\n d.Expire();\n }\n\n break;\n }\n\n layout.Invalidate();\n };\n }","smell":"long method","id":75} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing OpenRA.Primitives;\n\nnamespace OpenRA.Platforms.Default\n{\n\tstatic class MultiTapDetection\n\t{\n\t\tstatic Cache<(Keycode Key, Modifiers Mods), TapHistory> keyHistoryCache =\n\t\t\tnew Cache<(Keycode, Modifiers), TapHistory>(_ => new TapHistory(DateTime.Now - TimeSpan.FromSeconds(1)));\n\t\tstatic Cache clickHistoryCache =\n\t\t\tnew Cache(_ => new TapHistory(DateTime.Now - TimeSpan.FromSeconds(1)));\n\n\t\tpublic static int DetectFromMouse(byte button, int2 xy)\n\t\t{\n\t\t\treturn clickHistoryCache[button].GetTapCount(xy);\n\t\t}\n\n\t\tpublic static int InfoFromMouse(byte button)\n\t\t{\n\t\t\treturn clickHistoryCache[button].LastTapCount();\n\t\t}\n\n\t\tpublic static int DetectFromKeyboard(Keycode key, Modifiers mods)\n\t\t{\n\t\t\treturn keyHistoryCache[(key, mods)].GetTapCount(int2.Zero);\n\t\t}\n\n\t\tpublic static int InfoFromKeyboard(Keycode key, Modifiers mods)\n\t\t{\n\t\t\treturn keyHistoryCache[(key, mods)].LastTapCount();\n\t\t}\n\t}\n\n\tclass TapHistory\n\t{\n\t\tpublic (DateTime Time, int2 Location) FirstRelease, SecondRelease, ThirdRelease;\n\n\t\tpublic TapHistory(DateTime now)\n\t\t{\n\t\t\tFirstRelease = SecondRelease = ThirdRelease = (now, int2.Zero);\n\t\t}\n\n\t\tstatic bool CloseEnough((DateTime Time, int2 Location) a, (DateTime Time, int2 Location) b)\n\t\t{\n\t\t\treturn a.Time - b.Time < TimeSpan.FromMilliseconds(250)\n\t\t\t\t&& (a.Location - b.Location).Length < 4;\n\t\t}\n\n\t\tpublic int GetTapCount(int2 xy)\n\t\t{\n\t\t\tFirstRelease = SecondRelease;\n\t\t\tSecondRelease = ThirdRelease;\n\t\t\tThirdRelease = (DateTime.Now, xy);\n\n\t\t\tif (!CloseEnough(ThirdRelease, SecondRelease))\n\t\t\t\treturn 1;\n\t\t\tif (!CloseEnough(SecondRelease, FirstRelease))\n\t\t\t\treturn 2;\n\n\t\t\treturn 3;\n\t\t}\n\n\t\tpublic int LastTapCount()\n\t\t{\n\t\t\tif (!CloseEnough(ThirdRelease, SecondRelease))\n\t\t\t\treturn 1;\n\t\t\tif (!CloseEnough(SecondRelease, FirstRelease))\n\t\t\t\treturn 2;\n\n\t\t\treturn 3;\n\t\t}\n\t}\n}","smell_code":"\t\tpublic int LastTapCount()\n\t\t{\n\t\t\tif (!CloseEnough(ThirdRelease, SecondRelease))\n\t\t\t\treturn 1;\n\t\t\tif (!CloseEnough(SecondRelease, FirstRelease))\n\t\t\t\treturn 2;\n\n\t\t\treturn 3;\n\t\t}","smell":"long method","id":76} {"lang_cluster":"C#","source_code":"using System;\nusing Microsoft.Xna.Framework.Content.Pipeline;\nusing Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;\n\nnamespace Aseprite {\n\t[ContentTypeWriter]\n\tpublic class AudioWriter : ContentTypeWriter {\n\t\tpublic override string GetRuntimeType(TargetPlatform targetPlatform) {\n\t\t\tType type = typeof(AsepriteReader);\n\t\t\treturn type.Namespace + \".AudioReader, \" + type.AssemblyQualifiedName;\n\t\t}\n\n\t\tpublic override string GetRuntimeReader(TargetPlatform targetPlatform) {\n\t\t\tType type = typeof(AsepriteReader);\n\t\t\treturn type.Namespace + \".AudioReader, \" + type.Assembly.FullName;\n\t\t}\n\n\t\tprotected override void Write(ContentWriter output, AudioFile value) {\n\t\t\toutput.Write(value.Stereo);\n\t\t\toutput.Write(value.SampleRate);\n\t\t\toutput.Write(value.Buffer.Length);\n\n\t\t\tfor (var i = 0; i < value.Buffer.Length; i++) {\n\t\t\t\toutput.Write(value.Buffer[i]);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t\tpublic override string GetRuntimeReader(TargetPlatform targetPlatform) {\n\t\t\tType type = typeof(AsepriteReader);\n\t\t\treturn type.Namespace + \".AudioReader, \" + type.Assembly.FullName;\n\t\t}","smell":"long method","id":77} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing OpenRA.Primitives;\nusing OpenRA.Widgets;\n\nnamespace OpenRA.Mods.Common.Lint\n{\n\t[AttributeUsage(AttributeTargets.Class)]\n\tpublic sealed class ChromeLogicArgsHotkeys : Attribute\n\t{\n\t\tpublic string[] LogicArgKeys;\n\t\tpublic ChromeLogicArgsHotkeys(params string[] logicArgKeys)\n\t\t{\n\t\t\tLogicArgKeys = logicArgKeys;\n\t\t}\n\t}\n\n\t[AttributeUsage(AttributeTargets.Method)]\n\tpublic sealed class CustomLintableHotkeyNames : Attribute { }\n\n\tclass CheckChromeHotkeys : ILintPass\n\t{\n\t\tpublic void Run(Action emitError, Action emitWarning, ModData modData)\n\t\t{\n\t\t\t\/\/ Build the list of valid hotkey names\n\t\t\tvar namedKeys = modData.Hotkeys.Definitions.Select(d => d.Name).ToArray();\n\n\t\t\t\/\/ Build the list of widget keys to validate\n\t\t\tvar checkWidgetFields = modData.ObjectCreator.GetTypesImplementing()\n\t\t\t\t.SelectMany(w => w.GetFields()\n\t\t\t\t\t.Where(f => f.FieldType == typeof(HotkeyReference))\n\t\t\t\t\t.Select(f => (w.Name.Substring(0, w.Name.Length - 6), f.Name)))\n\t\t\t\t.ToArray();\n\n\t\t\tvar customLintMethods = new Dictionary>();\n\n\t\t\tforeach (var w in modData.ObjectCreator.GetTypesImplementing())\n\t\t\t{\n\t\t\t\tforeach (var m in w.GetMethods().Where(m => m.HasAttribute()))\n\t\t\t\t{\n\t\t\t\t\tvar p = m.GetParameters();\n\t\t\t\t\tif (p.Length == 3 && p[0].ParameterType == typeof(MiniYamlNode) && p[1].ParameterType == typeof(Action)\n\t\t\t\t\t\t\t&& p[2].ParameterType == typeof(Action))\n\t\t\t\t\t\tcustomLintMethods.GetOrAdd(w.Name.Substring(0, w.Name.Length - 6)).Add(m.Name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach (var filename in modData.Manifest.ChromeLayout)\n\t\t\t{\n\t\t\t\tvar yaml = MiniYaml.FromStream(modData.DefaultFileSystem.Open(filename), filename);\n\t\t\t\tCheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, yaml, filename, null, emitError, emitWarning);\n\t\t\t}\n\t\t}\n\n\t\tvoid CheckInner(ModData modData, string[] namedKeys, (string Widget, string Field)[] checkWidgetFields, Dictionary> customLintMethods,\n\t\t\tList nodes, string filename, MiniYamlNode parent, Action emitError, Action emitWarning)\n\t\t{\n\t\t\tforeach (var node in nodes)\n\t\t\t{\n\t\t\t\tif (node.Value == null)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tforeach (var x in checkWidgetFields)\n\t\t\t\t{\n\t\t\t\t\tif (node.Key == x.Field && parent != null && parent.Key.StartsWith(x.Widget, StringComparison.Ordinal))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Keys are valid if they refer to a named key or can be parsed as a regular Hotkey.\n\t\t\t\t\t\tif (!namedKeys.Contains(node.Value.Value) && !Hotkey.TryParse(node.Value.Value, out var unused))\n\t\t\t\t\t\t\temitError(\"{0} refers to a Key named `{1}` that does not exist\".F(node.Location, node.Value.Value));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Check runtime-defined hotkey names\n\t\t\t\tvar widgetType = node.Key.Split('@')[0];\n\t\t\t\tif (customLintMethods.TryGetValue(widgetType, out var checkMethods))\n\t\t\t\t{\n\t\t\t\t\tvar type = modData.ObjectCreator.FindType(widgetType + \"Widget\");\n\t\t\t\t\tvar keyNames = checkMethods.SelectMany(m => (IEnumerable)type.GetMethod(m).Invoke(null, new object[] { node, emitError, emitWarning }));\n\n\t\t\t\t\tforeach (var name in keyNames)\n\t\t\t\t\t\tif (!namedKeys.Contains(name) && !Hotkey.TryParse(name, out var unused))\n\t\t\t\t\t\t\temitError(\"{0} refers to a Key named `{1}` that does not exist\".F(node.Location, name));\n\t\t\t\t}\n\n\t\t\t\t\/\/ Logic classes can declare the data key names that specify hotkeys\n\t\t\t\tif (node.Key == \"Logic\" && node.Value.Nodes.Any())\n\t\t\t\t{\n\t\t\t\t\tvar typeNames = FieldLoader.GetValue(node.Key, node.Value.Value);\n\t\t\t\t\tvar checkArgKeys = new List();\n\t\t\t\t\tforeach (var typeName in typeNames)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar type = Game.ModData.ObjectCreator.FindType(typeName);\n\t\t\t\t\t\tif (type == null)\n\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\tcheckArgKeys.AddRange(type.GetCustomAttributes(true).SelectMany(x => x.LogicArgKeys));\n\t\t\t\t\t}\n\n\t\t\t\t\tforeach (var n in node.Value.Nodes)\n\t\t\t\t\t\tif (checkArgKeys.Contains(n.Key))\n\t\t\t\t\t\t\tif (!namedKeys.Contains(n.Value.Value) && !Hotkey.TryParse(n.Value.Value, out var unused))\n\t\t\t\t\t\t\t\temitError(\"{0} {1}:{2} refers to a Key named `{3}` that does not exist\".F(filename, node.Value.Value, n.Key, n.Value.Value));\n\t\t\t\t}\n\n\t\t\t\tif (node.Value.Nodes != null)\n\t\t\t\t\tCheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, node.Value.Nodes, filename, node, emitError, emitWarning);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t\tpublic void Run(Action emitError, Action emitWarning, ModData modData)\n\t\t{\n\t\t\t\/\/ Build the list of valid hotkey names\n\t\t\tvar namedKeys = modData.Hotkeys.Definitions.Select(d => d.Name).ToArray();\n\n\t\t\t\/\/ Build the list of widget keys to validate\n\t\t\tvar checkWidgetFields = modData.ObjectCreator.GetTypesImplementing()\n\t\t\t\t.SelectMany(w => w.GetFields()\n\t\t\t\t\t.Where(f => f.FieldType == typeof(HotkeyReference))\n\t\t\t\t\t.Select(f => (w.Name.Substring(0, w.Name.Length - 6), f.Name)))\n\t\t\t\t.ToArray();\n\n\t\t\tvar customLintMethods = new Dictionary>();\n\n\t\t\tforeach (var w in modData.ObjectCreator.GetTypesImplementing())\n\t\t\t{\n\t\t\t\tforeach (var m in w.GetMethods().Where(m => m.HasAttribute()))\n\t\t\t\t{\n\t\t\t\t\tvar p = m.GetParameters();\n\t\t\t\t\tif (p.Length == 3 && p[0].ParameterType == typeof(MiniYamlNode) && p[1].ParameterType == typeof(Action)\n\t\t\t\t\t\t\t&& p[2].ParameterType == typeof(Action))\n\t\t\t\t\t\tcustomLintMethods.GetOrAdd(w.Name.Substring(0, w.Name.Length - 6)).Add(m.Name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach (var filename in modData.Manifest.ChromeLayout)\n\t\t\t{\n\t\t\t\tvar yaml = MiniYaml.FromStream(modData.DefaultFileSystem.Open(filename), filename);\n\t\t\t\tCheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, yaml, filename, null, emitError, emitWarning);\n\t\t\t}\n\t\t}","smell":"long method","id":78} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Eluant;\nusing OpenRA.Mods.Common.Traits;\nusing OpenRA.Primitives;\nusing OpenRA.Scripting;\n\nnamespace OpenRA.Mods.Common.Scripting\n{\n\t[ScriptPropertyGroup(\"Player\")]\n\tpublic class PlayerProperties : ScriptPlayerProperties\n\t{\n\t\tpublic PlayerProperties(ScriptContext context, Player player)\n\t\t\t: base(context, player) { }\n\n\t\t[Desc(\"The player's internal name.\")]\n\t\tpublic string InternalName { get { return Player.InternalName; } }\n\n\t\t[Desc(\"The player's name.\")]\n\t\tpublic string Name { get { return Player.PlayerName; } }\n\n\t\t[Desc(\"The player's color.\")]\n\t\tpublic Color Color { get { return Player.Color; } }\n\n\t\t[Desc(\"The player's faction.\")]\n\t\tpublic string Faction { get { return Player.Faction.InternalName; } }\n\n\t\t[Desc(\"The player's spawnpoint ID.\")]\n\t\tpublic int Spawn { get { return Player.SpawnPoint; } }\n\n\t\t[Desc(\"The player's home\/starting location.\")]\n\t\tpublic CPos HomeLocation { get { return Player.HomeLocation; } }\n\n\t\t[Desc(\"The player's team ID.\")]\n\t\tpublic int Team\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tvar c = Player.World.LobbyInfo.Clients.FirstOrDefault(i => i.Index == Player.ClientIndex);\n\t\t\t\treturn c?.Team ?? 0;\n\t\t\t}\n\t\t}\n\n\t\t[Desc(\"Returns true if the player is a bot.\")]\n\t\tpublic bool IsBot { get { return Player.IsBot; } }\n\n\t\t[Desc(\"Returns true if the player is non combatant.\")]\n\t\tpublic bool IsNonCombatant { get { return Player.NonCombatant; } }\n\n\t\t[Desc(\"Returns true if the player is the local player.\")]\n\t\tpublic bool IsLocalPlayer { get { return Player == (Player.World.RenderPlayer ?? Player.World.LocalPlayer); } }\n\n\t\t[Desc(\"Returns all living actors staying inside the world for this player.\")]\n\t\tpublic Actor[] GetActors()\n\t\t{\n\t\t\treturn Player.World.Actors.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld).ToArray();\n\t\t}\n\n\t\t[Desc(\"Returns an array of actors representing all ground attack units of this player.\")]\n\t\tpublic Actor[] GetGroundAttackers()\n\t\t{\n\t\t\treturn Player.World.ActorsHavingTrait()\n\t\t\t\t.Where(a => a.Owner == Player && !a.IsDead && a.IsInWorld && a.Info.HasTraitInfo())\n\t\t\t\t.ToArray();\n\t\t}\n\n\t\t[Desc(\"Returns all living actors of the specified type of this player.\")]\n\t\tpublic Actor[] GetActorsByType(string type)\n\t\t{\n\t\t\tvar result = new List();\n\n\t\t\tif (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai))\n\t\t\t\tthrow new LuaException(\"Unknown actor type '{0}'\".F(type));\n\n\t\t\tresult.AddRange(Player.World.Actors\n\t\t\t\t.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && actor.Info.Name == ai.Name));\n\n\t\t\treturn result.ToArray();\n\t\t}\n\n\t\t[Desc(\"Returns all living actors of the specified types of this player.\")]\n\t\tpublic Actor[] GetActorsByTypes(string[] types)\n\t\t{\n\t\t\tvar result = new List();\n\n\t\t\tforeach (var type in types)\n\t\t\t\tif (!Context.World.Map.Rules.Actors.ContainsKey(type))\n\t\t\t\t\tthrow new LuaException(\"Unknown actor type '{0}'\".F(type));\n\n\t\t\tresult.AddRange(Player.World.Actors\n\t\t\t\t.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && types.Contains(actor.Info.Name)));\n\n\t\t\treturn result.ToArray();\n\t\t}\n\n\t\t[Desc(\"Check if the player has these prerequisites available.\")]\n\t\tpublic bool HasPrerequisites(string[] type)\n\t\t{\n\t\t\tvar tt = Player.PlayerActor.TraitOrDefault();\n\t\t\tif (tt == null)\n\t\t\t\tthrow new LuaException(\"Missing TechTree trait on player {0}!\".F(Player));\n\n\t\t\treturn tt.HasPrerequisites(type);\n\t\t}\n\t}\n}","smell_code":"\t\t[Desc(\"Returns all living actors of the specified types of this player.\")]\n\t\tpublic Actor[] GetActorsByTypes(string[] types)\n\t\t{\n\t\t\tvar result = new List();\n\n\t\t\tforeach (var type in types)\n\t\t\t\tif (!Context.World.Map.Rules.Actors.ContainsKey(type))\n\t\t\t\t\tthrow new LuaException(\"Unknown actor type '{0}'\".F(type));\n\n\t\t\tresult.AddRange(Player.World.Actors\n\t\t\t\t.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && types.Contains(actor.Info.Name)));\n\n\t\t\treturn result.ToArray();\n\t\t}","smell":"long method","id":79} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osuTK;\nusing osuTK.Graphics;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Shapes;\nusing osu.Game.Rulesets.Taiko.Objects;\n\nnamespace osu.Game.Rulesets.Taiko.UI\n{\n \/\/\/ \n \/\/\/ A component that is displayed at the hit position in the taiko playfield.\n \/\/\/ <\/summary>\n internal class TaikoHitTarget : Container\n {\n \/\/\/ \n \/\/\/ Thickness of all drawn line pieces.\n \/\/\/ <\/summary>\n private const float border_thickness = 2.5f;\n\n public TaikoHitTarget()\n {\n RelativeSizeAxes = Axes.Both;\n\n Children = new Drawable[]\n {\n new Box\n {\n Name = \"Bar Upper\",\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n RelativeSizeAxes = Axes.Y,\n Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) \/ 2f),\n Alpha = 0.1f\n },\n new CircularContainer\n {\n Name = \"Strong Hit Ring\",\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n RelativeSizeAxes = Axes.Both,\n Size = new Vector2(TaikoStrongableHitObject.DEFAULT_STRONG_SIZE),\n Masking = true,\n BorderColour = Color4.White,\n BorderThickness = border_thickness,\n Alpha = 0.1f,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n },\n new CircularContainer\n {\n Name = \"Normal Hit Ring\",\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n RelativeSizeAxes = Axes.Both,\n Size = new Vector2(TaikoHitObject.DEFAULT_SIZE),\n Masking = true,\n BorderColour = Color4.White,\n BorderThickness = border_thickness,\n Alpha = 0.5f,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n },\n new Box\n {\n Name = \"Bar Lower\",\n Anchor = Anchor.BottomCentre,\n Origin = Anchor.BottomCentre,\n RelativeSizeAxes = Axes.Y,\n Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) \/ 2f),\n Alpha = 0.1f\n },\n };\n }\n }\n}","smell_code":" public TaikoHitTarget()\n {\n RelativeSizeAxes = Axes.Both;\n\n Children = new Drawable[]\n {\n new Box\n {\n Name = \"Bar Upper\",\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n RelativeSizeAxes = Axes.Y,\n Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) \/ 2f),\n Alpha = 0.1f\n },\n new CircularContainer\n {\n Name = \"Strong Hit Ring\",\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n RelativeSizeAxes = Axes.Both,\n Size = new Vector2(TaikoStrongableHitObject.DEFAULT_STRONG_SIZE),\n Masking = true,\n BorderColour = Color4.White,\n BorderThickness = border_thickness,\n Alpha = 0.1f,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n },\n new CircularContainer\n {\n Name = \"Normal Hit Ring\",\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n RelativeSizeAxes = Axes.Both,\n Size = new Vector2(TaikoHitObject.DEFAULT_SIZE),\n Masking = true,\n BorderColour = Color4.White,\n BorderThickness = border_thickness,\n Alpha = 0.5f,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n },\n new Box\n {\n Name = \"Bar Lower\",\n Anchor = Anchor.BottomCentre,\n Origin = Anchor.BottomCentre,\n RelativeSizeAxes = Axes.Y,\n Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) \/ 2f),\n Alpha = 0.1f\n },\n };\n }","smell":"long method","id":80} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Framework.Graphics.Textures;\nusing osu.Game.Rulesets.Objects.Drawables;\nusing osu.Game.Rulesets.Osu.Objects;\nusing osuTK;\n\nnamespace osu.Game.Rulesets.Osu.Skinning.Default\n{\n public class CirclePiece : CompositeDrawable\n {\n [Resolved]\n private DrawableHitObject drawableObject { get; set; }\n\n private TrianglesPiece triangles;\n\n public CirclePiece()\n {\n Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);\n Masking = true;\n\n CornerRadius = Size.X \/ 2;\n CornerExponent = 2;\n\n Anchor = Anchor.Centre;\n Origin = Anchor.Centre;\n }\n\n [BackgroundDependencyLoader]\n private void load(TextureStore textures)\n {\n InternalChildren = new Drawable[]\n {\n new Sprite\n {\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n Texture = textures.Get(@\"Gameplay\/osu\/disc\"),\n },\n triangles = new TrianglesPiece\n {\n RelativeSizeAxes = Axes.Both,\n Blending = BlendingParameters.Additive,\n Alpha = 0.5f,\n }\n };\n\n drawableObject.HitObjectApplied += onHitObjectApplied;\n onHitObjectApplied(drawableObject);\n }\n\n private void onHitObjectApplied(DrawableHitObject obj)\n {\n if (obj.HitObject == null)\n return;\n\n triangles.Reset((int)obj.HitObject.StartTime);\n }\n\n protected override void Dispose(bool isDisposing)\n {\n base.Dispose(isDisposing);\n\n if (drawableObject != null)\n drawableObject.HitObjectApplied -= onHitObjectApplied;\n }\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load(TextureStore textures)\n {\n InternalChildren = new Drawable[]\n {\n new Sprite\n {\n Anchor = Anchor.Centre,\n Origin = Anchor.Centre,\n Texture = textures.Get(@\"Gameplay\/osu\/disc\"),\n },\n triangles = new TrianglesPiece\n {\n RelativeSizeAxes = Axes.Both,\n Blending = BlendingParameters.Additive,\n Alpha = 0.5f,\n }\n };\n\n drawableObject.HitObjectApplied += onHitObjectApplied;\n onHitObjectApplied(drawableObject);\n }","smell":"long method","id":81} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace OpenRA.Platforms.Default\n{\n\tsealed class VertexBuffer : ThreadAffine, IVertexBuffer\n\t\t\twhere T : struct\n\t{\n\t\tstatic readonly int VertexSize = Marshal.SizeOf(typeof(T));\n\t\tuint buffer;\n\t\tbool disposed;\n\n\t\tpublic VertexBuffer(int size)\n\t\t{\n\t\t\tOpenGL.glGenBuffers(1, out buffer);\n\t\t\tOpenGL.CheckGLError();\n\t\t\tBind();\n\n\t\t\t\/\/ Generates a buffer with uninitialized memory.\n\t\t\tOpenGL.glBufferData(OpenGL.GL_ARRAY_BUFFER,\n\t\t\t\t\tnew IntPtr(VertexSize * size),\n\t\t\t\t\tIntPtr.Zero,\n\t\t\t\t\tOpenGL.GL_DYNAMIC_DRAW);\n\t\t\tOpenGL.CheckGLError();\n\n\t\t\t\/\/ We need to zero all the memory. Let's generate a smallish array and copy that over the whole buffer.\n\t\t\tvar zeroedArrayElementSize = Math.Min(size, 2048);\n\t\t\tvar ptr = GCHandle.Alloc(new T[zeroedArrayElementSize], GCHandleType.Pinned);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfor (var offset = 0; offset < size; offset += zeroedArrayElementSize)\n\t\t\t\t{\n\t\t\t\t\tvar length = Math.Min(zeroedArrayElementSize, size - offset);\n\t\t\t\t\tOpenGL.glBufferSubData(OpenGL.GL_ARRAY_BUFFER,\n\t\t\t\t\t\tnew IntPtr(VertexSize * offset),\n\t\t\t\t\t\tnew IntPtr(VertexSize * length),\n\t\t\t\t\t\tptr.AddrOfPinnedObject());\n\t\t\t\t\tOpenGL.CheckGLError();\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tptr.Free();\n\t\t\t}\n\t\t}\n\n\t\tpublic void SetData(T[] data, int length)\n\t\t{\n\t\t\tSetData(data, 0, 0, length);\n\t\t}\n\n\t\tpublic void SetData(T[] data, int offset, int start, int length)\n\t\t{\n\t\t\tBind();\n\n\t\t\tvar ptr = GCHandle.Alloc(data, GCHandleType.Pinned);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tOpenGL.glBufferSubData(OpenGL.GL_ARRAY_BUFFER,\n\t\t\t\t\tnew IntPtr(VertexSize * start),\n\t\t\t\t\tnew IntPtr(VertexSize * length),\n\t\t\t\t\tptr.AddrOfPinnedObject() + VertexSize * offset);\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tptr.Free();\n\t\t\t}\n\n\t\t\tOpenGL.CheckGLError();\n\t\t}\n\n\t\tpublic void Bind()\n\t\t{\n\t\t\tVerifyThreadAffinity();\n\t\t\tOpenGL.glBindBuffer(OpenGL.GL_ARRAY_BUFFER, buffer);\n\t\t\tOpenGL.CheckGLError();\n\t\t\tOpenGL.glVertexAttribPointer(Shader.VertexPosAttributeIndex, 3, OpenGL.GL_FLOAT, false, VertexSize, IntPtr.Zero);\n\t\t\tOpenGL.CheckGLError();\n\t\t\tOpenGL.glVertexAttribPointer(Shader.TexCoordAttributeIndex, 4, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(12));\n\t\t\tOpenGL.CheckGLError();\n\t\t\tOpenGL.glVertexAttribPointer(Shader.TexMetadataAttributeIndex, 2, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(28));\n\t\t\tOpenGL.CheckGLError();\n\t\t\tOpenGL.glVertexAttribPointer(Shader.TintAttributeIndex, 3, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(36));\n\t\t\tOpenGL.CheckGLError();\n\t\t}\n\n\t\tpublic void Dispose()\n\t\t{\n\t\t\tDispose(true);\n\t\t\tGC.SuppressFinalize(this);\n\t\t}\n\n\t\tvoid Dispose(bool disposing)\n\t\t{\n\t\t\tif (disposed)\n\t\t\t\treturn;\n\t\t\tdisposed = true;\n\t\t\tOpenGL.glDeleteBuffers(1, ref buffer);\n\t\t\tOpenGL.CheckGLError();\n\t\t}\n\t}\n}","smell_code":"\t\tvoid Dispose(bool disposing)\n\t\t{\n\t\t\tif (disposed)\n\t\t\t\treturn;\n\t\t\tdisposed = true;\n\t\t\tOpenGL.glDeleteBuffers(1, ref buffer);\n\t\t\tOpenGL.CheckGLError();\n\t\t}","smell":"long method","id":82} {"lang_cluster":"C#","source_code":"using System;\nusing BurningKnight.assets;\nusing BurningKnight.assets.lighting;\nusing BurningKnight.assets.particle;\nusing BurningKnight.assets.particle.custom;\nusing BurningKnight.entity.component;\nusing BurningKnight.state;\nusing BurningKnight.util;\nusing Lens.entity;\nusing Lens.graphics;\nusing Lens.util.file;\nusing Lens.util.math;\nusing Microsoft.Xna.Framework;\n\nnamespace BurningKnight.level.entities.decor {\n\tpublic class Torch : SolidProp {\n\t\tpublic bool On = true;\n\t\tpublic float XSpread = 1f;\n\t\tpublic Vector2? Target;\n\t\t\n\t\tprivate bool broken;\n\t\tprivate FireEmitter emitter;\n\t\tprivate float t;\n\t\t\n\t\tpublic override void Init() {\n\t\t\tbase.Init();\n\n\t\t\tWidth = 10;\n\t\t\tSprite = \"torch\";\n\t\t\tt = Rnd.Float(6);\n\t\t\tAlwaysActive = Run.Depth < 1;\n\t\t}\n\n\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\t\t\t\n\t\t\tAddComponent(new LightComponent(this, 32f, new Color(1f, 0.8f, 0.3f, 1f)));\n\t\t\tAddComponent(new ShadowComponent());\n\t\t\tAddComponent(new RoomComponent());\n\t\t\t\n\t\t\tAddTag(Tags.Torch);\n\t\t}\n\n\t\tpublic override void Destroy() {\n\t\t\tbase.Destroy();\n\n\t\t\tif (emitter != null) {\n\t\t\t\temitter.Done = true;\n\t\t\t}\n\t\t}\n\n\t\tpublic override void PostInit() {\n\t\t\tbase.PostInit();\n\n\t\t\tif (!broken) {\n\t\t\t\tArea.Add(emitter = new FireEmitter {\n\t\t\t\t\tDepth = Depth + 1,\n\t\t\t\t\tPosition = new Vector2(CenterX, Y + 3),\n\t\t\t\t\tScale = 0.5f\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tUpdateSprite();\n\t\t}\n\n\t\tprivate void UpdateSprite() {\n\t\t\tif (broken) {\n\t\t\t\tvar s = GetComponent();\n\n\t\t\t\ts.Sprite = CommonAse.Props.GetSlice(\"broken_torch\");\n\t\t\t\ts.Offset = new Vector2(0, 5);\n\t\t\t}\n\t\t}\n\n\t\tpublic void Break() {\n\t\t\tif (broken) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tOn = false;\n\t\t\tbroken = true;\n\n\t\t\tif (emitter != null) {\n\t\t\t\temitter.Done = true;\n\t\t\t}\n\t\t\t\n\t\t\tAnimationUtil.Poof(Center);\n\t\t\tParticles.BreakSprite(Area, GetComponent().Sprite, Position);\n\t\t\t\n\t\t\tUpdateSprite();\n\t\t}\n\t\t\n\t\tprivate float lastFlame;\n\n\t\tpublic override void Update(float dt) {\n\t\t\tbase.Update(dt);\n\n\t\t\tif (!On) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tt += dt * 0.5f;\n\t\t\tGetComponent().Light.Radius = 38f + (float) Math.Cos(t) * 6;\n\t\t\tlastFlame += dt;\n\n\t\t\tif (lastFlame > 0.1f) {\n\t\t\t\tArea.Add(new FireParticle {\n\t\t\t\t\tX = CenterX,\n\t\t\t\t\tY = Y + 2,\n\t\t\t\t\tTarget = Target,\n\t\t\t\t\tXChange = XSpread\n\t\t\t\t});\n\n\t\t\t\tlastFlame = 0;\n\t\t\t}\n\t\t}\n\n\t\tprotected override Rectangle GetCollider() {\n\t\t\treturn new Rectangle(2, 5, 6, 5);\n\t\t}\n\n\t\tpublic override void Load(FileReader stream) {\n\t\t\tbase.Load(stream);\n\t\t\tbroken = stream.ReadBoolean();\n\t\t}\n\n\t\tpublic override void Save(FileWriter stream) {\n\t\t\tbase.Save(stream);\n\t\t\tstream.WriteBoolean(broken);\n\t\t}\n\n\t\tpublic override bool ShouldCollide(Entity entity) {\n\t\t\treturn false;\n\t\t}\n\t}\n}","smell_code":"\t\tpublic override void AddComponents() {\n\t\t\tbase.AddComponents();\n\t\t\t\n\t\t\tAddComponent(new LightComponent(this, 32f, new Color(1f, 0.8f, 0.3f, 1f)));\n\t\t\tAddComponent(new ShadowComponent());\n\t\t\tAddComponent(new RoomComponent());\n\t\t\t\n\t\t\tAddTag(Tags.Torch);\n\t\t}","smell":"long method","id":83} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing OpenRA.Activities;\nusing OpenRA.Mods.Common.Pathfinder;\nusing OpenRA.Mods.Common.Traits;\nusing OpenRA.Primitives;\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Activities\n{\n\tpublic class MoveAdjacentTo : Activity\n\t{\n\t\tstatic readonly List NoPath = new List();\n\n\t\tprotected readonly Mobile Mobile;\n\t\treadonly IPathFinder pathFinder;\n\t\treadonly DomainIndex domainIndex;\n\t\treadonly Color? targetLineColor;\n\n\t\tprotected Target Target\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn useLastVisibleTarget ? lastVisibleTarget : target;\n\t\t\t}\n\t\t}\n\n\t\tTarget target;\n\t\tTarget lastVisibleTarget;\n\t\tprotected CPos lastVisibleTargetLocation;\n\t\tbool useLastVisibleTarget;\n\n\t\tpublic MoveAdjacentTo(Actor self, in Target target, WPos? initialTargetPosition = null, Color? targetLineColor = null)\n\t\t{\n\t\t\tthis.target = target;\n\t\t\tthis.targetLineColor = targetLineColor;\n\t\t\tMobile = self.Trait();\n\t\t\tpathFinder = self.World.WorldActor.Trait();\n\t\t\tdomainIndex = self.World.WorldActor.Trait();\n\t\t\tChildHasPriority = false;\n\n\t\t\t\/\/ The target may become hidden between the initial order request and the first tick (e.g. if queued)\n\t\t\t\/\/ Moving to any position (even if quite stale) is still better than immediately giving up\n\t\t\tif ((target.Type == TargetType.Actor && target.Actor.CanBeViewedByPlayer(self.Owner))\n\t\t\t || target.Type == TargetType.FrozenActor || target.Type == TargetType.Terrain)\n\t\t\t{\n\t\t\t\tlastVisibleTarget = Target.FromPos(target.CenterPosition);\n\t\t\t\tlastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition);\n\t\t\t}\n\t\t\telse if (initialTargetPosition.HasValue)\n\t\t\t{\n\t\t\t\tlastVisibleTarget = Target.FromPos(initialTargetPosition.Value);\n\t\t\t\tlastVisibleTargetLocation = self.World.Map.CellContaining(initialTargetPosition.Value);\n\t\t\t}\n\t\t}\n\n\t\tprotected virtual bool ShouldStop(Actor self)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tprotected virtual bool ShouldRepath(Actor self, CPos targetLocation)\n\t\t{\n\t\t\treturn lastVisibleTargetLocation != targetLocation;\n\t\t}\n\n\t\tprotected virtual IEnumerable CandidateMovementCells(Actor self)\n\t\t{\n\t\t\treturn Util.AdjacentCells(self.World, Target)\n\t\t\t\t.Where(c => Mobile.CanStayInCell(c));\n\t\t}\n\n\t\tprotected override void OnFirstRun(Actor self)\n\t\t{\n\t\t\tQueueChild(Mobile.MoveTo(check => CalculatePathToTarget(self, check)));\n\t\t}\n\n\t\tpublic override bool Tick(Actor self)\n\t\t{\n\t\t\tvar oldTargetLocation = lastVisibleTargetLocation;\n\t\t\ttarget = target.Recalculate(self.Owner, out var targetIsHiddenActor);\n\t\t\tif (!targetIsHiddenActor && target.Type == TargetType.Actor)\n\t\t\t{\n\t\t\t\tlastVisibleTarget = Target.FromTargetPositions(target);\n\t\t\t\tlastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition);\n\t\t\t}\n\n\t\t\t\/\/ Target is equivalent to checkTarget variable in other activities\n\t\t\t\/\/ value is either lastVisibleTarget or target based on visibility and validity\n\t\t\tvar targetIsValid = Target.IsValidFor(self);\n\t\t\tuseLastVisibleTarget = targetIsHiddenActor || !targetIsValid;\n\n\t\t\t\/\/ Target is hidden or dead, and we don't have a fallback position to move towards\n\t\t\tvar noTarget = useLastVisibleTarget && !lastVisibleTarget.IsValidFor(self);\n\n\t\t\t\/\/ Cancel the current path if the activity asks to stop, or asks to repath\n\t\t\t\/\/ The repath happens once the move activity stops in the next cell\n\t\t\tvar shouldRepath = targetIsValid && ShouldRepath(self, oldTargetLocation);\n\t\t\tif (ChildActivity != null && (ShouldStop(self) || shouldRepath || noTarget))\n\t\t\t\tChildActivity.Cancel(self);\n\n\t\t\t\/\/ Target has moved, and MoveAdjacentTo is still valid.\n\t\t\tif (!IsCanceling && shouldRepath)\n\t\t\t\tQueueChild(Mobile.MoveTo(check => CalculatePathToTarget(self, check)));\n\n\t\t\t\/\/ The last queued childactivity is guaranteed to be the inner move, so if the childactivity\n\t\t\t\/\/ queue is empty it means we have reached our destination.\n\t\t\treturn TickChild(self);\n\t\t}\n\n\t\tList searchCells = new List();\n\t\tint searchCellsTick = -1;\n\n\t\tList CalculatePathToTarget(Actor self, BlockedByActor check)\n\t\t{\n\t\t\tvar loc = self.Location;\n\n\t\t\t\/\/ PERF: Assume that CandidateMovementCells doesn't change within a tick to avoid repeated queries\n\t\t\t\/\/ when Move enumerates different BlockedByActor values\n\t\t\tif (searchCellsTick != self.World.WorldTick)\n\t\t\t{\n\t\t\t\tsearchCells.Clear();\n\t\t\t\tsearchCellsTick = self.World.WorldTick;\n\t\t\t\tforeach (var cell in CandidateMovementCells(self))\n\t\t\t\t\tif (domainIndex.IsPassable(loc, cell, Mobile.Locomotor) && Mobile.CanEnterCell(cell))\n\t\t\t\t\t\tsearchCells.Add(cell);\n\t\t\t}\n\n\t\t\tif (!searchCells.Any())\n\t\t\t\treturn NoPath;\n\n\t\t\tusing (var fromSrc = PathSearch.FromPoints(self.World, Mobile.Locomotor, self, searchCells, loc, check))\n\t\t\tusing (var fromDest = PathSearch.FromPoint(self.World, Mobile.Locomotor, self, loc, lastVisibleTargetLocation, check).Reverse())\n\t\t\t\treturn pathFinder.FindBidiPath(fromSrc, fromDest);\n\t\t}\n\n\t\tpublic override IEnumerable GetTargets(Actor self)\n\t\t{\n\t\t\tif (ChildActivity != null)\n\t\t\t\treturn ChildActivity.GetTargets(self);\n\n\t\t\treturn Target.None;\n\t\t}\n\n\t\tpublic override IEnumerable TargetLineNodes(Actor self)\n\t\t{\n\t\t\tif (targetLineColor.HasValue)\n\t\t\t\tyield return new TargetLineNode(useLastVisibleTarget ? lastVisibleTarget : target, targetLineColor.Value);\n\t\t}\n\t}\n}","smell_code":"\t\tpublic override bool Tick(Actor self)\n\t\t{\n\t\t\tvar oldTargetLocation = lastVisibleTargetLocation;\n\t\t\ttarget = target.Recalculate(self.Owner, out var targetIsHiddenActor);\n\t\t\tif (!targetIsHiddenActor && target.Type == TargetType.Actor)\n\t\t\t{\n\t\t\t\tlastVisibleTarget = Target.FromTargetPositions(target);\n\t\t\t\tlastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition);\n\t\t\t}\n\n\t\t\t\/\/ Target is equivalent to checkTarget variable in other activities\n\t\t\t\/\/ value is either lastVisibleTarget or target based on visibility and validity\n\t\t\tvar targetIsValid = Target.IsValidFor(self);\n\t\t\tuseLastVisibleTarget = targetIsHiddenActor || !targetIsValid;\n\n\t\t\t\/\/ Target is hidden or dead, and we don't have a fallback position to move towards\n\t\t\tvar noTarget = useLastVisibleTarget && !lastVisibleTarget.IsValidFor(self);\n\n\t\t\t\/\/ Cancel the current path if the activity asks to stop, or asks to repath\n\t\t\t\/\/ The repath happens once the move activity stops in the next cell\n\t\t\tvar shouldRepath = targetIsValid && ShouldRepath(self, oldTargetLocation);\n\t\t\tif (ChildActivity != null && (ShouldStop(self) || shouldRepath || noTarget))\n\t\t\t\tChildActivity.Cancel(self);\n\n\t\t\t\/\/ Target has moved, and MoveAdjacentTo is still valid.\n\t\t\tif (!IsCanceling && shouldRepath)\n\t\t\t\tQueueChild(Mobile.MoveTo(check => CalculatePathToTarget(self, check)));\n\n\t\t\t\/\/ The last queued childactivity is guaranteed to be the inner move, so if the childactivity\n\t\t\t\/\/ queue is empty it means we have reached our destination.\n\t\t\treturn TickChild(self);\n\t\t}","smell":"long method","id":84} {"lang_cluster":"C#","source_code":"using System;\nusing BurningKnight.entity.component;\nusing BurningKnight.entity.projectile;\nusing BurningKnight.util;\nusing Lens.entity;\nusing Lens.util;\nusing Lens.util.camera;\nusing Lens.util.math;\nusing Microsoft.Xna.Framework;\n\nnamespace BurningKnight.entity {\n\tpublic static class BlankMaker {\n\t\tpublic const float Radius = 48f;\n\t\t\n\t\tpublic static void Make(Vector2 where, Area area, float r = Radius) {\n\t\t\tforeach (var p in area.Tagged[Tags.Projectile]) {\n\t\t\t\tif (p.DistanceTo(where) <= r) {\n\t\t\t\t\t((Projectile) p).Break();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tforeach (var e in area.Tagged[Tags.MustBeKilled]) {\n\t\t\t\tif (e.DistanceTo(where) <= r) {\n\t\t\t\t\te.GetAnyComponent()?.KnockbackFrom(where, 10f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < 10; i++) {\n\t\t\t\tvar a = i * 0.1f * Math.PI * 2 + Rnd.Float(-0.1f, 0.1f);\n\t\t\t\tAnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, r - 8), where);\n\t\t\t}\n\t\t\t\n\t\t\tfor (var i = 0; i < 10; i++) {\n\t\t\t\tvar a = Rnd.AnglePI();\n\t\t\t\tvar d = Rnd.Float(r);\n\t\t\t\t\n\t\t\t\tAnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, d), where);\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\tCamera.Instance.Shake(6);\n\t\t}\n\t}\n}","smell_code":"\t\tpublic static void Make(Vector2 where, Area area, float r = Radius) {\n\t\t\tforeach (var p in area.Tagged[Tags.Projectile]) {\n\t\t\t\tif (p.DistanceTo(where) <= r) {\n\t\t\t\t\t((Projectile) p).Break();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tforeach (var e in area.Tagged[Tags.MustBeKilled]) {\n\t\t\t\tif (e.DistanceTo(where) <= r) {\n\t\t\t\t\te.GetAnyComponent()?.KnockbackFrom(where, 10f);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < 10; i++) {\n\t\t\t\tvar a = i * 0.1f * Math.PI * 2 + Rnd.Float(-0.1f, 0.1f);\n\t\t\t\tAnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, r - 8), where);\n\t\t\t}\n\t\t\t\n\t\t\tfor (var i = 0; i < 10; i++) {\n\t\t\t\tvar a = Rnd.AnglePI();\n\t\t\t\tvar d = Rnd.Float(r);\n\t\t\t\t\n\t\t\t\tAnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, d), where);\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\tCamera.Instance.Shake(6);\n\t\t}","smell":"long method","id":85} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing System.Collections.Generic;\nusing OpenRA.Graphics;\nusing OpenRA.Mods.Common.Traits;\nusing OpenRA.Widgets;\n\nnamespace OpenRA.Mods.Common.Widgets.Logic\n{\n\tpublic class HistoryLogLogic : ChromeLogic\n\t{\n\t\treadonly ScrollPanelWidget panel;\n\t\treadonly EditorActionManager editorActionManager;\n\t\treadonly ScrollItemWidget template;\n\n\t\treadonly Dictionary states = new Dictionary();\n\n\t\t[ObjectCreator.UseCtor]\n\t\tpublic HistoryLogLogic(Widget widget, World world, WorldRenderer worldRenderer, Dictionary logicArgs)\n\t\t{\n\t\t\tpanel = widget.Get(\"HISTORY_LIST\");\n\t\t\ttemplate = panel.Get(\"HISTORY_TEMPLATE\");\n\t\t\teditorActionManager = world.WorldActor.Trait();\n\n\t\t\teditorActionManager.ItemAdded += ItemAdded;\n\t\t\teditorActionManager.ItemRemoved += ItemRemoved;\n\t\t}\n\n\t\tvoid ItemAdded(EditorActionContainer editorAction)\n\t\t{\n\t\t\tvar item = ScrollItemWidget.Setup(template, () => false, () =>\n\t\t\t{\n\t\t\t\tif (editorAction.Status == EditorActionStatus.History)\n\t\t\t\t\teditorActionManager.Rewind(editorAction.Id);\n\t\t\t\telse if (editorAction.Status == EditorActionStatus.Future)\n\t\t\t\t\teditorActionManager.Forward(editorAction.Id);\n\t\t\t});\n\n\t\t\tvar titleLabel = item.Get(\"TITLE\");\n\t\t\tvar textColor = template.TextColor;\n\t\t\tvar futureTextColor = template.TextColorDisabled;\n\n\t\t\ttitleLabel.GetText = () => editorAction.Action.Text;\n\t\t\ttitleLabel.GetColor = () => editorAction.Status == EditorActionStatus.Future ? futureTextColor : textColor;\n\n\t\t\titem.IsSelected = () => editorAction.Status == EditorActionStatus.Active;\n\t\t\tpanel.AddChild(item);\n\n\t\t\tstates[editorAction] = item;\n\t\t}\n\n\t\tvoid ItemRemoved(EditorActionContainer editorAction)\n\t\t{\n\t\t\tvar widget = states[editorAction];\n\n\t\t\tpanel.RemoveChild(widget);\n\n\t\t\tstates.Remove(editorAction);\n\t\t}\n\t}\n}","smell_code":"\t\t[ObjectCreator.UseCtor]\n\t\tpublic HistoryLogLogic(Widget widget, World world, WorldRenderer worldRenderer, Dictionary logicArgs)\n\t\t{\n\t\t\tpanel = widget.Get(\"HISTORY_LIST\");\n\t\t\ttemplate = panel.Get(\"HISTORY_TEMPLATE\");\n\t\t\teditorActionManager = world.WorldActor.Trait();\n\n\t\t\teditorActionManager.ItemAdded += ItemAdded;\n\t\t\teditorActionManager.ItemRemoved += ItemRemoved;\n\t\t}","smell":"long method","id":86} {"lang_cluster":"C#","source_code":"\ufeff#region License Information (GPL v3)\n\n\/*\n ShareX - A program that allows you to take screenshots and share any file type\n Copyright (c) 2007-2020 ShareX Team\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n Optionally you can also view the license at .\n*\/\n\n#endregion License Information (GPL v3)\n\nusing ShareX.HelpersLib;\nusing System.ComponentModel;\nusing System.Drawing;\n\nnamespace ShareX.ImageEffectsLib\n{\n internal class Hue : ImageEffect\n {\n [DefaultValue(0f), Description(\"From 0 to 360\")]\n public float Angle { get; set; }\n\n public Hue()\n {\n this.ApplyDefaultPropertyValues();\n }\n\n public override Bitmap Apply(Bitmap bmp)\n {\n using (bmp)\n {\n return ColorMatrixManager.Hue(Angle).Apply(bmp);\n }\n }\n }\n}","smell_code":" public override Bitmap Apply(Bitmap bmp)\n {\n using (bmp)\n {\n return ColorMatrixManager.Hue(Angle).Apply(bmp);\n }\n }","smell":"long method","id":87} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Graphics;\nusing osu.Game.Graphics.Sprites;\nusing osu.Framework.Allocation;\nusing osu.Game.Extensions;\nusing osu.Game.Graphics;\n\nnamespace osu.Game.Screens.Edit.Components\n{\n public class TimeInfoContainer : BottomBarContainer\n {\n private readonly OsuSpriteText trackTimer;\n\n [Resolved]\n private EditorClock editorClock { get; set; }\n\n public TimeInfoContainer()\n {\n Children = new Drawable[]\n {\n trackTimer = new OsuSpriteText\n {\n Anchor = Anchor.CentreRight,\n Origin = Anchor.CentreRight,\n \/\/ intentionally fudged centre to avoid movement of the number portion when\n \/\/ going negative.\n X = -35,\n Font = OsuFont.GetFont(size: 25, fixedWidth: true),\n }\n };\n }\n\n protected override void Update()\n {\n base.Update();\n trackTimer.Text = editorClock.CurrentTime.ToEditorFormattedString();\n }\n }\n}","smell_code":" public TimeInfoContainer()\n {\n Children = new Drawable[]\n {\n trackTimer = new OsuSpriteText\n {\n Anchor = Anchor.CentreRight,\n Origin = Anchor.CentreRight,\n \/\/ intentionally fudged centre to avoid movement of the number portion when\n \/\/ going negative.\n X = -35,\n Font = OsuFont.GetFont(size: 25, fixedWidth: true),\n }\n };\n }","smell":"long method","id":88} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common\n{\n\tpublic static class ShroudExts\n\t{\n\t\tpublic static bool AnyExplored(this Shroud shroud, (CPos Cell, SubCell SubCell)[] cells)\n\t\t{\n\t\t\t\/\/ PERF: Avoid LINQ.\n\t\t\tforeach (var cell in cells)\n\t\t\t\tif (shroud.IsExplored(cell.Cell))\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static bool AnyExplored(this Shroud shroud, PPos[] puvs)\n\t\t{\n\t\t\t\/\/ PERF: Avoid LINQ.\n\t\t\tforeach (var puv in puvs)\n\t\t\t\tif (shroud.IsExplored(puv))\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static bool AnyVisible(this Shroud shroud, (CPos Cell, SubCell SubCell)[] cells)\n\t\t{\n\t\t\t\/\/ PERF: Avoid LINQ.\n\t\t\tforeach (var cell in cells)\n\t\t\t\tif (shroud.IsVisible(cell.Cell))\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\t}\n}","smell_code":"\t\tpublic static bool AnyExplored(this Shroud shroud, PPos[] puvs)\n\t\t{\n\t\t\t\/\/ PERF: Avoid LINQ.\n\t\t\tforeach (var puv in puvs)\n\t\t\t\tif (shroud.IsExplored(puv))\n\t\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}","smell":"long method","id":89} {"lang_cluster":"C#","source_code":"using System;\nusing System.Linq;\nusing BurningKnight.assets.achievements;\nusing BurningKnight.entity.creature.npc;\nusing BurningKnight.entity.creature.npc.dungeon;\nusing BurningKnight.entity.door;\nusing BurningKnight.level.biome;\nusing BurningKnight.level.tile;\nusing BurningKnight.save;\nusing BurningKnight.state;\nusing BurningKnight.util.geometry;\nusing Lens.util;\nusing Lens.util.math;\nusing Microsoft.Xna.Framework;\n\nnamespace BurningKnight.level.rooms.special {\n\tpublic class NpcSaveRoom : SpecialRoom {\n\t\tprivate class NpcData {\n\t\t\tpublic NpcData(byte d, string i) {\n\t\t\t\tDepth = d;\n\t\t\t\tId = i;\n\t\t\t}\n\t\t\t\n\t\t\tpublic byte Depth;\n\t\t\tpublic string Id;\n\t\t}\n\t\t\n\t\tprivate static NpcData[] npcs = {\n\t\t\tnew NpcData(2, ShopNpc.HatTrader),\n\t\t\tnew NpcData(2, ShopNpc.AccessoryTrader),\n\t\t\tnew NpcData(3, ShopNpc.ActiveTrader),\n\t\t\tnew NpcData(3, ShopNpc.WeaponTrader),\n\t\t\tnew NpcData(4, ShopNpc.Snek),\n\t\t\tnew NpcData(4, ShopNpc.Boxy),\n\t\t\tnew NpcData(5, ShopNpc.Duck),\n\t\t\tnew NpcData(6, ShopNpc.Vampire),\n\t\t\tnew NpcData(7, ShopNpc.Elon),\n\t\t\tnew NpcData(8, ShopNpc.Gobetta),\n\t\t\tnew NpcData(9, ShopNpc.Nurse),\n\t\t\tnew NpcData(10, ShopNpc.Roger),\n\t\t\tnew NpcData(10, ShopNpc.Mike)\n\t\t};\n\t\t\n\t\tpublic override int GetMaxConnections(Connection Side) {\n\t\t\treturn 1;\n\t\t}\n\n\t\tpublic override int GetMinConnections(Connection Side) {\n\t\t\treturn Side == Connection.All ? 1 : 0;\n\t\t}\n\n\t\tpublic override bool CanConnect(RoomDef R) {\n\t\t\treturn base.CanConnect(R) && !(R is NpcKeyRoom);\n\t\t}\n\n\t\tpublic override int GetMaxWidth() {\n\t\t\treturn 10;\n\t\t}\n\n\t\tpublic override int GetMaxHeight() {\n\t\t\treturn 10;\n\t\t}\n\n\t\tprivate static bool DefeatedBosses() {\n\t\t\treturn Achievements.IsComplete(\"bk:democracy\") && Achievements.IsComplete(\"bk:mummified\") && Achievements.IsComplete(\"bk:ice_boss\") && Achievements.IsComplete(\"bk:bk_no_more\") && Achievements.IsComplete(\"bk:sting_operation\");\n\t\t}\n\n\t\tprivate static string GenerateNpc() {\n\t\t\tvar d = Run.Depth;\n\n\t\t\tforeach (var info in npcs) {\n\t\t\t\tif (info.Depth == d && GlobalSave.IsFalse(info.Id)) {\n\t\t\t\t\tif (info.Id == ShopNpc.Mike && !DefeatedBosses()) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tLog.Info($\"Npc {info.Id} should be generated\");\n\t\t\t\t\treturn info.Id;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tLog.Info($\"No npc should be generated\");\n\t\t\treturn null;\n\t\t}\n\n\t\tpublic override void Paint(Level level) {\n\t\t\tvar ice = LevelSave.BiomeGenerated is IceBiome;\n\t\t\n\t\t\tif (ice) {\n\t\t\t\tvar clip = Painter.Clip;\n\t\t\t\tPainter.Clip = null;\n\t\t\t\tPainter.Rect(level, this, 0, Tile.WallB);\n\t\t\t\tPainter.Clip = clip;\n\t\t\t}\n\t\t\t\n\t\t\tvar id = GenerateNpc();\n\n\t\t\tif (id == null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tGameSave.Put(\"npc_appeared\", true);\n\n\t\t\tvar d = Connected.Values.First();\n\t\t\tvar npc = ShopNpc.FromId(id);\n\t\t\tlevel.Area.Add(npc);\n\n\t\t\tvar fl = Tiles.RandomFloorOrSpike();\n\t\t\t\n\t\t\tif (d.X == Left || d.X == Right) {\n\t\t\t\tvar w = (int) (GetWidth() \/ 2f + Rnd.Int(-1, 1));\n\t\t\t\tvar door = new Dot(Left + w, Rnd.Int(Top + 2, Bottom - 2));\n\t\t\t\t\n\t\t\t\tPainter.DrawLine(level, new Dot(Left + w, Top), new Dot(Left + w, Bottom), ice ? Tile.WallB : Tile.WallA);\n\t\t\t\tPainter.Set(level, door, fl);\n\t\t\t\t\n\t\t\t\tnpc.Center = new Dot(Left + w + (d.X == Left ? 2 : -2), Rnd.Int(Top + 2, Bottom - 3)) * 16 + new Vector2(8);\n\n\t\t\t\tvar dr = new CageDoor {\n\t\t\t\t\tVertical = true\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tdr.Center = door * 16 + new Vector2(12, 0);\n\t\t\t\tlevel.Area.Add(dr);\n\t\t\t\t\n\t\t\t\tvar v = (d.X == Left ? -1 : 1);\n\t\t\t\t\n\t\t\t\tPainter.DrawLine(level, new Dot(Left + w + v, Top + 1), new Dot(Left + w + v, Bottom - 1), Tiles.Pick(Tile.Chasm, Tile.Lava, Tile.SensingSpikeTmp));\n\t\t\t\tPainter.Set(level, door + new Dot(v, 0), fl);\n\t\t\t} else if (true) {\n\t\t\t\tvar h = (int) (GetHeight() \/ 2f + Rnd.Int(-1, 1));\n\t\t\t\tvar door = new Dot(Rnd.Int(Left + 2, Right - 2), Top + h);\n\n\t\t\t\tPainter.DrawLine(level, new Dot(Left, Top + h), new Dot(Right, Top + h), Tile.WallA);\n\t\t\t\tPainter.Set(level, door, fl);\n\t\t\t\t\n\t\t\t\tnpc.Center = new Dot(Rnd.Int(Left + 2, Right - 2), Top + h + (d.Y == Top ? 2 : -2)) * 16 + new Vector2(8);\n\t\t\t\t\n\t\t\t\tvar dr = new CageDoor();\n\t\t\t\tdr.Center = door * 16 + new Vector2(7, 8);\n\t\t\t\tlevel.Area.Add(dr);\n\n\t\t\t\tvar v = (d.Y == Top ? -1 : 1);\n\t\t\t\t\n\t\t\t\tPainter.DrawLine(level, new Dot(Left + 1, Top + h + v), new Dot(Right - 1, Top + h + v), Tiles.Pick(Tile.Chasm, Tile.Lava, Tile.SensingSpikeTmp));\n\t\t\t\tPainter.Set(level, door + new Dot(0, v), fl);\n\t\t\t}\n\t\t}\n\n\t\tpublic static bool ShouldBeAdded() {\n\t\t\tif (Run.Type != RunType.Regular || GameSave.IsTrue(\"npc_appeared\")) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn GenerateNpc() != null;\n\t\t}\n\t}\n}","smell_code":"\t\tpublic static bool ShouldBeAdded() {\n\t\t\tif (Run.Type != RunType.Regular || GameSave.IsTrue(\"npc_appeared\")) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn GenerateNpc() != null;\n\t\t}","smell":"long method","id":90} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing osu.Game.Beatmaps;\nusing osu.Game.Rulesets.Difficulty;\nusing osu.Game.Rulesets.Difficulty.Preprocessing;\nusing osu.Game.Rulesets.Difficulty.Skills;\nusing osu.Game.Rulesets.Mania.Beatmaps;\nusing osu.Game.Rulesets.Mania.Difficulty.Preprocessing;\nusing osu.Game.Rulesets.Mania.Difficulty.Skills;\nusing osu.Game.Rulesets.Mania.MathUtils;\nusing osu.Game.Rulesets.Mania.Mods;\nusing osu.Game.Rulesets.Mania.Objects;\nusing osu.Game.Rulesets.Mania.Scoring;\nusing osu.Game.Rulesets.Mods;\nusing osu.Game.Rulesets.Objects;\nusing osu.Game.Rulesets.Scoring;\n\nnamespace osu.Game.Rulesets.Mania.Difficulty\n{\n public class ManiaDifficultyCalculator : DifficultyCalculator\n {\n private const double star_scaling_factor = 0.018;\n\n private readonly bool isForCurrentRuleset;\n private readonly double originalOverallDifficulty;\n\n public ManiaDifficultyCalculator(Ruleset ruleset, WorkingBeatmap beatmap)\n : base(ruleset, beatmap)\n {\n isForCurrentRuleset = beatmap.BeatmapInfo.Ruleset.Equals(ruleset.RulesetInfo);\n originalOverallDifficulty = beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty;\n }\n\n protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)\n {\n if (beatmap.HitObjects.Count == 0)\n return new ManiaDifficultyAttributes { Mods = mods, Skills = skills };\n\n HitWindows hitWindows = new ManiaHitWindows();\n hitWindows.SetDifficulty(beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty);\n\n return new ManiaDifficultyAttributes\n {\n StarRating = skills[0].DifficultyValue() * star_scaling_factor,\n Mods = mods,\n \/\/ Todo: This int cast is temporary to achieve 1:1 results with osu!stable, and should be removed in the future\n GreatHitWindow = (int)Math.Ceiling(getHitWindow300(mods) \/ clockRate),\n ScoreMultiplier = getScoreMultiplier(beatmap, mods),\n MaxCombo = beatmap.HitObjects.Sum(h => h is HoldNote ? 2 : 1),\n Skills = skills\n };\n }\n\n protected override IEnumerable CreateDifficultyHitObjects(IBeatmap beatmap, double clockRate)\n {\n var sortedObjects = beatmap.HitObjects.ToArray();\n\n LegacySortHelper.Sort(sortedObjects, Comparer.Create((a, b) => (int)Math.Round(a.StartTime) - (int)Math.Round(b.StartTime)));\n\n for (int i = 1; i < sortedObjects.Length; i++)\n yield return new ManiaDifficultyHitObject(sortedObjects[i], sortedObjects[i - 1], clockRate);\n }\n\n \/\/ Sorting is done in CreateDifficultyHitObjects, since the full list of hitobjects is required.\n protected override IEnumerable SortObjects(IEnumerable input) => input;\n\n protected override Skill[] CreateSkills(IBeatmap beatmap) => new Skill[]\n {\n new Strain(((ManiaBeatmap)beatmap).TotalColumns)\n };\n\n protected override Mod[] DifficultyAdjustmentMods\n {\n get\n {\n var mods = new Mod[]\n {\n new ManiaModDoubleTime(),\n new ManiaModHalfTime(),\n new ManiaModEasy(),\n new ManiaModHardRock(),\n };\n\n if (isForCurrentRuleset)\n return mods;\n\n \/\/ if we are a convert, we can be played in any key mod.\n return mods.Concat(new Mod[]\n {\n new ManiaModKey1(),\n new ManiaModKey2(),\n new ManiaModKey3(),\n new ManiaModKey4(),\n new ManiaModKey5(),\n new MultiMod(new ManiaModKey5(), new ManiaModDualStages()),\n new ManiaModKey6(),\n new MultiMod(new ManiaModKey6(), new ManiaModDualStages()),\n new ManiaModKey7(),\n new MultiMod(new ManiaModKey7(), new ManiaModDualStages()),\n new ManiaModKey8(),\n new MultiMod(new ManiaModKey8(), new ManiaModDualStages()),\n new ManiaModKey9(),\n new MultiMod(new ManiaModKey9(), new ManiaModDualStages()),\n }).ToArray();\n }\n }\n\n private int getHitWindow300(Mod[] mods)\n {\n if (isForCurrentRuleset)\n {\n double od = Math.Min(10.0, Math.Max(0, 10.0 - originalOverallDifficulty));\n return applyModAdjustments(34 + 3 * od, mods);\n }\n\n if (Math.Round(originalOverallDifficulty) > 4)\n return applyModAdjustments(34, mods);\n\n return applyModAdjustments(47, mods);\n\n static int applyModAdjustments(double value, Mod[] mods)\n {\n if (mods.Any(m => m is ManiaModHardRock))\n value \/= 1.4;\n else if (mods.Any(m => m is ManiaModEasy))\n value *= 1.4;\n\n if (mods.Any(m => m is ManiaModDoubleTime))\n value *= 1.5;\n else if (mods.Any(m => m is ManiaModHalfTime))\n value *= 0.75;\n\n return (int)value;\n }\n }\n\n private double getScoreMultiplier(IBeatmap beatmap, Mod[] mods)\n {\n double scoreMultiplier = 1;\n\n foreach (var m in mods)\n {\n switch (m)\n {\n case ManiaModNoFail _:\n case ManiaModEasy _:\n case ManiaModHalfTime _:\n scoreMultiplier *= 0.5;\n break;\n }\n }\n\n var maniaBeatmap = (ManiaBeatmap)beatmap;\n int diff = maniaBeatmap.TotalColumns - maniaBeatmap.OriginalTotalColumns;\n\n if (diff > 0)\n scoreMultiplier *= 0.9;\n else if (diff < 0)\n scoreMultiplier *= 0.9 + 0.04 * diff;\n\n return scoreMultiplier;\n }\n }\n}","smell_code":" protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)\n {\n if (beatmap.HitObjects.Count == 0)\n return new ManiaDifficultyAttributes { Mods = mods, Skills = skills };\n\n HitWindows hitWindows = new ManiaHitWindows();\n hitWindows.SetDifficulty(beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty);\n\n return new ManiaDifficultyAttributes\n {\n StarRating = skills[0].DifficultyValue() * star_scaling_factor,\n Mods = mods,\n \/\/ Todo: This int cast is temporary to achieve 1:1 results with osu!stable, and should be removed in the future\n GreatHitWindow = (int)Math.Ceiling(getHitWindow300(mods) \/ clockRate),\n ScoreMultiplier = getScoreMultiplier(beatmap, mods),\n MaxCombo = beatmap.HitObjects.Sum(h => h is HoldNote ? 2 : 1),\n Skills = skills\n };\n }","smell":"long method","id":91} {"lang_cluster":"C#","source_code":"\ufeff#region License Information (GPL v3)\n\n\/*\n ShareX - A program that allows you to take screenshots and share any file type\n Copyright (c) 2007-2020 ShareX Team\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n Optionally you can also view the license at .\n*\/\n\n#endregion License Information (GPL v3)\n\nusing System;\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ShareX.HelpersLib\n{\n public static class TranslatorHelper\n {\n #region Text to ...\n\n public static string[] TextToBinary(string text)\n {\n string[] result = new string[text.Length];\n\n for (int i = 0; i < text.Length; i++)\n {\n result[i] = ByteToBinary((byte)text[i]);\n }\n\n return result;\n }\n\n public static string[] TextToHexadecimal(string text)\n {\n return BytesToHexadecimal(Encoding.UTF8.GetBytes(text));\n }\n\n public static byte[] TextToASCII(string text)\n {\n return Encoding.ASCII.GetBytes(text);\n }\n\n public static string TextToBase64(string text)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(text);\n return Convert.ToBase64String(bytes);\n }\n\n public static string TextToHash(string text, HashType hashType, bool uppercase = false)\n {\n using (HashAlgorithm hash = HashCheck.GetHashAlgorithm(hashType))\n {\n byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text));\n string[] hex = BytesToHexadecimal(bytes);\n string result = string.Concat(hex);\n if (uppercase) result = result.ToUpperInvariant();\n return result;\n }\n }\n\n #endregion Text to ...\n\n #region Binary to ...\n\n public static byte BinaryToByte(string binary)\n {\n return Convert.ToByte(binary, 2);\n }\n\n public static string BinaryToText(string binary)\n {\n binary = Regex.Replace(binary, @\"[^01]\", \"\");\n\n using (MemoryStream stream = new MemoryStream())\n {\n for (int i = 0; i + 8 <= binary.Length; i += 8)\n {\n stream.WriteByte(BinaryToByte(binary.Substring(i, 8)));\n }\n\n return Encoding.UTF8.GetString(stream.ToArray());\n }\n }\n\n #endregion Binary to ...\n\n #region Byte to ...\n\n public static string ByteToBinary(byte b)\n {\n char[] result = new char[8];\n int pos = 7;\n\n for (int i = 0; i < 8; i++)\n {\n if ((b & (1 << i)) != 0)\n {\n result[pos] = '1';\n }\n else\n {\n result[pos] = '0';\n }\n\n pos--;\n }\n\n return new string(result);\n }\n\n public static string[] BytesToHexadecimal(byte[] bytes)\n {\n string[] result = new string[bytes.Length];\n\n for (int i = 0; i < bytes.Length; i++)\n {\n result[i] = bytes[i].ToString(\"x2\");\n }\n\n return result;\n }\n\n #endregion Byte to ...\n\n #region Hexadecimal to ...\n\n public static byte HexadecimalToByte(string hex)\n {\n return Convert.ToByte(hex, 16);\n }\n\n public static string HexadecimalToText(string hex)\n {\n hex = Regex.Replace(hex, @\"[^0-9a-fA-F]\", \"\");\n\n using (MemoryStream stream = new MemoryStream())\n {\n for (int i = 0; i + 2 <= hex.Length; i += 2)\n {\n stream.WriteByte(HexadecimalToByte(hex.Substring(i, 2)));\n }\n\n return Encoding.UTF8.GetString(stream.ToArray());\n }\n }\n\n #endregion Hexadecimal to ...\n\n #region Base64 to ...\n\n public static string Base64ToText(string base64)\n {\n byte[] bytes = Convert.FromBase64String(base64);\n return Encoding.UTF8.GetString(bytes);\n }\n\n #endregion Base64 to ...\n\n #region ASCII to ...\n\n public static string ASCIIToText(string ascii)\n {\n string[] numbers = Regex.Split(ascii, @\"\\D+\");\n\n using (MemoryStream stream = new MemoryStream())\n {\n foreach (string number in numbers)\n {\n byte b;\n if (byte.TryParse(number, out b))\n {\n stream.WriteByte(b);\n }\n }\n\n return Encoding.ASCII.GetString(stream.ToArray());\n }\n }\n\n #endregion ASCII to ...\n }\n}","smell_code":" public static string ASCIIToText(string ascii)\n {\n string[] numbers = Regex.Split(ascii, @\"\\D+\");\n\n using (MemoryStream stream = new MemoryStream())\n {\n foreach (string number in numbers)\n {\n byte b;\n if (byte.TryParse(number, out b))\n {\n stream.WriteByte(b);\n }\n }\n\n return Encoding.ASCII.GetString(stream.ToArray());\n }\n }","smell":"long method","id":92} {"lang_cluster":"C#","source_code":"\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing osu.Framework.Allocation;\nusing osu.Framework.Extensions.Color4Extensions;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Effects;\nusing osu.Framework.Graphics.Shapes;\nusing osu.Game.Graphics;\nusing osuTK.Graphics;\n\nnamespace osu.Game.Rulesets.Taiko.UI\n{\n public class PlayfieldBackgroundRight : CompositeDrawable\n {\n [BackgroundDependencyLoader]\n private void load(OsuColour colours)\n {\n Name = \"Transparent playfield background\";\n RelativeSizeAxes = Axes.Both;\n Masking = true;\n BorderColour = colours.Gray1;\n\n EdgeEffect = new EdgeEffectParameters\n {\n Type = EdgeEffectType.Shadow,\n Colour = Color4.Black.Opacity(0.2f),\n Radius = 5,\n };\n\n InternalChildren = new Drawable[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Colour = colours.Gray0,\n Alpha = 0.6f\n },\n new Container\n {\n Name = \"Border\",\n RelativeSizeAxes = Axes.Both,\n Masking = true,\n MaskingSmoothness = 0,\n BorderThickness = 2,\n AlwaysPresent = true,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n }\n };\n }\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load(OsuColour colours)\n {\n Name = \"Transparent playfield background\";\n RelativeSizeAxes = Axes.Both;\n Masking = true;\n BorderColour = colours.Gray1;\n\n EdgeEffect = new EdgeEffectParameters\n {\n Type = EdgeEffectType.Shadow,\n Colour = Color4.Black.Opacity(0.2f),\n Radius = 5,\n };\n\n InternalChildren = new Drawable[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Colour = colours.Gray0,\n Alpha = 0.6f\n },\n new Container\n {\n Name = \"Border\",\n RelativeSizeAxes = Axes.Both,\n Masking = true,\n MaskingSmoothness = 0,\n BorderThickness = 2,\n AlwaysPresent = true,\n Children = new[]\n {\n new Box\n {\n RelativeSizeAxes = Axes.Both,\n Alpha = 0,\n AlwaysPresent = true\n }\n }\n }\n };\n }","smell":"long method","id":93} {"lang_cluster":"C#","source_code":"using System;\nusing System.Diagnostics;\nusing System.IO;\nusing Desktop.integration.crash;\nusing Lens.assets;\nusing Microsoft.Xna.Framework.Audio;\n\nnamespace Desktop {\n\tpublic class Program {\n\t\tprivate static void TryToRemove(string file) {\n\t\t\tif (File.Exists(file)) {\n\t\t\t\ttry {\n\t\t\t\t\tFile.Delete(file);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tConsole.WriteLine(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t[STAThread]\n\t\tpublic static void Main() {\n\t\t\tCrashReporter.Bind();\n\n\t\t\tif (!Environment.Is64BitOperatingSystem) {\n\t\t\t\tConsole.ForegroundColor = ConsoleColor.Red;\n\t\t\t\tConsole.WriteLine(\"Burning Knight can't run on 32 bit OS, sorry :(\");\n\t\t\t\tConsole.ForegroundColor = ConsoleColor.White;\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar current = Process.GetCurrentProcess();\n\t\t\tvar processes = Process.GetProcessesByName(current.ProcessName);\n\n\t\t\tConsole.WriteLine($\"Found a total of {processes.Length} processes with name {current.ProcessName}\");\n\n\t\t\tforeach (var process in processes) {\n\t\t\t\tif (process.Id != current.Id) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tprocess.CloseMainWindow();\n\t\t\t\t\t\tprocess.Kill();\n\t\t\t\t\t\tConsole.WriteLine(\"Killing older process\");\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tConsole.WriteLine($\"Failed: {e}\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tTryToRemove(\"burning_log.txt\");\n\t\t\tTryToRemove(\"crashes.txt\");\n\n\t\t\ttry {\n\t\t\t\tSoundEffect.Initialize();\n\t\t\t\tConsole.WriteLine(\"SoundEffect.Initialize() went ok\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tAssets.FailedToLoadAudio = true;\n\t\t\t\tAssets.LoadSfx = false;\n\t\t\t\tAssets.LoadMusic = false;\n\t\t\t\t\n\t\t\t\tConsole.WriteLine($\"Failed: {e}\");\n\t\t\t}\n\n\t\t\t\n\t\t\ttry {\n\t\t\t\tusing (var game = new DesktopApp()) {\n\t\t\t\t\tgame.Run();\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tCrashReporter.Report(e);\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\t\t[STAThread]\n\t\tpublic static void Main() {\n\t\t\tCrashReporter.Bind();\n\n\t\t\tif (!Environment.Is64BitOperatingSystem) {\n\t\t\t\tConsole.ForegroundColor = ConsoleColor.Red;\n\t\t\t\tConsole.WriteLine(\"Burning Knight can't run on 32 bit OS, sorry :(\");\n\t\t\t\tConsole.ForegroundColor = ConsoleColor.White;\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar current = Process.GetCurrentProcess();\n\t\t\tvar processes = Process.GetProcessesByName(current.ProcessName);\n\n\t\t\tConsole.WriteLine($\"Found a total of {processes.Length} processes with name {current.ProcessName}\");\n\n\t\t\tforeach (var process in processes) {\n\t\t\t\tif (process.Id != current.Id) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tprocess.CloseMainWindow();\n\t\t\t\t\t\tprocess.Kill();\n\t\t\t\t\t\tConsole.WriteLine(\"Killing older process\");\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tConsole.WriteLine($\"Failed: {e}\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tTryToRemove(\"burning_log.txt\");\n\t\t\tTryToRemove(\"crashes.txt\");\n\n\t\t\ttry {\n\t\t\t\tSoundEffect.Initialize();\n\t\t\t\tConsole.WriteLine(\"SoundEffect.Initialize() went ok\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tAssets.FailedToLoadAudio = true;\n\t\t\t\tAssets.LoadSfx = false;\n\t\t\t\tAssets.LoadMusic = false;\n\t\t\t\t\n\t\t\t\tConsole.WriteLine($\"Failed: {e}\");\n\t\t\t}\n\n\t\t\t\n\t\t\ttry {\n\t\t\t\tusing (var game = new DesktopApp()) {\n\t\t\t\t\tgame.Run();\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\tCrashReporter.Report(e);\n\t\t\t}\n\t\t}","smell":"long method","id":94} {"lang_cluster":"C#","source_code":"\ufeffusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Jellyfin.Data.Entities;\nusing Jellyfin.Data.Enums;\nusing MediaBrowser.Common.Extensions;\nusing MediaBrowser.Controller.Dto;\nusing MediaBrowser.Controller.Entities;\nusing MediaBrowser.Controller.Net;\nusing MediaBrowser.Controller.Session;\nusing MediaBrowser.Model.Dto;\nusing MediaBrowser.Model.Querying;\nusing Microsoft.AspNetCore.Http;\n\nnamespace Jellyfin.Api.Helpers\n{\n \/\/\/ \n \/\/\/ Request Extensions.\n \/\/\/ <\/summary>\n public static class RequestHelpers\n {\n \/\/\/ \n \/\/\/ Get Order By.\n \/\/\/ <\/summary>\n \/\/\/ Sort By. Comma delimited string.<\/param>\n \/\/\/ Sort Order. Comma delimited string.<\/param>\n \/\/\/ Order By.<\/returns>\n public static (string, SortOrder)[] GetOrderBy(IReadOnlyList sortBy, IReadOnlyList requestedSortOrder)\n {\n if (sortBy.Count == 0)\n {\n return Array.Empty>();\n }\n\n var result = new (string, SortOrder)[sortBy.Count];\n var i = 0;\n \/\/ Add elements which have a SortOrder specified\n for (; i < requestedSortOrder.Count; i++)\n {\n result[i] = (sortBy[i], requestedSortOrder[i]);\n }\n\n \/\/ Add remaining elements with the first specified SortOrder\n \/\/ or the default one if no SortOrders are specified\n var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending;\n for (; i < sortBy.Count; i++)\n {\n result[i] = (sortBy[i], order);\n }\n\n return result;\n }\n\n \/\/\/ \n \/\/\/ Checks if the user can update an entry.\n \/\/\/ <\/summary>\n \/\/\/ Instance of the interface.<\/param>\n \/\/\/ The .<\/param>\n \/\/\/ The user id.<\/param>\n \/\/\/ Whether to restrict the user preferences.<\/param>\n \/\/\/ A whether the user can update the entry.<\/returns>\n internal static bool AssertCanUpdateUser(IAuthorizationContext authContext, HttpRequest requestContext, Guid userId, bool restrictUserPreferences)\n {\n var auth = authContext.GetAuthorizationInfo(requestContext);\n\n var authenticatedUser = auth.User;\n\n \/\/ If they're going to update the record of another user, they must be an administrator\n if ((!userId.Equals(auth.UserId) && !authenticatedUser.HasPermission(PermissionKind.IsAdministrator))\n || (restrictUserPreferences && !authenticatedUser.EnableUserPreferenceAccess))\n {\n return false;\n }\n\n return true;\n }\n\n internal static SessionInfo GetSession(ISessionManager sessionManager, IAuthorizationContext authContext, HttpRequest request)\n {\n var authorization = authContext.GetAuthorizationInfo(request);\n var user = authorization.User;\n var session = sessionManager.LogSessionActivity(\n authorization.Client,\n authorization.Version,\n authorization.DeviceId,\n authorization.Device,\n request.HttpContext.GetNormalizedRemoteIp(),\n user);\n\n if (session == null)\n {\n throw new ArgumentException(\"Session not found.\");\n }\n\n return session;\n }\n\n internal static QueryResult CreateQueryResult(\n QueryResult<(BaseItem, ItemCounts)> result,\n DtoOptions dtoOptions,\n IDtoService dtoService,\n bool includeItemTypes,\n User? user)\n {\n var dtos = result.Items.Select(i =>\n {\n var (baseItem, counts) = i;\n var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);\n\n if (includeItemTypes)\n {\n dto.ChildCount = counts.ItemCount;\n dto.ProgramCount = counts.ProgramCount;\n dto.SeriesCount = counts.SeriesCount;\n dto.EpisodeCount = counts.EpisodeCount;\n dto.MovieCount = counts.MovieCount;\n dto.TrailerCount = counts.TrailerCount;\n dto.AlbumCount = counts.AlbumCount;\n dto.SongCount = counts.SongCount;\n dto.ArtistCount = counts.ArtistCount;\n }\n\n return dto;\n });\n\n return new QueryResult\n {\n Items = dtos.ToArray(),\n TotalRecordCount = result.TotalRecordCount\n };\n }\n }\n}","smell_code":" internal static bool AssertCanUpdateUser(IAuthorizationContext authContext, HttpRequest requestContext, Guid userId, bool restrictUserPreferences)\n {\n var auth = authContext.GetAuthorizationInfo(requestContext);\n\n var authenticatedUser = auth.User;\n\n \/\/ If they're going to update the record of another user, they must be an administrator\n if ((!userId.Equals(auth.UserId) && !authenticatedUser.HasPermission(PermissionKind.IsAdministrator))\n || (restrictUserPreferences && !authenticatedUser.EnableUserPreferenceAccess))\n {\n return false;\n }\n\n return true;\n }","smell":"long method","id":95} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Game.Overlays.Settings.Sections.Gameplay;\nusing osu.Game.Rulesets;\nusing System.Linq;\nusing osu.Framework.Graphics.Sprites;\nusing osu.Framework.Logging;\n\nnamespace osu.Game.Overlays.Settings.Sections\n{\n public class GameplaySection : SettingsSection\n {\n public override string Header => \"Gameplay\";\n\n public override Drawable CreateIcon() => new SpriteIcon\n {\n Icon = FontAwesome.Regular.Circle\n };\n\n public GameplaySection()\n {\n Children = new Drawable[]\n {\n new GeneralSettings(),\n new ModsSettings(),\n };\n }\n\n [BackgroundDependencyLoader]\n private void load(RulesetStore rulesets)\n {\n foreach (Ruleset ruleset in rulesets.AvailableRulesets.Select(info => info.CreateInstance()))\n {\n try\n {\n SettingsSubsection section = ruleset.CreateSettings();\n\n if (section != null)\n Add(section);\n }\n catch (Exception e)\n {\n Logger.Error(e, \"Failed to load ruleset settings\");\n }\n }\n }\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load(RulesetStore rulesets)\n {\n foreach (Ruleset ruleset in rulesets.AvailableRulesets.Select(info => info.CreateInstance()))\n {\n try\n {\n SettingsSubsection section = ruleset.CreateSettings();\n\n if (section != null)\n Add(section);\n }\n catch (Exception e)\n {\n Logger.Error(e, \"Failed to load ruleset settings\");\n }\n }\n }","smell":"long method","id":96} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System;\nusing osuTK;\nusing osuTK.Graphics;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Framework.Graphics.Shapes;\n\nnamespace osu.Game.Graphics.UserInterface\n{\n public class Bar : Container, IHasAccentColour\n {\n private readonly Box background;\n private readonly Box bar;\n\n private const int resize_duration = 250;\n\n private const Easing easing = Easing.InOutCubic;\n\n private float length;\n\n \/\/\/ \n \/\/\/ Length of the bar, ranges from 0 to 1\n \/\/\/ <\/summary>\n public float Length\n {\n get => length;\n set\n {\n length = Math.Clamp(value, 0, 1);\n updateBarLength();\n }\n }\n\n public Color4 BackgroundColour\n {\n get => background.Colour;\n set => background.Colour = value;\n }\n\n public Color4 AccentColour\n {\n get => bar.Colour;\n set => bar.Colour = value;\n }\n\n private BarDirection direction = BarDirection.LeftToRight;\n\n public BarDirection Direction\n {\n get => direction;\n set\n {\n direction = value;\n updateBarLength();\n }\n }\n\n public Bar()\n {\n Children = new[]\n {\n background = new Box\n {\n RelativeSizeAxes = Axes.Both,\n Colour = new Color4(0, 0, 0, 0)\n },\n bar = new Box\n {\n RelativeSizeAxes = Axes.Both,\n Width = 0,\n },\n };\n }\n\n private void updateBarLength()\n {\n switch (direction)\n {\n case BarDirection.LeftToRight:\n case BarDirection.RightToLeft:\n bar.ResizeTo(new Vector2(length, 1), resize_duration, easing);\n break;\n\n case BarDirection.TopToBottom:\n case BarDirection.BottomToTop:\n bar.ResizeTo(new Vector2(1, length), resize_duration, easing);\n break;\n }\n\n switch (direction)\n {\n case BarDirection.LeftToRight:\n case BarDirection.TopToBottom:\n bar.Anchor = Anchor.TopLeft;\n bar.Origin = Anchor.TopLeft;\n break;\n\n case BarDirection.RightToLeft:\n case BarDirection.BottomToTop:\n bar.Anchor = Anchor.BottomRight;\n bar.Origin = Anchor.BottomRight;\n break;\n }\n }\n }\n\n [Flags]\n public enum BarDirection\n {\n LeftToRight = 1,\n RightToLeft = 1 << 1,\n TopToBottom = 1 << 2,\n BottomToTop = 1 << 3,\n\n Vertical = TopToBottom | BottomToTop,\n Horizontal = LeftToRight | RightToLeft,\n }\n}","smell_code":" public Bar()\n {\n Children = new[]\n {\n background = new Box\n {\n RelativeSizeAxes = Axes.Both,\n Colour = new Color4(0, 0, 0, 0)\n },\n bar = new Box\n {\n RelativeSizeAxes = Axes.Both,\n Width = 0,\n },\n };\n }","smell":"long method","id":97} {"lang_cluster":"C#","source_code":"#region Copyright & License Information\n\/*\n * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)\n * This file is part of OpenRA, which is free software. It is made\n * available to you under the terms of the GNU General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version. For more\n * information, see COPYING.\n *\/\n#endregion\n\nusing OpenRA.Traits;\n\nnamespace OpenRA.Mods.Common.Traits\n{\n\t[Desc(\"This actor has a voice.\")]\n\tpublic class VoicedInfo : TraitInfo\n\t{\n\t\t[VoiceSetReference]\n\t\t[FieldLoader.Require]\n\t\t[Desc(\"Which voice set to use.\")]\n\t\tpublic readonly string VoiceSet = null;\n\n\t\t[Desc(\"Multiply volume with this factor.\")]\n\t\tpublic readonly float Volume = 1f;\n\n\t\tpublic override object Create(ActorInitializer init) { return new Voiced(init.Self, this); }\n\t}\n\n\tpublic class Voiced : IVoiced\n\t{\n\t\tpublic readonly VoicedInfo Info;\n\n\t\tpublic Voiced(Actor self, VoicedInfo info)\n\t\t{\n\t\t\tInfo = info;\n\t\t}\n\n\t\tstring IVoiced.VoiceSet { get { return Info.VoiceSet; } }\n\n\t\tbool IVoiced.PlayVoice(Actor self, string phrase, string variant)\n\t\t{\n\t\t\tif (phrase == null)\n\t\t\t\treturn false;\n\n\t\t\tif (string.IsNullOrEmpty(Info.VoiceSet))\n\t\t\t\treturn false;\n\n\t\t\tvar type = Info.VoiceSet.ToLowerInvariant();\n\t\t\tvar volume = Info.Volume;\n\t\t\treturn Game.Sound.PlayPredefined(SoundType.World, self.World.Map.Rules, null, self, type, phrase, variant, true, WPos.Zero, volume, true);\n\t\t}\n\n\t\tbool IVoiced.PlayVoiceLocal(Actor self, string phrase, string variant, float volume)\n\t\t{\n\t\t\tif (phrase == null)\n\t\t\t\treturn false;\n\n\t\t\tif (string.IsNullOrEmpty(Info.VoiceSet))\n\t\t\t\treturn false;\n\n\t\t\tvar type = Info.VoiceSet.ToLowerInvariant();\n\t\t\treturn Game.Sound.PlayPredefined(SoundType.World, self.World.Map.Rules, null, self, type, phrase, variant, false, self.CenterPosition, volume, true);\n\t\t}\n\n\t\tbool IVoiced.HasVoice(Actor self, string voice)\n\t\t{\n\t\t\tif (string.IsNullOrEmpty(Info.VoiceSet))\n\t\t\t\treturn false;\n\n\t\t\tvar voices = self.World.Map.Rules.Voices[Info.VoiceSet.ToLowerInvariant()];\n\t\t\treturn voices != null && voices.Voices.ContainsKey(voice);\n\t\t}\n\t}\n}","smell_code":"\t\tbool IVoiced.PlayVoiceLocal(Actor self, string phrase, string variant, float volume)\n\t\t{\n\t\t\tif (phrase == null)\n\t\t\t\treturn false;\n\n\t\t\tif (string.IsNullOrEmpty(Info.VoiceSet))\n\t\t\t\treturn false;\n\n\t\t\tvar type = Info.VoiceSet.ToLowerInvariant();\n\t\t\treturn Game.Sound.PlayPredefined(SoundType.World, self.World.Map.Rules, null, self, type, phrase, variant, false, self.CenterPosition, volume, true);\n\t\t}","smell":"long method","id":98} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Linq;\nusing System.Threading;\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Graphics.UserInterface;\nusing osu.Game.Online.API;\nusing osu.Game.Online.API.Requests;\nusing osuTK;\n\nnamespace osu.Game.Overlays.News.Displays\n{\n public class FrontPageDisplay : CompositeDrawable\n {\n [Resolved]\n private IAPIProvider api { get; set; }\n\n private FillFlowContainer content;\n private ShowMoreButton showMore;\n\n private GetNewsRequest request;\n private Cursor lastCursor;\n\n [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n AutoSizeAxes = Axes.Y;\n Padding = new MarginPadding\n {\n Vertical = 20,\n Left = 30,\n Right = 50\n };\n\n InternalChild = new FillFlowContainer\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 10),\n Children = new Drawable[]\n {\n content = new FillFlowContainer\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 10)\n },\n showMore = new ShowMoreButton\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Margin = new MarginPadding\n {\n Top = 15\n },\n Action = performFetch,\n Alpha = 0\n }\n }\n };\n\n performFetch();\n }\n\n private void performFetch()\n {\n request?.Cancel();\n\n request = new GetNewsRequest(lastCursor);\n request.Success += response => Schedule(() => onSuccess(response));\n api.PerformAsync(request);\n }\n\n private CancellationTokenSource cancellationToken;\n\n private void onSuccess(GetNewsResponse response)\n {\n cancellationToken?.Cancel();\n\n lastCursor = response.Cursor;\n\n var flow = new FillFlowContainer\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 10),\n Children = response.NewsPosts.Select(p => new NewsCard(p)).ToList()\n };\n\n LoadComponentAsync(flow, loaded =>\n {\n content.Add(loaded);\n showMore.IsLoading = false;\n showMore.Show();\n }, (cancellationToken = new CancellationTokenSource()).Token);\n }\n\n protected override void Dispose(bool isDisposing)\n {\n request?.Cancel();\n cancellationToken?.Cancel();\n base.Dispose(isDisposing);\n }\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load()\n {\n RelativeSizeAxes = Axes.X;\n AutoSizeAxes = Axes.Y;\n Padding = new MarginPadding\n {\n Vertical = 20,\n Left = 30,\n Right = 50\n };\n\n InternalChild = new FillFlowContainer\n {\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 10),\n Children = new Drawable[]\n {\n content = new FillFlowContainer\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n RelativeSizeAxes = Axes.X,\n AutoSizeAxes = Axes.Y,\n Direction = FillDirection.Vertical,\n Spacing = new Vector2(0, 10)\n },\n showMore = new ShowMoreButton\n {\n Anchor = Anchor.TopCentre,\n Origin = Anchor.TopCentre,\n Margin = new MarginPadding\n {\n Top = 15\n },\n Action = performFetch,\n Alpha = 0\n }\n }\n };\n\n performFetch();\n }","smell":"long method","id":99} {"lang_cluster":"C#","source_code":"\ufeff\/\/ Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence.\n\/\/ See the LICENCE file in the repository root for full licence text.\n\nusing System.Diagnostics;\nusing JetBrains.Annotations;\nusing osu.Framework.Allocation;\nusing osu.Framework.Graphics;\nusing osu.Framework.Graphics.Containers;\nusing osu.Game.Rulesets.Objects.Drawables;\nusing osu.Game.Skinning;\nusing osuTK;\n\nnamespace osu.Game.Rulesets.Osu.Objects.Drawables\n{\n public class DrawableSliderTail : DrawableOsuHitObject, IRequireTracking, ITrackSnaking\n {\n public new SliderTailCircle HitObject => (SliderTailCircle)base.HitObject;\n\n [CanBeNull]\n public Slider Slider => DrawableSlider?.HitObject;\n\n protected DrawableSlider DrawableSlider => (DrawableSlider)ParentHitObject;\n\n \/\/\/ \n \/\/\/ The judgement text is provided by the .\n \/\/\/ <\/summary>\n public override bool DisplayResult => false;\n\n public bool Tracking { get; set; }\n\n private SkinnableDrawable circlePiece;\n private Container scaleContainer;\n\n public DrawableSliderTail()\n : base(null)\n {\n }\n\n public DrawableSliderTail(SliderTailCircle tailCircle)\n : base(tailCircle)\n {\n }\n\n [BackgroundDependencyLoader]\n private void load()\n {\n Origin = Anchor.Centre;\n Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);\n\n InternalChildren = new Drawable[]\n {\n scaleContainer = new Container\n {\n RelativeSizeAxes = Axes.Both,\n Origin = Anchor.Centre,\n Anchor = Anchor.Centre,\n Children = new Drawable[]\n {\n \/\/ no default for this; only visible in legacy skins.\n circlePiece = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SliderTailHitCircle), _ => Empty())\n }\n },\n };\n\n ScaleBindable.BindValueChanged(scale => scaleContainer.Scale = new Vector2(scale.NewValue));\n }\n\n protected override void UpdateInitialTransforms()\n {\n base.UpdateInitialTransforms();\n\n circlePiece.FadeInFromZero(HitObject.TimeFadeIn);\n }\n\n protected override void UpdateHitStateTransforms(ArmedState state)\n {\n base.UpdateHitStateTransforms(state);\n\n Debug.Assert(HitObject.HitWindows != null);\n\n switch (state)\n {\n case ArmedState.Idle:\n this.Delay(HitObject.TimePreempt).FadeOut(500);\n break;\n\n case ArmedState.Miss:\n this.FadeOut(100);\n break;\n\n case ArmedState.Hit:\n \/\/ todo: temporary \/ arbitrary\n this.Delay(800).FadeOut();\n break;\n }\n }\n\n protected override void CheckForResult(bool userTriggered, double timeOffset)\n {\n if (!userTriggered && timeOffset >= 0)\n ApplyResult(r => r.Type = Tracking ? r.Judgement.MaxResult : r.Judgement.MinResult);\n }\n\n public void UpdateSnakingPosition(Vector2 start, Vector2 end) =>\n Position = HitObject.RepeatIndex % 2 == 0 ? end : start;\n }\n}","smell_code":" [BackgroundDependencyLoader]\n private void load()\n {\n Origin = Anchor.Centre;\n Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);\n\n InternalChildren = new Drawable[]\n {\n scaleContainer = new Container\n {\n RelativeSizeAxes = Axes.Both,\n Origin = Anchor.Centre,\n Anchor = Anchor.Centre,\n Children = new Drawable[]\n {\n \/\/ no default for this; only visible in legacy skins.\n circlePiece = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SliderTailHitCircle), _ => Empty())\n }\n },\n };\n\n ScaleBindable.BindValueChanged(scale => scaleContainer.Scale = new Vector2(scale.NewValue));\n }","smell":"long method","id":100} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage org.apache.cxf.maven_plugin.common;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\n\nimport org.apache.cxf.tools.common.ToolContext;\nimport org.apache.cxf.tools.wadlto.WADLToJava;\n\n\/\/TODO: Move to the common plugin module\npublic final class ForkOnceCodeGenerator {\n private ForkOnceCodeGenerator() {\n \/\/utility\n }\n public static void main(String[] args) throws Exception {\n File file = new File(args[0]);\n BufferedReader reader = new BufferedReader(new FileReader(file));\n String line = reader.readLine();\n while (line != null) {\n int i = Integer.parseInt(line);\n if (i == -1) {\n reader.close();\n return;\n }\n String[] wargs = new String[i];\n for (int x = 0; x < i; x++) {\n wargs[x] = reader.readLine();\n }\n\n new WADLToJava(wargs).run(new ToolContext());\n\n line = reader.readLine();\n }\n reader.close();\n }\n}","smell_code":"public final class ForkOnceCodeGenerator {\n private ForkOnceCodeGenerator() {\n \/\/utility\n }\n public static void main(String[] args) throws Exception {\n File file = new File(args[0]);\n BufferedReader reader = new BufferedReader(new FileReader(file));\n String line = reader.readLine();\n while (line != null) {\n int i = Integer.parseInt(line);\n if (i == -1) {\n reader.close();\n return;\n }\n String[] wargs = new String[i];\n for (int x = 0; x < i; x++) {\n wargs[x] = reader.readLine();\n }\n\n new WADLToJava(wargs).run(new ToolContext());\n\n line = reader.readLine();\n }\n reader.close();\n }\n}","smell":"data class","id":101} {"lang_cluster":"Java","source_code":"\/*\nCopyright 2011-2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Tag.Component.Help;\n\n\n\nimport java.net.URL;\n\nimport com.google.security.zynamics.binnavi.Help.CHelpFunctions;\nimport com.google.security.zynamics.binnavi.Help.IHelpInformation;\n\n\n\/**\n * Context-sensitive help information for fields that show tag names.\n *\/\npublic final class CNameHelp implements IHelpInformation {\n @Override\n public String getText() {\n return \"In this field you can edit the name of the tag.\";\n }\n\n @Override\n public URL getUrl() {\n return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE);\n }\n}","smell_code":"public final class CNameHelp implements IHelpInformation {\n @Override\n public String getText() {\n return \"In this field you can edit the name of the tag.\";\n }\n\n @Override\n public URL getUrl() {\n return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE);\n }\n}","smell":"data class","id":102} {"lang_cluster":"Java","source_code":"\/*****************************************************************\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n ****************************************************************\/\npackage org.apache.cayenne.di;\n\n\/**\n * A runtime exception thrown on DI misconfiguration.\n * \n * @since 4.0\n *\/\npublic class DIRuntimeException extends RuntimeException {\n \n\tprivate static final long serialVersionUID = 396131653561690312L;\n\n\t\/**\n * Creates new ConfigurationException<\/code> without detail message.\n *\/\n public DIRuntimeException() {\n }\n\n \/**\n * Constructs an exception with the specified message with an optional list\n * of message formatting arguments. Message formatting rules follow\n * \"String.format(..)\" conventions.\n *\/\n public DIRuntimeException(String messageFormat, Object... messageArgs) {\n super(String.format(messageFormat, messageArgs));\n }\n\n \/**\n * Constructs an exception wrapping another exception thrown elsewhere.\n *\/\n public DIRuntimeException(Throwable cause) {\n super(cause);\n }\n\n public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) {\n super(String.format(messageFormat, messageArgs), cause);\n }\n}","smell_code":"public class DIRuntimeException extends RuntimeException {\n \n\tprivate static final long serialVersionUID = 396131653561690312L;\n\n\t\/**\n * Creates new ConfigurationException<\/code> without detail message.\n *\/\n public DIRuntimeException() {\n }\n\n \/**\n * Constructs an exception with the specified message with an optional list\n * of message formatting arguments. Message formatting rules follow\n * \"String.format(..)\" conventions.\n *\/\n public DIRuntimeException(String messageFormat, Object... messageArgs) {\n super(String.format(messageFormat, messageArgs));\n }\n\n \/**\n * Constructs an exception wrapping another exception thrown elsewhere.\n *\/\n public DIRuntimeException(Throwable cause) {\n super(cause);\n }\n\n public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) {\n super(String.format(messageFormat, messageArgs), cause);\n }\n}","smell":"data class","id":103} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.ignite.internal.visor.node;\n\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectOutput;\nimport org.apache.ignite.configuration.IgniteConfiguration;\nimport org.apache.ignite.internal.util.typedef.internal.S;\nimport org.apache.ignite.internal.util.typedef.internal.U;\nimport org.apache.ignite.internal.visor.VisorDataTransferObject;\nimport org.jetbrains.annotations.Nullable;\n\nimport static org.apache.ignite.internal.visor.util.VisorTaskUtils.compactArray;\n\n\/**\n * Data transfer object for node lifecycle configuration properties.\n *\/\npublic class VisorLifecycleConfiguration extends VisorDataTransferObject{\n \/** *\/\n private static final long serialVersionUID = 0L;\n\n \/** Lifecycle beans. *\/\n private String beans;\n\n \/**\n * Default constructor.\n *\/\n public VisorLifecycleConfiguration() {\n \/\/ No-op.\n }\n\n \/**\n * Create data transfer object for node lifecycle configuration properties.\n *\n * @param c Grid configuration.\n *\/\n public VisorLifecycleConfiguration(IgniteConfiguration c) {\n beans = compactArray(c.getLifecycleBeans());\n }\n\n \/**\n * @return Lifecycle beans.\n *\/\n @Nullable public String getBeans() {\n return beans;\n }\n\n \/** {@inheritDoc} *\/\n @Override protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, beans);\n }\n\n \/** {@inheritDoc} *\/\n @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n beans = U.readString(in);\n }\n\n \/** {@inheritDoc} *\/\n @Override public String toString() {\n return S.toString(VisorLifecycleConfiguration.class, this);\n }\n}","smell_code":"public class VisorLifecycleConfiguration extends VisorDataTransferObject{\n \/** *\/\n private static final long serialVersionUID = 0L;\n\n \/** Lifecycle beans. *\/\n private String beans;\n\n \/**\n * Default constructor.\n *\/\n public VisorLifecycleConfiguration() {\n \/\/ No-op.\n }\n\n \/**\n * Create data transfer object for node lifecycle configuration properties.\n *\n * @param c Grid configuration.\n *\/\n public VisorLifecycleConfiguration(IgniteConfiguration c) {\n beans = compactArray(c.getLifecycleBeans());\n }\n\n \/**\n * @return Lifecycle beans.\n *\/\n @Nullable public String getBeans() {\n return beans;\n }\n\n \/** {@inheritDoc} *\/\n @Override protected void writeExternalData(ObjectOutput out) throws IOException {\n U.writeString(out, beans);\n }\n\n \/** {@inheritDoc} *\/\n @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {\n beans = U.readString(in);\n }\n\n \/** {@inheritDoc} *\/\n @Override public String toString() {\n return S.toString(VisorLifecycleConfiguration.class, this);\n }\n}","smell":"data class","id":104} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2010, 2013, Oracle and\/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n *\/\npackage java.util.function;\n\nimport java.util.Objects;\n\n\/**\n * Represents a function that accepts one argument and produces a result.\n *\n *

This is a functional interface<\/a>\n * whose functional method is {@link #apply(Object)}.\n *\n * @param the type of the input to the function\n * @param the type of the result of the function\n *\n * @since 1.8\n *\/\n@FunctionalInterface\npublic interface Function {\n\n \/**\n * Applies this function to the given argument.\n *\n * @param t the function argument\n * @return the function result\n *\/\n R apply(T t);\n\n \/**\n * Returns a composed function that first applies the {@code before}\n * function to its input, and then applies this function to the result.\n * If evaluation of either function throws an exception, it is relayed to\n * the caller of the composed function.\n *\n * @param the type of input to the {@code before} function, and to the\n * composed function\n * @param before the function to apply before this function is applied\n * @return a composed function that first applies the {@code before}\n * function and then applies this function\n * @throws NullPointerException if before is null\n *\n * @see #andThen(Function)\n *\/\n default Function compose(Function before) {\n Objects.requireNonNull(before);\n return (V v) -> apply(before.apply(v));\n }\n\n \/**\n * Returns a composed function that first applies this function to\n * its input, and then applies the {@code after} function to the result.\n * If evaluation of either function throws an exception, it is relayed to\n * the caller of the composed function.\n *\n * @param the type of output of the {@code after} function, and of the\n * composed function\n * @param after the function to apply after this function is applied\n * @return a composed function that first applies this function and then\n * applies the {@code after} function\n * @throws NullPointerException if after is null\n *\n * @see #compose(Function)\n *\/\n default Function andThen(Function after) {\n Objects.requireNonNull(after);\n return (T t) -> after.apply(apply(t));\n }\n\n \/**\n * Returns a function that always returns its input argument.\n *\n * @param the type of the input and output objects to the function\n * @return a function that always returns its input argument\n *\/\n static Function identity() {\n return t -> t;\n }\n}","smell_code":"@FunctionalInterface\npublic interface Function {\n\n \/**\n * Applies this function to the given argument.\n *\n * @param t the function argument\n * @return the function result\n *\/\n R apply(T t);\n\n \/**\n * Returns a composed function that first applies the {@code before}\n * function to its input, and then applies this function to the result.\n * If evaluation of either function throws an exception, it is relayed to\n * the caller of the composed function.\n *\n * @param the type of input to the {@code before} function, and to the\n * composed function\n * @param before the function to apply before this function is applied\n * @return a composed function that first applies the {@code before}\n * function and then applies this function\n * @throws NullPointerException if before is null\n *\n * @see #andThen(Function)\n *\/\n default Function compose(Function before) {\n Objects.requireNonNull(before);\n return (V v) -> apply(before.apply(v));\n }\n\n \/**\n * Returns a composed function that first applies this function to\n * its input, and then applies the {@code after} function to the result.\n * If evaluation of either function throws an exception, it is relayed to\n * the caller of the composed function.\n *\n * @param the type of output of the {@code after} function, and of the\n * composed function\n * @param after the function to apply after this function is applied\n * @return a composed function that first applies this function and then\n * applies the {@code after} function\n * @throws NullPointerException if after is null\n *\n * @see #compose(Function)\n *\/\n default Function andThen(Function after) {\n Objects.requireNonNull(after);\n return (T t) -> after.apply(apply(t));\n }\n\n \/**\n * Returns a function that always returns its input argument.\n *\n * @param the type of the input and output objects to the function\n * @return a function that always returns its input argument\n *\/\n static Function identity() {\n return t -> t;\n }\n}","smell":"data class","id":105} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2016 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.springframework.statemachine.data;\n\n\/**\n * Generic base class representing guard entity.\n *\n * @author Janne Valkealahti\n *\n *\/\npublic abstract class RepositoryGuard extends BaseRepositoryEntity {\n\n\t\/**\n\t * Gets the name.\n\t *\n\t * @return the name\n\t *\/\n\tpublic abstract String getName();\n\n\t\/**\n\t * Gets the spel.\n\t *\n\t * @return the spel\n\t *\/\n\tpublic abstract String getSpel();\n}","smell_code":"public abstract class RepositoryGuard extends BaseRepositoryEntity {\n\n\t\/**\n\t * Gets the name.\n\t *\n\t * @return the name\n\t *\/\n\tpublic abstract String getName();\n\n\t\/**\n\t * Gets the spel.\n\t *\n\t * @return the spel\n\t *\/\n\tpublic abstract String getSpel();\n}","smell":"data class","id":106} {"lang_cluster":"Java","source_code":"\/********************************************************************************\n * Copyright (c) 2011-2017 Red Hat Inc. and\/or its affiliates and others\n *\n * This program and the accompanying materials are made available under the \n * terms of the Apache License, Version 2.0 which is available at\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * SPDX-License-Identifier: Apache-2.0 \n ********************************************************************************\/\npackage org.eclipse.ceylon.tools.new_;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.eclipse.ceylon.common.FileUtil;\nimport org.eclipse.ceylon.common.tool.Tool;\nimport org.eclipse.ceylon.common.tools.CeylonTool;\n\npublic abstract class NewSubTool implements Tool {\n\n private File directory;\n \n public void setDirectory(File directory) {\n this.directory = directory;\n }\n \n public File getDirectory() {\n return this.directory;\n }\n \n void mkBaseDir(File cwd) throws IOException {\n if (directory != null) {\n File actualDir = FileUtil.applyCwd(cwd, directory);\n if (actualDir.exists() && !actualDir.isDirectory()) {\n throw new IOException(Messages.msg(\"path.exists.and.not.dir\", directory));\n } else if (!actualDir.exists()) {\n if (!FileUtil.mkdirs(actualDir)) {\n throw new IOException(Messages.msg(\"could.not.mkdir\", directory));\n }\n }\n }\n }\n \n public abstract List getVariables();\n \n public abstract List getResources(Environment env);\n \n @Override\n public void initialize(CeylonTool mainTool) {\n }\n \n @Override\n public final void run() throws Exception {\n \/\/ Projects are never run as tools\n throw new RuntimeException();\n }\n \n}","smell_code":"public abstract class NewSubTool implements Tool {\n\n private File directory;\n \n public void setDirectory(File directory) {\n this.directory = directory;\n }\n \n public File getDirectory() {\n return this.directory;\n }\n \n void mkBaseDir(File cwd) throws IOException {\n if (directory != null) {\n File actualDir = FileUtil.applyCwd(cwd, directory);\n if (actualDir.exists() && !actualDir.isDirectory()) {\n throw new IOException(Messages.msg(\"path.exists.and.not.dir\", directory));\n } else if (!actualDir.exists()) {\n if (!FileUtil.mkdirs(actualDir)) {\n throw new IOException(Messages.msg(\"could.not.mkdir\", directory));\n }\n }\n }\n }\n \n public abstract List getVariables();\n \n public abstract List getResources(Environment env);\n \n @Override\n public void initialize(CeylonTool mainTool) {\n }\n \n @Override\n public final void run() throws Exception {\n \/\/ Projects are never run as tools\n throw new RuntimeException();\n }\n \n}","smell":"data class","id":107} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *******************************************************************************\/\npackage org.apache.ofbiz.widget.renderer;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.apache.ofbiz.widget.model.ModelTree;\n\n\/**\n * Widget Library - Tree String Renderer interface\n *\/\npublic interface TreeStringRenderer {\n\n public void renderNodeBegin(Appendable writer, Map context, ModelTree.ModelNode node, int depth) throws IOException;\n public void renderNodeEnd(Appendable writer, Map context, ModelTree.ModelNode node) throws IOException;\n public void renderLabel(Appendable writer, Map context, ModelTree.ModelNode.Label label) throws IOException;\n public void renderLink(Appendable writer, Map context, ModelTree.ModelNode.Link link) throws IOException;\n public void renderImage(Appendable writer, Map context, ModelTree.ModelNode.Image image) throws IOException;\n public void renderLastElement(Appendable writer, Map context, ModelTree.ModelNode node) throws IOException;\n public ScreenStringRenderer getScreenStringRenderer(Map context);\n}","smell_code":"public interface TreeStringRenderer {\n\n public void renderNodeBegin(Appendable writer, Map context, ModelTree.ModelNode node, int depth) throws IOException;\n public void renderNodeEnd(Appendable writer, Map context, ModelTree.ModelNode node) throws IOException;\n public void renderLabel(Appendable writer, Map context, ModelTree.ModelNode.Label label) throws IOException;\n public void renderLink(Appendable writer, Map context, ModelTree.ModelNode.Link link) throws IOException;\n public void renderImage(Appendable writer, Map context, ModelTree.ModelNode.Image image) throws IOException;\n public void renderLastElement(Appendable writer, Map context, ModelTree.ModelNode node) throws IOException;\n public ScreenStringRenderer getScreenStringRenderer(Map context);\n}","smell":"data class","id":108} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.hive.hplsql;\n\n\/**\n * Signals and exceptions\n *\/\npublic class Signal {\n public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED };\n Type type;\n String value = \"\";\n Exception exception = null;\n \n Signal(Type type, String value) {\n this.type = type;\n this.value = value;\n this.exception = null;\n }\n \n Signal(Type type, String value, Exception exception) {\n this.type = type;\n this.value = value;\n this.exception = exception;\n }\n \n \/**\n * Get the signal value (message text)\n *\/\n public String getValue() {\n return value;\n }\n}","smell_code":"public class Signal {\n public enum Type { LEAVE_LOOP, LEAVE_ROUTINE, LEAVE_PROGRAM, SQLEXCEPTION, NOTFOUND, UNSUPPORTED_OPERATION, USERDEFINED };\n Type type;\n String value = \"\";\n Exception exception = null;\n \n Signal(Type type, String value) {\n this.type = type;\n this.value = value;\n this.exception = null;\n }\n \n Signal(Type type, String value, Exception exception) {\n this.type = type;\n this.value = value;\n this.exception = exception;\n }\n \n \/**\n * Get the signal value (message text)\n *\/\n public String getValue() {\n return value;\n }\n}","smell":"data class","id":109} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2012-2019 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.springframework.boot.convert;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Set;\nimport java.util.stream.Stream;\n\nimport org.springframework.core.CollectionFactory;\nimport org.springframework.core.convert.ConversionService;\nimport org.springframework.core.convert.TypeDescriptor;\nimport org.springframework.core.convert.converter.ConditionalGenericConverter;\nimport org.springframework.util.Assert;\nimport org.springframework.util.StringUtils;\n\n\/**\n * Converts a {@link Delimiter delimited} String to a Collection.\n *\n * @author Phillip Webb\n *\/\nfinal class DelimitedStringToCollectionConverter implements ConditionalGenericConverter {\n\n\tprivate final ConversionService conversionService;\n\n\tDelimitedStringToCollectionConverter(ConversionService conversionService) {\n\t\tAssert.notNull(conversionService, \"ConversionService must not be null\");\n\t\tthis.conversionService = conversionService;\n\t}\n\n\t@Override\n\tpublic Set getConvertibleTypes() {\n\t\treturn Collections.singleton(new ConvertiblePair(String.class, Collection.class));\n\t}\n\n\t@Override\n\tpublic boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {\n\t\treturn targetType.getElementTypeDescriptor() == null || this.conversionService\n\t\t\t\t.canConvert(sourceType, targetType.getElementTypeDescriptor());\n\t}\n\n\t@Override\n\tpublic Object convert(Object source, TypeDescriptor sourceType,\n\t\t\tTypeDescriptor targetType) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn convert((String) source, sourceType, targetType);\n\t}\n\n\tprivate Object convert(String source, TypeDescriptor sourceType,\n\t\t\tTypeDescriptor targetType) {\n\t\tDelimiter delimiter = targetType.getAnnotation(Delimiter.class);\n\t\tString[] elements = getElements(source,\n\t\t\t\t(delimiter != null) ? delimiter.value() : \",\");\n\t\tTypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor();\n\t\tCollection target = createCollection(targetType, elementDescriptor,\n\t\t\t\telements.length);\n\t\tStream stream = Arrays.stream(elements).map(String::trim);\n\t\tif (elementDescriptor != null) {\n\t\t\tstream = stream.map((element) -> this.conversionService.convert(element,\n\t\t\t\t\tsourceType, elementDescriptor));\n\t\t}\n\t\tstream.forEach(target::add);\n\t\treturn target;\n\t}\n\n\tprivate Collection createCollection(TypeDescriptor targetType,\n\t\t\tTypeDescriptor elementDescriptor, int length) {\n\t\treturn CollectionFactory.createCollection(targetType.getType(),\n\t\t\t\t(elementDescriptor != null) ? elementDescriptor.getType() : null, length);\n\t}\n\n\tprivate String[] getElements(String source, String delimiter) {\n\t\treturn StringUtils.delimitedListToStringArray(source,\n\t\t\t\tDelimiter.NONE.equals(delimiter) ? null : delimiter);\n\t}\n\n}","smell_code":"final class DelimitedStringToCollectionConverter implements ConditionalGenericConverter {\n\n\tprivate final ConversionService conversionService;\n\n\tDelimitedStringToCollectionConverter(ConversionService conversionService) {\n\t\tAssert.notNull(conversionService, \"ConversionService must not be null\");\n\t\tthis.conversionService = conversionService;\n\t}\n\n\t@Override\n\tpublic Set getConvertibleTypes() {\n\t\treturn Collections.singleton(new ConvertiblePair(String.class, Collection.class));\n\t}\n\n\t@Override\n\tpublic boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {\n\t\treturn targetType.getElementTypeDescriptor() == null || this.conversionService\n\t\t\t\t.canConvert(sourceType, targetType.getElementTypeDescriptor());\n\t}\n\n\t@Override\n\tpublic Object convert(Object source, TypeDescriptor sourceType,\n\t\t\tTypeDescriptor targetType) {\n\t\tif (source == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn convert((String) source, sourceType, targetType);\n\t}\n\n\tprivate Object convert(String source, TypeDescriptor sourceType,\n\t\t\tTypeDescriptor targetType) {\n\t\tDelimiter delimiter = targetType.getAnnotation(Delimiter.class);\n\t\tString[] elements = getElements(source,\n\t\t\t\t(delimiter != null) ? delimiter.value() : \",\");\n\t\tTypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor();\n\t\tCollection target = createCollection(targetType, elementDescriptor,\n\t\t\t\telements.length);\n\t\tStream stream = Arrays.stream(elements).map(String::trim);\n\t\tif (elementDescriptor != null) {\n\t\t\tstream = stream.map((element) -> this.conversionService.convert(element,\n\t\t\t\t\tsourceType, elementDescriptor));\n\t\t}\n\t\tstream.forEach(target::add);\n\t\treturn target;\n\t}\n\n\tprivate Collection createCollection(TypeDescriptor targetType,\n\t\t\tTypeDescriptor elementDescriptor, int length) {\n\t\treturn CollectionFactory.createCollection(targetType.getType(),\n\t\t\t\t(elementDescriptor != null) ? elementDescriptor.getType() : null, length);\n\t}\n\n\tprivate String[] getElements(String source, String delimiter) {\n\t\treturn StringUtils.delimitedListToStringArray(source,\n\t\t\t\tDelimiter.NONE.equals(delimiter) ? null : delimiter);\n\t}\n\n}","smell":"data class","id":110} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.jena.sparql.expr.nodevalue;\n\nimport org.apache.jena.graph.Node ;\nimport org.apache.jena.graph.NodeFactory ;\nimport org.apache.jena.sparql.expr.NodeValue ;\nimport org.apache.jena.sparql.util.FmtUtils ;\n\n\npublic class NodeValueString extends NodeValue\n{\n \/\/ A plain string, with no language tag, or an xsd:string.\n \n private String string ; \n \n public NodeValueString(String str) { string = str ; } \n public NodeValueString(String str, Node n) { super(n) ; string = str ; }\n \n @Override\n public boolean isString() { return true ; }\n \n @Override\n public String getString() { return string ; }\n\n @Override\n public String asString() { return string ; }\n \n @Override\n public String toString()\n { \n if ( getNode() != null )\n {\n \/\/ Can be a plain string or an xsd:string.\n return FmtUtils.stringForNode(getNode()) ;\n }\n return '\"'+string+'\"' ;\n }\n \n @Override\n protected Node makeNode()\n { return NodeFactory.createLiteral(string) ; }\n \n @Override\n public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; }\n}","smell_code":"public class NodeValueString extends NodeValue\n{\n \/\/ A plain string, with no language tag, or an xsd:string.\n \n private String string ; \n \n public NodeValueString(String str) { string = str ; } \n public NodeValueString(String str, Node n) { super(n) ; string = str ; }\n \n @Override\n public boolean isString() { return true ; }\n \n @Override\n public String getString() { return string ; }\n\n @Override\n public String asString() { return string ; }\n \n @Override\n public String toString()\n { \n if ( getNode() != null )\n {\n \/\/ Can be a plain string or an xsd:string.\n return FmtUtils.stringForNode(getNode()) ;\n }\n return '\"'+string+'\"' ;\n }\n \n @Override\n protected Node makeNode()\n { return NodeFactory.createLiteral(string) ; }\n \n @Override\n public void visit(NodeValueVisitor visitor) { visitor.visit(this) ; }\n}","smell":"data class","id":111} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/* $Id$ *\/\n\npackage org.apache.fop.render.pcl;\n\nimport org.apache.fop.apps.MimeConstants;\nimport org.apache.fop.render.intermediate.AbstractIFDocumentHandlerMaker;\nimport org.apache.fop.render.intermediate.IFContext;\nimport org.apache.fop.render.intermediate.IFDocumentHandler;\n\n\/**\n * Document handler factory for PCL output.\n *\/\npublic class PCLDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker {\n\n private static final String[] MIMES = new String[] {\n MimeConstants.MIME_PCL,\n MimeConstants.MIME_PCL_ALT\n };\n\n \/** {@inheritDoc} *\/\n public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) {\n return new PCLDocumentHandler(ifContext);\n }\n\n \/** {@inheritDoc} *\/\n public boolean needsOutputStream() {\n return true;\n }\n\n \/** {@inheritDoc} *\/\n public String[] getSupportedMimeTypes() {\n return MIMES;\n }\n\n}","smell_code":"public class PCLDocumentHandlerMaker extends AbstractIFDocumentHandlerMaker {\n\n private static final String[] MIMES = new String[] {\n MimeConstants.MIME_PCL,\n MimeConstants.MIME_PCL_ALT\n };\n\n \/** {@inheritDoc} *\/\n public IFDocumentHandler makeIFDocumentHandler(IFContext ifContext) {\n return new PCLDocumentHandler(ifContext);\n }\n\n \/** {@inheritDoc} *\/\n public boolean needsOutputStream() {\n return true;\n }\n\n \/** {@inheritDoc} *\/\n public String[] getSupportedMimeTypes() {\n return MIMES;\n }\n\n}","smell":"data class","id":112} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.commons.functor.range;\n\nimport org.apache.commons.functor.BinaryFunction;\n\n\/**\n * A base class for numeric ranges. The elements within this range must be a\n * Number<\/b> and Comparable<\/b>.\n *\n * @param the type of numbers and step that are both a number and comparable\n * @see org.apache.commons.functor.range.IntegerRange\n * @see org.apache.commons.functor.range.LongRange\n * @see org.apache.commons.functor.range.FloatRange\n * @see org.apache.commons.functor.range.DoubleRange\n * @see org.apache.commons.functor.range.CharacterRange\n * @since 0.1\n * @version $Revision$ $Date$\n *\/\npublic abstract class NumericRange> extends AbstractRange {\n\n \/**\n * Construct a new {@link NumericRange}.\n * @param leftEndpoint left endpoint\n * @param rightEndpoint right endpoint\n * @param step increment step\n * @param nextValue function to implement the taking of a step\n *\/\n protected NumericRange(Endpoint leftEndpoint, Endpoint rightEndpoint, T step,\n BinaryFunction nextValue) {\n super(leftEndpoint, rightEndpoint, step, nextValue);\n }\n\n \/**\n * {@inheritDoc}\n *\/\n public boolean contains(T obj) {\n if (obj == null) {\n return false;\n }\n double leftValue = this.getLeftEndpoint().getValue().doubleValue();\n double rightValue = this.getRightEndpoint().getValue().doubleValue();\n boolean includeLeft = this.getLeftEndpoint().getBoundType() == BoundType.CLOSED;\n boolean includeRight = this.getRightEndpoint().getBoundType() == BoundType.CLOSED;\n double step = this.getStep().doubleValue();\n double value = obj.doubleValue();\n\n double firstValue = 0;\n double lastValue = 0;\n\n if (step < 0.0) {\n firstValue = includeLeft ? leftValue : leftValue + step;\n lastValue = includeRight ? rightValue : Math.nextUp(rightValue);\n if (value > firstValue || value < lastValue) {\n return false;\n }\n } else {\n firstValue = includeLeft ? leftValue : leftValue + step;\n lastValue = includeRight ? rightValue : rightValue\n - (rightValue - Math\n .nextUp(rightValue));\n if (value < firstValue || value > lastValue) {\n return false;\n }\n }\n return ((value - firstValue) \/ step + 1) % 1.0 == 0.0;\n }\n\n}","smell_code":"public abstract class NumericRange> extends AbstractRange {\n\n \/**\n * Construct a new {@link NumericRange}.\n * @param leftEndpoint left endpoint\n * @param rightEndpoint right endpoint\n * @param step increment step\n * @param nextValue function to implement the taking of a step\n *\/\n protected NumericRange(Endpoint leftEndpoint, Endpoint rightEndpoint, T step,\n BinaryFunction nextValue) {\n super(leftEndpoint, rightEndpoint, step, nextValue);\n }\n\n \/**\n * {@inheritDoc}\n *\/\n public boolean contains(T obj) {\n if (obj == null) {\n return false;\n }\n double leftValue = this.getLeftEndpoint().getValue().doubleValue();\n double rightValue = this.getRightEndpoint().getValue().doubleValue();\n boolean includeLeft = this.getLeftEndpoint().getBoundType() == BoundType.CLOSED;\n boolean includeRight = this.getRightEndpoint().getBoundType() == BoundType.CLOSED;\n double step = this.getStep().doubleValue();\n double value = obj.doubleValue();\n\n double firstValue = 0;\n double lastValue = 0;\n\n if (step < 0.0) {\n firstValue = includeLeft ? leftValue : leftValue + step;\n lastValue = includeRight ? rightValue : Math.nextUp(rightValue);\n if (value > firstValue || value < lastValue) {\n return false;\n }\n } else {\n firstValue = includeLeft ? leftValue : leftValue + step;\n lastValue = includeRight ? rightValue : rightValue\n - (rightValue - Math\n .nextUp(rightValue));\n if (value < firstValue || value > lastValue) {\n return false;\n }\n }\n return ((value - firstValue) \/ step + 1) % 1.0 == 0.0;\n }\n\n}","smell":"data class","id":113} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.jena.graph;\n\nimport org.apache.jena.graph.impl.GraphBase ;\nimport org.apache.jena.shared.AddDeniedException ;\nimport org.apache.jena.shared.DeleteDeniedException ;\nimport org.apache.jena.shared.PrefixMapping ;\nimport org.apache.jena.util.iterator.ExtendedIterator ;\nimport org.apache.jena.util.iterator.NullIterator ;\n\n\/**\n The interface to be satisfied by implementations maintaining collections\n of RDF triples. The core interface is small (add, delete, find, contains) and\n is augmented by additional classes to handle more complicated matters\n such as event management.\n @see GraphBase for an implementation framework.\n*\/\npublic interface Graph\n {\n \/**\n An immutable empty graph. \n *\/\n public static final Graph emptyGraph = new GraphBase()\n { @Override\n public ExtendedIterator graphBaseFind( Triple tm ) { return NullIterator.instance(); } };\n \t\n \/** \n true if this graph's content depends on the other graph. May be\n pessimistic (ie return true if it's not sure). Typically true when a\n graph is a composition of other graphs, eg union.\n \n @param other the graph this graph may depend on\n @return false if this does not depend on other \n *\/\n boolean dependsOn( Graph other );\n \n \/** returns this Graph's transaction handler *\/\n TransactionHandler getTransactionHandler();\n \n \/** returns this Graph's capabilities *\/\n Capabilities getCapabilities();\n \n \/**\n Answer this Graph's event manager.\n *\/\n GraphEventManager getEventManager(); \n \n \/**\n Answer this Graph's statistics handler, or null if there isn't one. Every\n call to this method on a particular graph delivers the same (==) answer.\n *\/\n GraphStatisticsHandler getStatisticsHandler();\n \n \/**\n returns this Graph's prefix mapping. Each call on a given Graph gets the\n same PrefixMapping object, which is the one used by the Graph.\n *\/\n PrefixMapping getPrefixMapping();\n\n \/** \n Add the triple t (if possible) to the set belonging to this graph \n @param t the triple to add to the graph\n @throws AddDeniedException if the triple cannot be added \n *\/\n void add( Triple t ) throws AddDeniedException;\n\n \/** \n Delete the triple t (if possible) from the set belonging to this graph \n \n @param t the triple to delete to the graph\n @throws DeleteDeniedException if the triple cannot be removed \n *\/ \n\tvoid delete(Triple t) throws DeleteDeniedException;\n \n\t\/** \n Returns an iterator over all the Triples that match the triple pattern.\n \n @param m a Triple encoding the pattern to look for\n @return an iterator of all triples in this graph that match m\n\t *\/\n\tExtendedIterator find(Triple m);\n\n\t\/** Returns an iterator over Triples matching a pattern.\n * \n * @return an iterator of all triples in this graph\n\t *\/\n\tExtendedIterator find(Node s, Node p, Node o);\n \n \/** Returns an iterator over all Triples in the graph.\n * Equivalent to {@code find(Node.ANY, Node.ANY, Node.ANY)}\n * \n * @return an iterator of all triples in this graph\n *\/\n default ExtendedIterator find() { return find(Node.ANY, Node.ANY, Node.ANY); }\n\n \/**\n\t * Compare this graph with another using the method\n\t * described in \n\t * \n * http:\/\/www.w3.org\/TR\/rdf-concepts#section-Graph-syntax\n * <\/a>\n\t * @param g Compare against this.\n\t * @return boolean True if the two graphs are isomorphic.\n\t *\/\n\tboolean isIsomorphicWith(Graph g);\n \n \/** \n Answer true iff the graph contains a triple matching (s, p, o).\n s\/p\/o may be concrete or fluid. Equivalent to find(s,p,o).hasNext,\n but an implementation is expected to optimise this in easy cases.\n *\/\n boolean contains( Node s, Node p, Node o );\n \n \/** \n Answer true iff the graph contains a triple that t matches; t may be\n fluid.\n *\/\n boolean contains( Triple t );\n \n \/**\n Remove all the statements from this graph.\n *\/\n void clear();\n \n \/**\n Remove all triples that match by find(s, p, o)\n *\/\n void remove( Node s, Node p, Node o );\n \n\t\/** Free all resources, any further use of this Graph is an error.\n\t *\/\n\tvoid close();\n \n \/**\n Answer true iff this graph is empty. \"Empty\" means \"has as few triples as it\n can manage\", because an inference graph may have irremovable axioms\n and their consequences.\n *\/\n boolean isEmpty();\n \n \/**\n * For a concrete graph this returns the number of triples in the graph. For graphs which\n * might infer additional triples it results an estimated lower bound of the number of triples.\n * For example, an inference graph might return the number of triples in the raw data graph. \n *\/\n\t int size();\n\n \/**\n Answer true iff .close() has been called on this Graph.\n *\/\n boolean isClosed();\n }","smell_code":"public interface Graph\n {\n \/**\n An immutable empty graph. \n *\/\n public static final Graph emptyGraph = new GraphBase()\n { @Override\n public ExtendedIterator graphBaseFind( Triple tm ) { return NullIterator.instance(); } };\n \t\n \/** \n true if this graph's content depends on the other graph. May be\n pessimistic (ie return true if it's not sure). Typically true when a\n graph is a composition of other graphs, eg union.\n \n @param other the graph this graph may depend on\n @return false if this does not depend on other \n *\/\n boolean dependsOn( Graph other );\n \n \/** returns this Graph's transaction handler *\/\n TransactionHandler getTransactionHandler();\n \n \/** returns this Graph's capabilities *\/\n Capabilities getCapabilities();\n \n \/**\n Answer this Graph's event manager.\n *\/\n GraphEventManager getEventManager(); \n \n \/**\n Answer this Graph's statistics handler, or null if there isn't one. Every\n call to this method on a particular graph delivers the same (==) answer.\n *\/\n GraphStatisticsHandler getStatisticsHandler();\n \n \/**\n returns this Graph's prefix mapping. Each call on a given Graph gets the\n same PrefixMapping object, which is the one used by the Graph.\n *\/\n PrefixMapping getPrefixMapping();\n\n \/** \n Add the triple t (if possible) to the set belonging to this graph \n @param t the triple to add to the graph\n @throws AddDeniedException if the triple cannot be added \n *\/\n void add( Triple t ) throws AddDeniedException;\n\n \/** \n Delete the triple t (if possible) from the set belonging to this graph \n \n @param t the triple to delete to the graph\n @throws DeleteDeniedException if the triple cannot be removed \n *\/ \n\tvoid delete(Triple t) throws DeleteDeniedException;\n \n\t\/** \n Returns an iterator over all the Triples that match the triple pattern.\n \n @param m a Triple encoding the pattern to look for\n @return an iterator of all triples in this graph that match m\n\t *\/\n\tExtendedIterator find(Triple m);\n\n\t\/** Returns an iterator over Triples matching a pattern.\n * \n * @return an iterator of all triples in this graph\n\t *\/\n\tExtendedIterator find(Node s, Node p, Node o);\n \n \/** Returns an iterator over all Triples in the graph.\n * Equivalent to {@code find(Node.ANY, Node.ANY, Node.ANY)}\n * \n * @return an iterator of all triples in this graph\n *\/\n default ExtendedIterator find() { return find(Node.ANY, Node.ANY, Node.ANY); }\n\n \/**\n\t * Compare this graph with another using the method\n\t * described in \n\t * \n * http:\/\/www.w3.org\/TR\/rdf-concepts#section-Graph-syntax\n * <\/a>\n\t * @param g Compare against this.\n\t * @return boolean True if the two graphs are isomorphic.\n\t *\/\n\tboolean isIsomorphicWith(Graph g);\n \n \/** \n Answer true iff the graph contains a triple matching (s, p, o).\n s\/p\/o may be concrete or fluid. Equivalent to find(s,p,o).hasNext,\n but an implementation is expected to optimise this in easy cases.\n *\/\n boolean contains( Node s, Node p, Node o );\n \n \/** \n Answer true iff the graph contains a triple that t matches; t may be\n fluid.\n *\/\n boolean contains( Triple t );\n \n \/**\n Remove all the statements from this graph.\n *\/\n void clear();\n \n \/**\n Remove all triples that match by find(s, p, o)\n *\/\n void remove( Node s, Node p, Node o );\n \n\t\/** Free all resources, any further use of this Graph is an error.\n\t *\/\n\tvoid close();\n \n \/**\n Answer true iff this graph is empty. \"Empty\" means \"has as few triples as it\n can manage\", because an inference graph may have irremovable axioms\n and their consequences.\n *\/\n boolean isEmpty();\n \n \/**\n * For a concrete graph this returns the number of triples in the graph. For graphs which\n * might infer additional triples it results an estimated lower bound of the number of triples.\n * For example, an inference graph might return the number of triples in the raw data graph. \n *\/\n\t int size();\n\n \/**\n Answer true iff .close() has been called on this Graph.\n *\/\n boolean isClosed();\n }","smell":"data class","id":114} {"lang_cluster":"Java","source_code":"\/*\n\n Derby - Class org.apache.derbyTesting.functionTests.tests.compatibility.helpers.DummyClob\n\n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to you under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n *\/\npackage org.apache.derbyTesting.functionTests.tests.compatibility.helpers;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.Writer;\nimport java.sql.Clob;\nimport java.sql.SQLException;\n\n\/**\n * A crude Clob implementation for datatype testing.\n *\/\npublic class DummyClob\n implements Clob {\n private\tString\t_contents;\n\n public\tDummyClob(String contents)\n {\n _contents = contents;\n }\n\n public\tInputStream\tgetAsciiStream()\n {\n try {\n return new ByteArrayInputStream( _contents.getBytes( \"UTF-8\" ) );\n }\n catch (Exception e) { return null; }\n }\n\n public\tReader\tgetCharacterStream()\n {\n return new StringReader(_contents);\n }\n\n public\tString\tgetSubString( long position, int length )\n {\n return _contents.substring( (int) position -1, length );\n }\n\n public\tlong\tlength() { return (long) _contents.length(); }\n\n public\tlong\tposition( Clob searchstr, long start ) { return 0L; }\n public\tlong\tposition( String searchstr, long start ) { return 0L; }\n\n public\tboolean\tequals( Object other )\n {\n if ( other == null ) { return false; }\n if ( !( other instanceof Clob ) ) { return false; }\n\n Clob\tthat = (Clob) other;\n\n try {\n if ( this.length() != that.length() ) { return false; }\n\n InputStream\tthisStream = this.getAsciiStream();\n InputStream\tthatStream = that.getAsciiStream();\n\n while( true )\n {\n int\t\tnextByte = thisStream.read();\n\n if ( nextByte < 0 ) { break; }\n if ( nextByte != thatStream.read() ) { return false; }\n }\n }\n catch (Exception e)\n {\n System.err.println( e.getMessage() );\n e.printStackTrace(System.err);\n return false;\n }\n\n return true;\n }\n\n public int setString(long arg0, String arg1) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public int setString(long arg0, String arg1, int arg2, int arg3) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public OutputStream setAsciiStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public Writer setCharacterStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void truncate(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void free() throws SQLException {\n _contents = null;\n }\n\n public Reader getCharacterStream(long pos, long length) throws SQLException {\n return new StringReader(\n _contents.substring((int)pos -1, (int)(pos + length)));\n }\n}","smell_code":"public class DummyClob\n implements Clob {\n private\tString\t_contents;\n\n public\tDummyClob(String contents)\n {\n _contents = contents;\n }\n\n public\tInputStream\tgetAsciiStream()\n {\n try {\n return new ByteArrayInputStream( _contents.getBytes( \"UTF-8\" ) );\n }\n catch (Exception e) { return null; }\n }\n\n public\tReader\tgetCharacterStream()\n {\n return new StringReader(_contents);\n }\n\n public\tString\tgetSubString( long position, int length )\n {\n return _contents.substring( (int) position -1, length );\n }\n\n public\tlong\tlength() { return (long) _contents.length(); }\n\n public\tlong\tposition( Clob searchstr, long start ) { return 0L; }\n public\tlong\tposition( String searchstr, long start ) { return 0L; }\n\n public\tboolean\tequals( Object other )\n {\n if ( other == null ) { return false; }\n if ( !( other instanceof Clob ) ) { return false; }\n\n Clob\tthat = (Clob) other;\n\n try {\n if ( this.length() != that.length() ) { return false; }\n\n InputStream\tthisStream = this.getAsciiStream();\n InputStream\tthatStream = that.getAsciiStream();\n\n while( true )\n {\n int\t\tnextByte = thisStream.read();\n\n if ( nextByte < 0 ) { break; }\n if ( nextByte != thatStream.read() ) { return false; }\n }\n }\n catch (Exception e)\n {\n System.err.println( e.getMessage() );\n e.printStackTrace(System.err);\n return false;\n }\n\n return true;\n }\n\n public int setString(long arg0, String arg1) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public int setString(long arg0, String arg1, int arg2, int arg3) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public OutputStream setAsciiStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public Writer setCharacterStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void truncate(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void free() throws SQLException {\n _contents = null;\n }\n\n public Reader getCharacterStream(long pos, long length) throws SQLException {\n return new StringReader(\n _contents.substring((int)pos -1, (int)(pos + length)));\n }\n}","smell":"data class","id":115} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage org.apache.ode.bpel.engine.migration;\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.apache.ode.bpel.engine.BpelProcess;\nimport org.apache.ode.bpel.engine.Contexts;\n\n\/**\n * Checks database schema versions and migrates when necessary.\n *\/\npublic class MigrationHandler {\n private static final Logger __log = LoggerFactory.getLogger(MigrationHandler.class);\n\n public static final int CURRENT_SCHEMA_VERSION = 7;\n\n\n private Contexts _contexts;\n private List migrationLinks = new ArrayList() {{\n add(new MigrationLink(1, 2, new Migration[] { new CorrelatorsMigration(),\n new CorrelationKeyMigration() } ));\n add(new MigrationLink(2, 3, new Migration[] { new CorrelationKeySetMigration() } ));\n add(new MigrationLink(4, 3, new Migration[] { new CorrelationKeySetMigration() } ));\n add(new MigrationLink(3, 5, new Migration[] { new CorrelationKeySetDataMigration() } ));\n add(new MigrationLink(5, 6, new Migration[] { new OutstandingRequestsMigration() } ));\n add(new MigrationLink(6, 7, new Migration[] { new IMAManagerMigration() } ));\n }};\n\n\n public MigrationHandler(Contexts _contexts) {\n this._contexts = _contexts;\n }\n\n public boolean migrate(final Set registeredProcesses, int migrationTransactionTimeout) {\n if (_contexts.dao.getDataSource() == null) {\n __log.debug(\"No datasource available, stopping migration. Probably running fully in-memory.\");\n return true;\n }\n\n final int version;\n try {\n version = getDbVersion();\n } catch (Throwable e) {\n __log.info(\"The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data\" +\n \"from a past version, this message can be safely ignored.\");\n return false;\n }\n if (version == -1) {\n __log.info(\"No schema version available from the database, migrations will be skipped.\");\n return true;\n }\n if (version == CURRENT_SCHEMA_VERSION) return true;\n\n try {\n boolean success = _contexts.scheduler.execTransaction(new Callable() {\n public Boolean call() throws Exception {\n ArrayList migrations = new ArrayList();\n findMigrations(version, CURRENT_SCHEMA_VERSION, migrations);\n if (migrations.size() == 0) {\n __log.error(\"Don't know how to migrate from \" + version + \" to \" + CURRENT_SCHEMA_VERSION + \", aborting\");\n return false;\n } else {\n boolean success = true;\n for (Migration mig : migrations) {\n __log.debug(\"Running migration \" + mig);\n success = mig.migrate(registeredProcesses, _contexts.dao.getConnection()) && success;\n }\n\n if (!success) _contexts.scheduler.setRollbackOnly();\n else setDbVersion(CURRENT_SCHEMA_VERSION);\n return success;\n }\n }\n }, migrationTransactionTimeout);\n return success;\n } catch (Exception e) {\n __log.error(\"An error occured while migrating your database to a newer version of ODE, changes have \" +\n \"been aborted\", e);\n throw new RuntimeException(e);\n }\n }\n\n private static class MigrationLink {\n int source;\n int target;\n Migration[] migrations;\n public MigrationLink(int source, int target, Migration[] migrations) {\n this.source = source;\n this.target = target;\n this.migrations = migrations;\n }\n }\n\n \/**\n * Attempts to find a way from a source to a target and collects the migrations found along. Assumes\n * a directed graph with no loops. Guarantees that migrations are collected in the proper start-to-end\n * order.\n *\/\n private boolean findMigrations(int source, int target, List ms) {\n List l = findLinksTo(target);\n for (MigrationLink link : l) {\n if (link.source == source || findMigrations(source, link.source, ms)) {\n ms.addAll(Arrays.asList(link.migrations));\n return true;\n }\n }\n return false;\n }\n\n \/**\n * Finds all the links with a given target.\n *\/\n private List findLinksTo(int target) {\n ArrayList mls = new ArrayList();\n for (MigrationLink ml : migrationLinks) {\n if (ml.target == target) mls.add(ml);\n }\n return mls;\n }\n\n private int getDbVersion() {\n int version = -1;\n Connection conn = null;\n PreparedStatement stmt = null;\n ResultSet rs = null;\n try {\n conn = _contexts.dao.getDataSource().getConnection();\n stmt = conn.prepareStatement(\"SELECT VERSION FROM ODE_SCHEMA_VERSION\");\n rs = stmt.executeQuery();\n if (rs.next()) version = rs.getInt(\"VERSION\");\n } catch (Exception e) {\n \/\/ Swallow, we'll just abort based on the version number\n } finally {\n try {\n if (rs != null) rs.close();\n if (stmt != null) stmt.close();\n if (conn != null) conn.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n return version;\n }\n\n private void setDbVersion(int version) {\n Connection conn = null;\n Statement stmt = null;\n try {\n conn = _contexts.dao.getDataSource().getConnection();\n stmt = conn.createStatement();\n int res = stmt.executeUpdate(\"UPDATE ODE_SCHEMA_VERSION SET VERSION = \" + version);\n \/\/ This should never happen but who knows?\n if (res == 0) throw new RuntimeException(\"Couldn't update schema version.\");\n } catch (Exception e) {\n \/\/ Swallow, we'll just abort based on the version number\n } finally {\n try {\n if (stmt != null) stmt.close();\n if (conn != null) conn.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}","smell_code":"public class MigrationHandler {\n private static final Logger __log = LoggerFactory.getLogger(MigrationHandler.class);\n\n public static final int CURRENT_SCHEMA_VERSION = 7;\n\n\n private Contexts _contexts;\n private List migrationLinks = new ArrayList() {{\n add(new MigrationLink(1, 2, new Migration[] { new CorrelatorsMigration(),\n new CorrelationKeyMigration() } ));\n add(new MigrationLink(2, 3, new Migration[] { new CorrelationKeySetMigration() } ));\n add(new MigrationLink(4, 3, new Migration[] { new CorrelationKeySetMigration() } ));\n add(new MigrationLink(3, 5, new Migration[] { new CorrelationKeySetDataMigration() } ));\n add(new MigrationLink(5, 6, new Migration[] { new OutstandingRequestsMigration() } ));\n add(new MigrationLink(6, 7, new Migration[] { new IMAManagerMigration() } ));\n }};\n\n\n public MigrationHandler(Contexts _contexts) {\n this._contexts = _contexts;\n }\n\n public boolean migrate(final Set registeredProcesses, int migrationTransactionTimeout) {\n if (_contexts.dao.getDataSource() == null) {\n __log.debug(\"No datasource available, stopping migration. Probably running fully in-memory.\");\n return true;\n }\n\n final int version;\n try {\n version = getDbVersion();\n } catch (Throwable e) {\n __log.info(\"The ODE_SCHEMA_VERSION database table doesn't exist. Unless you need to migrate your data\" +\n \"from a past version, this message can be safely ignored.\");\n return false;\n }\n if (version == -1) {\n __log.info(\"No schema version available from the database, migrations will be skipped.\");\n return true;\n }\n if (version == CURRENT_SCHEMA_VERSION) return true;\n\n try {\n boolean success = _contexts.scheduler.execTransaction(new Callable() {\n public Boolean call() throws Exception {\n ArrayList migrations = new ArrayList();\n findMigrations(version, CURRENT_SCHEMA_VERSION, migrations);\n if (migrations.size() == 0) {\n __log.error(\"Don't know how to migrate from \" + version + \" to \" + CURRENT_SCHEMA_VERSION + \", aborting\");\n return false;\n } else {\n boolean success = true;\n for (Migration mig : migrations) {\n __log.debug(\"Running migration \" + mig);\n success = mig.migrate(registeredProcesses, _contexts.dao.getConnection()) && success;\n }\n\n if (!success) _contexts.scheduler.setRollbackOnly();\n else setDbVersion(CURRENT_SCHEMA_VERSION);\n return success;\n }\n }\n }, migrationTransactionTimeout);\n return success;\n } catch (Exception e) {\n __log.error(\"An error occured while migrating your database to a newer version of ODE, changes have \" +\n \"been aborted\", e);\n throw new RuntimeException(e);\n }\n }\n\n private static class MigrationLink {\n int source;\n int target;\n Migration[] migrations;\n public MigrationLink(int source, int target, Migration[] migrations) {\n this.source = source;\n this.target = target;\n this.migrations = migrations;\n }\n }\n\n \/**\n * Attempts to find a way from a source to a target and collects the migrations found along. Assumes\n * a directed graph with no loops. Guarantees that migrations are collected in the proper start-to-end\n * order.\n *\/\n private boolean findMigrations(int source, int target, List ms) {\n List l = findLinksTo(target);\n for (MigrationLink link : l) {\n if (link.source == source || findMigrations(source, link.source, ms)) {\n ms.addAll(Arrays.asList(link.migrations));\n return true;\n }\n }\n return false;\n }\n\n \/**\n * Finds all the links with a given target.\n *\/\n private List findLinksTo(int target) {\n ArrayList mls = new ArrayList();\n for (MigrationLink ml : migrationLinks) {\n if (ml.target == target) mls.add(ml);\n }\n return mls;\n }\n\n private int getDbVersion() {\n int version = -1;\n Connection conn = null;\n PreparedStatement stmt = null;\n ResultSet rs = null;\n try {\n conn = _contexts.dao.getDataSource().getConnection();\n stmt = conn.prepareStatement(\"SELECT VERSION FROM ODE_SCHEMA_VERSION\");\n rs = stmt.executeQuery();\n if (rs.next()) version = rs.getInt(\"VERSION\");\n } catch (Exception e) {\n \/\/ Swallow, we'll just abort based on the version number\n } finally {\n try {\n if (rs != null) rs.close();\n if (stmt != null) stmt.close();\n if (conn != null) conn.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n return version;\n }\n\n private void setDbVersion(int version) {\n Connection conn = null;\n Statement stmt = null;\n try {\n conn = _contexts.dao.getDataSource().getConnection();\n stmt = conn.createStatement();\n int res = stmt.executeUpdate(\"UPDATE ODE_SCHEMA_VERSION SET VERSION = \" + version);\n \/\/ This should never happen but who knows?\n if (res == 0) throw new RuntimeException(\"Couldn't update schema version.\");\n } catch (Exception e) {\n \/\/ Swallow, we'll just abort based on the version number\n } finally {\n try {\n if (stmt != null) stmt.close();\n if (conn != null) conn.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}","smell":"data class","id":116} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.jena.atlas.lib;\n\nimport org.apache.jena.atlas.AtlasException ;\nimport org.slf4j.Logger ;\nimport org.slf4j.LoggerFactory ;\n\npublic class SystemUtils\n{\n private static Logger log = LoggerFactory.getLogger(SystemUtils.class.getName());\n \/\/ Unfortunately, this tends to cause confusing logging.\n private static boolean logging = false ;\n \n static public ClassLoader chooseClassLoader()\n {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n \n if ( logging && classLoader != null )\n log.trace(\"Using thread classloader\") ;\n \n\/\/ if (classLoader == null)\n\/\/ {\n\/\/ classLoader = this.getClass().getClassLoader();\n\/\/ if ( classLoader != null )\n\/\/ logger.trace(\"Using 'this' classloader\") ;\n\/\/ }\n \n if ( classLoader == null )\n {\n classLoader = ClassLoader.getSystemClassLoader() ;\n if ( logging && classLoader != null )\n log.trace(\"Using system classloader\") ;\n }\n \n if ( classLoader == null )\n throw new AtlasException(\"Failed to find a classloader\") ;\n return classLoader ;\n }\n \n}","smell_code":"public class SystemUtils\n{\n private static Logger log = LoggerFactory.getLogger(SystemUtils.class.getName());\n \/\/ Unfortunately, this tends to cause confusing logging.\n private static boolean logging = false ;\n \n static public ClassLoader chooseClassLoader()\n {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n \n if ( logging && classLoader != null )\n log.trace(\"Using thread classloader\") ;\n \n\/\/ if (classLoader == null)\n\/\/ {\n\/\/ classLoader = this.getClass().getClassLoader();\n\/\/ if ( classLoader != null )\n\/\/ logger.trace(\"Using 'this' classloader\") ;\n\/\/ }\n \n if ( classLoader == null )\n {\n classLoader = ClassLoader.getSystemClassLoader() ;\n if ( logging && classLoader != null )\n log.trace(\"Using system classloader\") ;\n }\n \n if ( classLoader == null )\n throw new AtlasException(\"Failed to find a classloader\") ;\n return classLoader ;\n }\n \n}","smell":"data class","id":117} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.springframework.security.access.intercept.aopalliance;\n\nimport org.springframework.security.access.SecurityMetadataSource;\nimport org.springframework.security.access.intercept.AbstractSecurityInterceptor;\nimport org.springframework.security.access.intercept.InterceptorStatusToken;\nimport org.springframework.security.access.method.MethodSecurityMetadataSource;\n\nimport org.aopalliance.intercept.MethodInterceptor;\nimport org.aopalliance.intercept.MethodInvocation;\n\n\/**\n * Provides security interception of AOP Alliance based method invocations.\n *

\n * The SecurityMetadataSource<\/code> required by this security interceptor is of\n * type {@link MethodSecurityMetadataSource}. This is shared with the AspectJ based\n * security interceptor (AspectJSecurityInterceptor<\/code>), since both work with\n * Java Method<\/code>s.\n *

\n * Refer to {@link AbstractSecurityInterceptor} for details on the workflow.\n *\n * @author Ben Alex\n * @author Rob Winch\n *\/\npublic class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements\n\t\tMethodInterceptor {\n\t\/\/ ~ Instance fields\n\t\/\/ ================================================================================================\n\n\tprivate MethodSecurityMetadataSource securityMetadataSource;\n\n\t\/\/ ~ Methods\n\t\/\/ ========================================================================================================\n\n\tpublic Class getSecureObjectClass() {\n\t\treturn MethodInvocation.class;\n\t}\n\n\t\/**\n\t * This method should be used to enforce security on a MethodInvocation<\/code>.\n\t *\n\t * @param mi The method being invoked which requires a security decision\n\t *\n\t * @return The returned value from the method invocation (possibly modified by the\n\t * {@code AfterInvocationManager}).\n\t *\n\t * @throws Throwable if any error occurs\n\t *\/\n\tpublic Object invoke(MethodInvocation mi) throws Throwable {\n\t\tInterceptorStatusToken token = super.beforeInvocation(mi);\n\n\t\tObject result;\n\t\ttry {\n\t\t\tresult = mi.proceed();\n\t\t}\n\t\tfinally {\n\t\t\tsuper.finallyInvocation(token);\n\t\t}\n\t\treturn super.afterInvocation(token, result);\n\t}\n\n\tpublic MethodSecurityMetadataSource getSecurityMetadataSource() {\n\t\treturn this.securityMetadataSource;\n\t}\n\n\tpublic SecurityMetadataSource obtainSecurityMetadataSource() {\n\t\treturn this.securityMetadataSource;\n\t}\n\n\tpublic void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) {\n\t\tthis.securityMetadataSource = newSource;\n\t}\n}","smell_code":"public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements\n\t\tMethodInterceptor {\n\t\/\/ ~ Instance fields\n\t\/\/ ================================================================================================\n\n\tprivate MethodSecurityMetadataSource securityMetadataSource;\n\n\t\/\/ ~ Methods\n\t\/\/ ========================================================================================================\n\n\tpublic Class getSecureObjectClass() {\n\t\treturn MethodInvocation.class;\n\t}\n\n\t\/**\n\t * This method should be used to enforce security on a MethodInvocation<\/code>.\n\t *\n\t * @param mi The method being invoked which requires a security decision\n\t *\n\t * @return The returned value from the method invocation (possibly modified by the\n\t * {@code AfterInvocationManager}).\n\t *\n\t * @throws Throwable if any error occurs\n\t *\/\n\tpublic Object invoke(MethodInvocation mi) throws Throwable {\n\t\tInterceptorStatusToken token = super.beforeInvocation(mi);\n\n\t\tObject result;\n\t\ttry {\n\t\t\tresult = mi.proceed();\n\t\t}\n\t\tfinally {\n\t\t\tsuper.finallyInvocation(token);\n\t\t}\n\t\treturn super.afterInvocation(token, result);\n\t}\n\n\tpublic MethodSecurityMetadataSource getSecurityMetadataSource() {\n\t\treturn this.securityMetadataSource;\n\t}\n\n\tpublic SecurityMetadataSource obtainSecurityMetadataSource() {\n\t\treturn this.securityMetadataSource;\n\t}\n\n\tpublic void setSecurityMetadataSource(MethodSecurityMetadataSource newSource) {\n\t\tthis.securityMetadataSource = newSource;\n\t}\n}","smell":"data class","id":118} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.apache.fineract.portfolio.tax.handler;\n\nimport org.apache.fineract.commands.annotation.CommandType;\nimport org.apache.fineract.commands.handler.NewCommandSourceHandler;\nimport org.apache.fineract.infrastructure.core.api.JsonCommand;\nimport org.apache.fineract.infrastructure.core.data.CommandProcessingResult;\nimport org.apache.fineract.portfolio.tax.service.TaxWritePlatformService;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\n@CommandType(entity = \"TAXGROUP\", action = \"UPDATE\")\npublic class UpdateTaxGroupCommandHandler implements NewCommandSourceHandler {\n\n private final TaxWritePlatformService taxWritePlatformService;\n\n @Autowired\n public UpdateTaxGroupCommandHandler(final TaxWritePlatformService taxWritePlatformService) {\n this.taxWritePlatformService = taxWritePlatformService;\n }\n\n @Override\n public CommandProcessingResult processCommand(JsonCommand jsonCommand) {\n return this.taxWritePlatformService.updateTaxGroup(jsonCommand.entityId(), jsonCommand);\n }\n\n}","smell_code":"@Service\n@CommandType(entity = \"TAXGROUP\", action = \"UPDATE\")\npublic class UpdateTaxGroupCommandHandler implements NewCommandSourceHandler {\n\n private final TaxWritePlatformService taxWritePlatformService;\n\n @Autowired\n public UpdateTaxGroupCommandHandler(final TaxWritePlatformService taxWritePlatformService) {\n this.taxWritePlatformService = taxWritePlatformService;\n }\n\n @Override\n public CommandProcessingResult processCommand(JsonCommand jsonCommand) {\n return this.taxWritePlatformService.updateTaxGroup(jsonCommand.entityId(), jsonCommand);\n }\n\n}","smell":"data class","id":119} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2011, 2016 itemis AG (http:\/\/www.itemis.eu) and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *******************************************************************************\/\npackage org.eclipse.xtext.serializer.sequencer;\n\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.EStructuralFeature;\nimport org.eclipse.xtext.AbstractElement;\nimport org.eclipse.xtext.nodemodel.ICompositeNode;\nimport org.eclipse.xtext.nodemodel.INode;\n\nimport com.google.inject.ImplementedBy;\n\n\/**\n * @author Moritz Eysholdt - Initial contribution and API\n *\/\n@ImplementedBy(SemanticNodeProvider.class)\npublic interface ISemanticNodeProvider {\n\n\tpublic interface ISemanticNode {\n\t\tINode getNode();\n\n\t\tISemanticNode getFollower();\n\n\t\tAbstractElement getGrammarElement();\n\t}\n\n\tpublic interface INodesForEObjectProvider {\n\t\tISemanticNode getSemanticNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexInNonTransient, Object value);\n\n\t\tISemanticNode getSemanticNodeForSingelValue(EStructuralFeature feature, Object value);\n\n\t\tISemanticNode getFirstSemanticNode();\n\n\t\tINode getNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexInNonTransient, Object value);\n\n\t\tINode getNodeForSingelValue(EStructuralFeature feature, Object value);\n\t}\n\n\tpublic class NullNodesForEObjectProvider implements INodesForEObjectProvider {\n\t\t@Override\n\t\tpublic INode getNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexAmongNonTransient,\n\t\t\t\tObject value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic INode getNodeForSingelValue(EStructuralFeature feature, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getSemanticNodeForMultiValue(EStructuralFeature feature, int indexInFeature,\n\t\t\t\tint indexInNonTransient, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getSemanticNodeForSingelValue(EStructuralFeature feature, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getFirstSemanticNode() {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic INodesForEObjectProvider NULL_NODES_PROVIDER = new NullNodesForEObjectProvider();\n\n\tINodesForEObjectProvider getNodesForSemanticObject(EObject semanticObject, ICompositeNode suggestedComposite);\n\n}","smell_code":"@ImplementedBy(SemanticNodeProvider.class)\npublic interface ISemanticNodeProvider {\n\n\tpublic interface ISemanticNode {\n\t\tINode getNode();\n\n\t\tISemanticNode getFollower();\n\n\t\tAbstractElement getGrammarElement();\n\t}\n\n\tpublic interface INodesForEObjectProvider {\n\t\tISemanticNode getSemanticNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexInNonTransient, Object value);\n\n\t\tISemanticNode getSemanticNodeForSingelValue(EStructuralFeature feature, Object value);\n\n\t\tISemanticNode getFirstSemanticNode();\n\n\t\tINode getNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexInNonTransient, Object value);\n\n\t\tINode getNodeForSingelValue(EStructuralFeature feature, Object value);\n\t}\n\n\tpublic class NullNodesForEObjectProvider implements INodesForEObjectProvider {\n\t\t@Override\n\t\tpublic INode getNodeForMultiValue(EStructuralFeature feature, int indexInFeature, int indexAmongNonTransient,\n\t\t\t\tObject value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic INode getNodeForSingelValue(EStructuralFeature feature, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getSemanticNodeForMultiValue(EStructuralFeature feature, int indexInFeature,\n\t\t\t\tint indexInNonTransient, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getSemanticNodeForSingelValue(EStructuralFeature feature, Object value) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic ISemanticNode getFirstSemanticNode() {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic INodesForEObjectProvider NULL_NODES_PROVIDER = new NullNodesForEObjectProvider();\n\n\tINodesForEObjectProvider getNodesForSemanticObject(EObject semanticObject, ICompositeNode suggestedComposite);\n\n}","smell":"data class","id":120} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.pig.piggybank.storage;\n\nimport org.apache.pig.LoadMetadata;\nimport org.apache.pig.StoreMetadata;\nimport org.apache.pig.builtin.PigStorage;\n\n\/**\n * This Load\/Store Func reads\/writes metafiles that allow the schema and\n * aliases to be determined at load time, saving one from having to manually\n * enter schemas for pig-generated datasets.\n *\n * It also creates a \".pig_headers\" file that simply lists the delimited aliases.\n * This is intended to make export to tools that can read files with header\n * lines easier (just cat the header to your data).\n * @deprecated Use PigStorage with a -schema option instead\n *\/\n@Deprecated\npublic class PigStorageSchema extends PigStorage implements LoadMetadata, StoreMetadata {\n public PigStorageSchema() {\n this(\"\\t\");\n }\n\n public PigStorageSchema(String delim) {\n super(delim, \"-schema\");\n }\n}","smell_code":"@Deprecated\npublic class PigStorageSchema extends PigStorage implements LoadMetadata, StoreMetadata {\n public PigStorageSchema() {\n this(\"\\t\");\n }\n\n public PigStorageSchema(String delim) {\n super(delim, \"-schema\");\n }\n}","smell":"data class","id":121} {"lang_cluster":"Java","source_code":"\/*\nCopyright 2011-2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage com.google.security.zynamics.reil.translators.mips;\n\nimport com.google.security.zynamics.reil.ReilHelpers;\nimport com.google.security.zynamics.reil.ReilInstruction;\nimport com.google.security.zynamics.reil.translators.IInstructionTranslator;\nimport com.google.security.zynamics.reil.translators.ITranslationEnvironment;\nimport com.google.security.zynamics.reil.translators.InternalTranslationException;\nimport com.google.security.zynamics.reil.translators.TranslationHelpers;\nimport com.google.security.zynamics.zylib.disassembly.IInstruction;\n\nimport java.util.List;\n\n\npublic class ExtTranslator implements IInstructionTranslator {\n @Override\n public void translate(final ITranslationEnvironment environment, final IInstruction instruction,\n final List instructions) throws InternalTranslationException {\n TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, \"ext\");\n\n final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong();\n instructions.add(ReilHelpers.createUnknown(baseOffset));\n \/\/ TODO final String todo = \"\";\n }\n}","smell_code":"public class ExtTranslator implements IInstructionTranslator {\n @Override\n public void translate(final ITranslationEnvironment environment, final IInstruction instruction,\n final List instructions) throws InternalTranslationException {\n TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, \"ext\");\n\n final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong();\n instructions.add(ReilHelpers.createUnknown(baseOffset));\n \/\/ TODO final String todo = \"\";\n }\n}","smell":"data class","id":122} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.accumulo.testing.performance.impl;\n\nimport java.io.BufferedReader;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n\nimport org.apache.accumulo.testing.performance.Result;\n\nimport com.google.common.collect.Sets;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonStreamParser;\n\npublic class Compare {\n\n private static class TestId {\n\n final String testClass;\n final String id;\n\n public TestId(String testClass, String id) {\n this.testClass = testClass;\n this.id = id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(testClass, id);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n\n if (obj instanceof TestId) {\n TestId other = (TestId) obj;\n\n return id.equals(other.id) && testClass.equals(other.testClass);\n }\n\n return false;\n }\n }\n\n public static void main(String[] args) throws Exception {\n Map oldResults = flatten(readReports(args[0]));\n Map newResults = flatten(readReports(args[1]));\n\n for (TestId testId : Sets.union(oldResults.keySet(), newResults.keySet())) {\n Double oldResult = oldResults.get(testId);\n Double newResult = newResults.get(testId);\n\n if (oldResult == null || newResult == null) {\n System.out.printf(\"%s %s %.2f %.2f\\n\", testId.testClass, testId.id, oldResult, newResult);\n } else {\n double change = (newResult - oldResult) \/ oldResult;\n System.out.printf(\"%s %s %.2f %.2f %.2f%s\\n\", testId.testClass, testId.id, oldResult,\n newResult, change * 100, \"%\");\n }\n }\n }\n\n static Collection readReports(String file) throws Exception {\n try (BufferedReader reader = Files.newBufferedReader(Paths.get(file))) {\n Gson gson = new GsonBuilder().create();\n JsonStreamParser p = new JsonStreamParser(reader);\n List rl = new ArrayList<>();\n\n while (p.hasNext()) {\n JsonElement e = p.next();\n ContextualReport results = gson.fromJson(e, ContextualReport.class);\n rl.add(results);\n }\n\n return rl;\n }\n }\n\n private static Map flatten(Collection results) {\n HashMap flattened = new HashMap<>();\n\n for (ContextualReport cr : results) {\n for (Result r : cr.results) {\n if (r.purpose == Result.Purpose.COMPARISON) {\n flattened.put(new TestId(cr.testClass, r.id), r.data.doubleValue());\n }\n }\n }\n\n return flattened;\n }\n}","smell_code":" private static class TestId {\n\n final String testClass;\n final String id;\n\n public TestId(String testClass, String id) {\n this.testClass = testClass;\n this.id = id;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(testClass, id);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n\n if (obj instanceof TestId) {\n TestId other = (TestId) obj;\n\n return id.equals(other.id) && testClass.equals(other.testClass);\n }\n\n return false;\n }\n }","smell":"data class","id":123} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.jena.hadoop.rdf.io.input.readers;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.io.LongWritable;\nimport org.apache.hadoop.mapreduce.RecordReader;\nimport org.apache.jena.graph.Node ;\nimport org.apache.jena.hadoop.rdf.io.registry.HadoopRdfIORegistry;\nimport org.apache.jena.hadoop.rdf.types.QuadWritable;\nimport org.apache.jena.riot.Lang;\nimport org.apache.jena.riot.RDFLanguages;\nimport org.apache.jena.sparql.core.Quad ;\n\n\/**\n * A record reader that reads RDF from any triples\/quads format. Triples are\n * converted into quads in the default graph. This behaviour can be changed by\n * deriving from this class and overriding the {@link #getGraphNode()} method\n * \n * \n * \n *\/\npublic class TriplesOrQuadsReader extends AbstractRdfReader {\n\n @Override\n protected RecordReader selectRecordReader(Lang lang) throws IOException {\n if (!RDFLanguages.isQuads(lang) && !RDFLanguages.isTriples(lang))\n throw new IOException(lang.getLabel() + \" is not a RDF triples\/quads format\");\n\n if (HadoopRdfIORegistry.hasQuadReader(lang)) {\n \/\/ Supports quads directly\n return HadoopRdfIORegistry.createQuadReader(lang);\n } else {\n \/\/ Try to create a triples reader and wrap upwards into quads\n \/\/ This will throw an error if a triple reader is not available\n return new TriplesToQuadsReader(HadoopRdfIORegistry.createTripleReader(lang));\n }\n }\n\n \/**\n * Gets the graph node which represents the graph into which triples will be\n * indicated to belong to when they are converting into quads.\n *

\n * Defaults to {@link Quad#defaultGraphNodeGenerated} which represents the\n * default graph\n * <\/p>\n * \n * @return Graph node\n *\/\n protected Node getGraphNode() {\n return Quad.defaultGraphNodeGenerated;\n }\n}","smell_code":"public class TriplesOrQuadsReader extends AbstractRdfReader {\n\n @Override\n protected RecordReader selectRecordReader(Lang lang) throws IOException {\n if (!RDFLanguages.isQuads(lang) && !RDFLanguages.isTriples(lang))\n throw new IOException(lang.getLabel() + \" is not a RDF triples\/quads format\");\n\n if (HadoopRdfIORegistry.hasQuadReader(lang)) {\n \/\/ Supports quads directly\n return HadoopRdfIORegistry.createQuadReader(lang);\n } else {\n \/\/ Try to create a triples reader and wrap upwards into quads\n \/\/ This will throw an error if a triple reader is not available\n return new TriplesToQuadsReader(HadoopRdfIORegistry.createTripleReader(lang));\n }\n }\n\n \/**\n * Gets the graph node which represents the graph into which triples will be\n * indicated to belong to when they are converting into quads.\n *

\n * Defaults to {@link Quad#defaultGraphNodeGenerated} which represents the\n * default graph\n * <\/p>\n * \n * @return Graph node\n *\/\n protected Node getGraphNode() {\n return Quad.defaultGraphNodeGenerated;\n }\n}","smell":"data class","id":124} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed\n * under the License is distributed on an \"AS IS\" BASIS, without warranties or\n * conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the\n * specific language governing permissions and limitations under the License.\n *\/\n\npackage com.vmware.xenon.common.jwt;\n\nimport com.google.gson.annotations.SerializedName;\n\n\/**\n * JSON Web Signature (JWS) Header.\n *\n * See: https:\/\/tools.ietf.org\/html\/rfc7515\n *\/\npublic class Header {\n @SerializedName(\"typ\")\n public String type;\n @SerializedName(\"alg\")\n public String algorithm;\n @SerializedName(\"cty\")\n public String contentType;\n}","smell_code":"public class Header {\n @SerializedName(\"typ\")\n public String type;\n @SerializedName(\"alg\")\n public String algorithm;\n @SerializedName(\"cty\")\n public String contentType;\n}","smell":"data class","id":125} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2017 Eurotech and\/or its affiliates and others\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * Eurotech\n *******************************************************************************\/\npackage org.eclipse.kapua.service.datastore.steps;\n\npublic class TestTopic {\n\n private String topic;\n\n private String clientId;\n\n private String captured;\n\n public String getTopic() {\n return topic;\n }\n\n public void setTopic(String topic) {\n this.topic = topic;\n }\n\n public String getClientId() {\n return clientId;\n }\n\n public void setClientId(String clientId) {\n this.clientId = clientId;\n }\n\n public String getCaptured() {\n return captured;\n }\n\n public void setCaptured(String captured) {\n this.captured = captured;\n }\n}","smell_code":"public class TestTopic {\n\n private String topic;\n\n private String clientId;\n\n private String captured;\n\n public String getTopic() {\n return topic;\n }\n\n public void setTopic(String topic) {\n this.topic = topic;\n }\n\n public String getClientId() {\n return clientId;\n }\n\n public void setClientId(String clientId) {\n this.clientId = clientId;\n }\n\n public String getCaptured() {\n return captured;\n }\n\n public void setCaptured(String captured) {\n this.captured = captured;\n }\n}","smell":"blob","id":126} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.sis.internal.jaxb.geometry;\n\nimport javax.xml.bind.JAXBElement;\nimport javax.xml.bind.annotation.XmlElementRef;\nimport javax.xml.bind.annotation.adapters.XmlAdapter;\nimport org.opengis.geometry.Geometry;\nimport org.apache.sis.xml.Namespaces;\n\n\n\/**\n * JAXB adapter for {@link Geometry}, in order to integrate the value in an element complying with OGC\/ISO standard.\n * The geometry element names are usually prefixed by {@code gml:}.\n *\n *

The default implementation does almost nothing. The geometry objects will not<\/strong>\n * create the expected {@link JAXBElement} type. This class is only a hook to be extended by more\n * specialized subclasses in GML modules.<\/p>\n *\n * @author Guilhem Legal (Geomatys)\n * @version 0.3\n * @since 0.3\n * @module\n *\/\npublic class GM_Object extends XmlAdapter {\n \/**\n * The Geometry value covered by a {@code gml:**} element.\n *\/\n @XmlElementRef(name = \"AbstractGeometry\", namespace = Namespaces.GML, type = JAXBElement.class)\n protected JAXBElement geometry;\n\n \/**\n * Empty constructor for JAXB and subclasses only.\n *\/\n public GM_Object() {\n }\n\n \/**\n * Converts an adapter read from an XML stream to the GeoAPI interface which will\n * contains this value. JAXB calls automatically this method at unmarshalling time.\n *\n * @param value the adapter for a geometry value.\n * @return an instance of the GeoAPI interface which represents the geometry value.\n *\/\n @Override\n public final Geometry unmarshal(final GM_Object value) {\n if (value != null) {\n final JAXBElement g = value.geometry;\n if (g != null) {\n return g.getValue();\n }\n }\n return null;\n }\n\n \/**\n * Converts a GeoAPI interface to the appropriate adapter for the way it will be\n * marshalled into an XML file or stream. JAXB calls automatically this method at\n * marshalling time.\n *\n * @param value the geometry value, here the interface.\n * @return the adapter for the given value.\n *\/\n @Override\n public final GM_Object marshal(final Geometry value) {\n if (value == null) {\n return null;\n }\n return wrap(value);\n }\n\n \/**\n * Returns the geometry value to be covered by a {@code gml:**} element.\n * The default implementation returns {@code null} if all cases. Subclasses\n * must override this method in order to provide useful marshalling.\n *\n * @param value the value to marshal.\n * @return the adapter which covers the geometry value.\n *\/\n protected GM_Object wrap(Geometry value) {\n return null;\n }\n}","smell_code":"public class GM_Object extends XmlAdapter {\n \/**\n * The Geometry value covered by a {@code gml:**} element.\n *\/\n @XmlElementRef(name = \"AbstractGeometry\", namespace = Namespaces.GML, type = JAXBElement.class)\n protected JAXBElement geometry;\n\n \/**\n * Empty constructor for JAXB and subclasses only.\n *\/\n public GM_Object() {\n }\n\n \/**\n * Converts an adapter read from an XML stream to the GeoAPI interface which will\n * contains this value. JAXB calls automatically this method at unmarshalling time.\n *\n * @param value the adapter for a geometry value.\n * @return an instance of the GeoAPI interface which represents the geometry value.\n *\/\n @Override\n public final Geometry unmarshal(final GM_Object value) {\n if (value != null) {\n final JAXBElement g = value.geometry;\n if (g != null) {\n return g.getValue();\n }\n }\n return null;\n }\n\n \/**\n * Converts a GeoAPI interface to the appropriate adapter for the way it will be\n * marshalled into an XML file or stream. JAXB calls automatically this method at\n * marshalling time.\n *\n * @param value the geometry value, here the interface.\n * @return the adapter for the given value.\n *\/\n @Override\n public final GM_Object marshal(final Geometry value) {\n if (value == null) {\n return null;\n }\n return wrap(value);\n }\n\n \/**\n * Returns the geometry value to be covered by a {@code gml:**} element.\n * The default implementation returns {@code null} if all cases. Subclasses\n * must override this method in order to provide useful marshalling.\n *\n * @param value the value to marshal.\n * @return the adapter which covers the geometry value.\n *\/\n protected GM_Object wrap(Geometry value) {\n return null;\n }\n}","smell":"blob","id":127} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2011 Google Inc.\n *\n * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse\n * Public License v1.0 which accompanies this distribution, and is available at\n *\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\npackage com.google.eclipse.protobuf.junit.core;\n\nimport static java.util.regex.Pattern.compile;\n\nimport static com.google.eclipse.protobuf.junit.core.GeneratedProtoFiles.ensureParentDirectoryExists;\nimport static com.google.eclipse.protobuf.junit.core.GeneratedProtoFiles.protoFile;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStreamWriter;\nimport java.io.Writer;\nimport java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n\/**\n * @author alruiz@google.com (Alex Ruiz)\n *\/\nclass FileCreator {\n private static final Pattern CREATE_FILE_PATTERN = compile(\"\/\/ Create file (.*)\");\n\n File createFileFrom(String comment) {\n String fileName = null;\n try (Scanner scanner = new Scanner(comment)) {\n\t while (scanner.hasNextLine()) {\n\t String line = scanner.nextLine();\n\t Matcher matcher = CREATE_FILE_PATTERN.matcher(line);\n\t if (!matcher.matches()) {\n\t return null;\n\t }\n\t fileName = matcher.group(1);\n\t break;\n\t }\n }\n return createFile(fileName, comment);\n }\n\n private File createFile(String fileName, String contents) {\n ensureParentDirectoryExists();\n File file = protoFile(fileName);\n if (file.isFile()) {\n file.delete();\n }\n Writer out = null;\n try {\n out = new OutputStreamWriter(new FileOutputStream(file));\n out.write(contents);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n closeQuietly(out);\n }\n return file;\n }\n\n private void closeQuietly(Writer out) {\n if (out == null) {\n return;\n }\n try {\n out.close();\n } catch (IOException e) {}\n }\n}","smell_code":"class FileCreator {\n private static final Pattern CREATE_FILE_PATTERN = compile(\"\/\/ Create file (.*)\");\n\n File createFileFrom(String comment) {\n String fileName = null;\n try (Scanner scanner = new Scanner(comment)) {\n\t while (scanner.hasNextLine()) {\n\t String line = scanner.nextLine();\n\t Matcher matcher = CREATE_FILE_PATTERN.matcher(line);\n\t if (!matcher.matches()) {\n\t return null;\n\t }\n\t fileName = matcher.group(1);\n\t break;\n\t }\n }\n return createFile(fileName, comment);\n }\n\n private File createFile(String fileName, String contents) {\n ensureParentDirectoryExists();\n File file = protoFile(fileName);\n if (file.isFile()) {\n file.delete();\n }\n Writer out = null;\n try {\n out = new OutputStreamWriter(new FileOutputStream(file));\n out.write(contents);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n closeQuietly(out);\n }\n return file;\n }\n\n private void closeQuietly(Writer out) {\n if (out == null) {\n return;\n }\n try {\n out.close();\n } catch (IOException e) {}\n }\n}","smell":"blob","id":128} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2014, 2018, Oracle and\/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 3 only, as\n * published by the Free Software Foundation.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 3 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 3 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n *\/\npackage com.oracle.truffle.r.runtime.conn;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.lang.ProcessBuilder.Redirect;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.ByteChannel;\nimport java.nio.channels.Channels;\nimport java.nio.channels.ReadableByteChannel;\nimport java.nio.channels.WritableByteChannel;\n\nimport com.oracle.truffle.r.runtime.RError;\nimport com.oracle.truffle.r.runtime.conn.ConnectionSupport.AbstractOpenMode;\nimport com.oracle.truffle.r.runtime.conn.ConnectionSupport.BaseRConnection;\nimport com.oracle.truffle.r.runtime.conn.ConnectionSupport.ConnectionClass;\n\npublic class PipeConnections {\n\n private static Process executeAndJoin(String command) throws IOException {\n ProcessBuilder pb = new ProcessBuilder(\"\/bin\/sh\", \"-c\", command);\n pb.redirectError(Redirect.INHERIT);\n Process p = pb.start();\n try {\n p.waitFor();\n } catch (InterruptedException e) {\n \/\/ TODO not sure how to handle an interrupted exception at this point\n }\n return p;\n }\n\n public static class PipeRConnection extends BaseRConnection {\n\n private final String command;\n\n public PipeRConnection(String command, String open, String encoding) throws IOException {\n super(ConnectionClass.FIFO, open, AbstractOpenMode.Read, encoding);\n this.command = command;\n openNonLazyConnection();\n }\n\n @Override\n protected void createDelegateConnection() throws IOException {\n final DelegateRConnection delegate;\n switch (getOpenMode().abstractOpenMode) {\n case Read:\n case ReadBinary:\n delegate = new PipeReadRConnection(this, command);\n break;\n case Write:\n case WriteBinary:\n delegate = new PipeWriteConnection(this, command);\n break;\n case ReadAppend:\n case ReadWrite:\n case ReadWriteBinary:\n case ReadWriteTrunc:\n case ReadWriteTruncBinary:\n delegate = new PipeReadWriteConnection(this, command);\n break;\n default:\n throw RError.nyi(RError.SHOW_CALLER2, \"open mode: \" + getOpenMode());\n }\n setDelegate(delegate);\n }\n\n @Override\n public String getSummaryDescription() {\n return command;\n }\n }\n\n static class PipeReadRConnection extends DelegateReadRConnection {\n private final ByteChannel channel;\n\n protected PipeReadRConnection(BaseRConnection base, String command) throws IOException {\n super(base);\n Process p = PipeConnections.executeAndJoin(command);\n channel = ConnectionSupport.newChannel(p.getInputStream());\n }\n\n @Override\n public ByteChannel getChannel() {\n return channel;\n }\n\n @Override\n public boolean isSeekable() {\n return false;\n }\n }\n\n private static class PipeWriteConnection extends DelegateWriteRConnection {\n private final ByteChannel channel;\n\n PipeWriteConnection(BaseRConnection base, String command) throws IOException {\n super(base);\n Process p = PipeConnections.executeAndJoin(command);\n channel = ConnectionSupport.newChannel(p.getOutputStream());\n }\n\n @Override\n public ByteChannel getChannel() {\n return channel;\n }\n\n @Override\n public boolean isSeekable() {\n return false;\n }\n }\n\n private static class PipeReadWriteConnection extends DelegateReadWriteRConnection {\n\n private final RWChannel channel;\n\n protected PipeReadWriteConnection(BaseRConnection base, String command) throws IOException {\n super(base);\n Process p = PipeConnections.executeAndJoin(command);\n channel = new RWChannel(p.getInputStream(), p.getOutputStream());\n }\n\n @Override\n public ByteChannel getChannel() {\n return channel;\n }\n\n @Override\n public boolean isSeekable() {\n return false;\n }\n\n private static final class RWChannel implements ByteChannel {\n private final ReadableByteChannel rchannel;\n private final WritableByteChannel wchannel;\n\n RWChannel(InputStream in, OutputStream out) {\n rchannel = Channels.newChannel(in);\n wchannel = Channels.newChannel(out);\n }\n\n @Override\n public int read(ByteBuffer dst) throws IOException {\n return rchannel.read(dst);\n }\n\n @Override\n public boolean isOpen() {\n return rchannel.isOpen() && wchannel.isOpen();\n }\n\n @Override\n public void close() throws IOException {\n rchannel.close();\n wchannel.close();\n }\n\n @Override\n public int write(ByteBuffer src) throws IOException {\n return wchannel.write(src);\n }\n }\n\n }\n}","smell_code":" static class PipeReadRConnection extends DelegateReadRConnection {\n private final ByteChannel channel;\n\n protected PipeReadRConnection(BaseRConnection base, String command) throws IOException {\n super(base);\n Process p = PipeConnections.executeAndJoin(command);\n channel = ConnectionSupport.newChannel(p.getInputStream());\n }\n\n @Override\n public ByteChannel getChannel() {\n return channel;\n }\n\n @Override\n public boolean isSeekable() {\n return false;\n }\n }","smell":"blob","id":129} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.apache.sshd.git.pgm;\n\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Path;\nimport java.util.List;\n\nimport org.apache.sshd.common.util.ValidateUtils;\nimport org.apache.sshd.common.util.threads.CloseableExecutorService;\nimport org.apache.sshd.git.AbstractGitCommand;\nimport org.apache.sshd.git.GitLocationResolver;\nimport org.apache.sshd.server.Environment;\n\n\/**\n * TODO Add javadoc\n *\n * @author Apache MINA SSHD Project<\/a>\n *\/\npublic class GitPgmCommand extends AbstractGitCommand {\n \/**\n * @param rootDirResolver Resolver for GIT root directory\n * @param command Command to execute\n * @param executorService An {@link CloseableExecutorService} to be used when {@link #start(Environment)}-ing\n * execution. If {@code null} an ad-hoc single-threaded service is created and used.\n *\/\n public GitPgmCommand(GitLocationResolver rootDirResolver, String command, CloseableExecutorService executorService) {\n super(rootDirResolver, command, executorService);\n }\n\n @Override\n public void run() {\n String command = getCommand();\n OutputStream err = getErrorStream();\n try {\n List strs = parseDelimitedString(command, \" \", true);\n String[] args = strs.toArray(new String[strs.size()]);\n for (int i = 0; i < args.length; i++) {\n String argVal = args[i];\n if (argVal.startsWith(\"'\") && argVal.endsWith(\"'\")) {\n args[i] = argVal.substring(1, argVal.length() - 1);\n argVal = args[i];\n }\n\n if (argVal.startsWith(\"\\\"\") && argVal.endsWith(\"\\\"\")) {\n args[i] = argVal.substring(1, argVal.length() - 1);\n argVal = args[i];\n }\n }\n\n GitLocationResolver resolver = getGitLocationResolver();\n Path rootDir = resolver.resolveRootDirectory(command, args, getServerSession(), getFileSystem());\n ValidateUtils.checkState(rootDir != null, \"No root directory provided for %s command\", command);\n\n new EmbeddedCommandRunner(rootDir).execute(args, getInputStream(), getOutputStream(), err);\n onExit(0);\n } catch (Throwable t) {\n try {\n err.write((t.getMessage() + \"\\n\").getBytes(StandardCharsets.UTF_8));\n err.flush();\n } catch (IOException e) {\n log.warn(\"Failed {} to flush command={} failure: {}\",\n e.getClass().getSimpleName(), command, e.getMessage());\n }\n onExit(-1, t.getMessage());\n }\n }\n}","smell_code":"public class GitPgmCommand extends AbstractGitCommand {\n \/**\n * @param rootDirResolver Resolver for GIT root directory\n * @param command Command to execute\n * @param executorService An {@link CloseableExecutorService} to be used when {@link #start(Environment)}-ing\n * execution. If {@code null} an ad-hoc single-threaded service is created and used.\n *\/\n public GitPgmCommand(GitLocationResolver rootDirResolver, String command, CloseableExecutorService executorService) {\n super(rootDirResolver, command, executorService);\n }\n\n @Override\n public void run() {\n String command = getCommand();\n OutputStream err = getErrorStream();\n try {\n List strs = parseDelimitedString(command, \" \", true);\n String[] args = strs.toArray(new String[strs.size()]);\n for (int i = 0; i < args.length; i++) {\n String argVal = args[i];\n if (argVal.startsWith(\"'\") && argVal.endsWith(\"'\")) {\n args[i] = argVal.substring(1, argVal.length() - 1);\n argVal = args[i];\n }\n\n if (argVal.startsWith(\"\\\"\") && argVal.endsWith(\"\\\"\")) {\n args[i] = argVal.substring(1, argVal.length() - 1);\n argVal = args[i];\n }\n }\n\n GitLocationResolver resolver = getGitLocationResolver();\n Path rootDir = resolver.resolveRootDirectory(command, args, getServerSession(), getFileSystem());\n ValidateUtils.checkState(rootDir != null, \"No root directory provided for %s command\", command);\n\n new EmbeddedCommandRunner(rootDir).execute(args, getInputStream(), getOutputStream(), err);\n onExit(0);\n } catch (Throwable t) {\n try {\n err.write((t.getMessage() + \"\\n\").getBytes(StandardCharsets.UTF_8));\n err.flush();\n } catch (IOException e) {\n log.warn(\"Failed {} to flush command={} failure: {}\",\n e.getClass().getSimpleName(), command, e.getMessage());\n }\n onExit(-1, t.getMessage());\n }\n }\n}","smell":"blob","id":130} {"lang_cluster":"Java","source_code":"package org.apache.helix.controller.pipeline;\n\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npublic class StageException extends Exception {\n\n public StageException(String message) {\n super(message);\n }\n\n public StageException(String message, Exception e) {\n super(message, e);\n }\n}","smell_code":"public class StageException extends Exception {\n\n public StageException(String message) {\n super(message);\n }\n\n public StageException(String message, Exception e) {\n super(message, e);\n }\n}","smell":"blob","id":131} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) Microsoft Corporation\n * \n * All rights reserved.\n * \n * MIT License\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and\n * to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n * the Software.\n * \n * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\n * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\npackage com.microsoft.tooling.msservices.serviceexplorer;\n\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class NodeAction {\n private String name;\n private boolean enabled = true;\n private List listeners = new ArrayList();\n private Node node; \/\/ the node with which this action is associated\n private String iconPath;\n\n public NodeAction(Node node, String name) {\n this.node = node;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void addListener(NodeActionListener listener) {\n listeners.add(listener);\n }\n\n public List getListeners() {\n return listeners;\n }\n\n public void fireNodeActionEvent() {\n if (!listeners.isEmpty()) {\n final NodeActionEvent event = new NodeActionEvent(this);\n for (final NodeActionListener listener : listeners) {\n listener.beforeActionPerformed(event);\n Futures.addCallback(listener.actionPerformedAsync(event), new FutureCallback() {\n @Override\n public void onSuccess(Void aVoid) {\n listener.afterActionPerformed(event);\n }\n\n @Override\n public void onFailure(Throwable throwable) {\n listener.afterActionPerformed(event);\n }\n });\n }\n }\n }\n\n public Node getNode() {\n return node;\n }\n\n public boolean isEnabled() {\n \/\/ if the node to which this action is attached is in a\n \/\/ \"loading\" state then we disable the action regardless\n \/\/ of what \"enabled\" is\n return !node.isLoading() && enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public String getIconPath() {\n return iconPath;\n }\n\n public void setIconPath(String iconPath) {\n this.iconPath = iconPath;\n }\n}","smell_code":"public class NodeAction {\n private String name;\n private boolean enabled = true;\n private List listeners = new ArrayList();\n private Node node; \/\/ the node with which this action is associated\n private String iconPath;\n\n public NodeAction(Node node, String name) {\n this.node = node;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void addListener(NodeActionListener listener) {\n listeners.add(listener);\n }\n\n public List getListeners() {\n return listeners;\n }\n\n public void fireNodeActionEvent() {\n if (!listeners.isEmpty()) {\n final NodeActionEvent event = new NodeActionEvent(this);\n for (final NodeActionListener listener : listeners) {\n listener.beforeActionPerformed(event);\n Futures.addCallback(listener.actionPerformedAsync(event), new FutureCallback() {\n @Override\n public void onSuccess(Void aVoid) {\n listener.afterActionPerformed(event);\n }\n\n @Override\n public void onFailure(Throwable throwable) {\n listener.afterActionPerformed(event);\n }\n });\n }\n }\n }\n\n public Node getNode() {\n return node;\n }\n\n public boolean isEnabled() {\n \/\/ if the node to which this action is attached is in a\n \/\/ \"loading\" state then we disable the action regardless\n \/\/ of what \"enabled\" is\n return !node.isLoading() && enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public String getIconPath() {\n return iconPath;\n }\n\n public void setIconPath(String iconPath) {\n this.iconPath = iconPath;\n }\n}","smell":"blob","id":132} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/* $Id$ *\/\n\npackage org.apache.xmlgraphics.java2d;\n\nimport java.awt.image.VolatileImage;\n\n\/**\n * Adapter to allow subclassing java.awt.GraphicsConfiguration without\n * compilation errors.\n * The version for JDK 1.4 needs to add an override for the abstract\n * createCompatibleVolatileImage() method. It can't be overidden\n * for JDK 1.3 because there is no VolatileImage there.\n *\n *\/\npublic abstract class AbstractGraphicsConfiguration extends java.awt.GraphicsConfiguration {\n\n \/**\n * @see java.awt.GraphicsConfiguration#createCompatibleVolatileImage(int, int)\n * @since JDK 1.4\n *\/\n public VolatileImage createCompatibleVolatileImage(int width, int height) {\n return null;\n }\n\n \/**\n * @see java.awt.GraphicsConfiguration#createCompatibleVolatileImage(int, int, int)\n * @since JDK 1.5\n *\/\n public VolatileImage createCompatibleVolatileImage(int width, int height, int transparency) {\n return null;\n }\n\n}","smell_code":"public abstract class AbstractGraphicsConfiguration extends java.awt.GraphicsConfiguration {\n\n \/**\n * @see java.awt.GraphicsConfiguration#createCompatibleVolatileImage(int, int)\n * @since JDK 1.4\n *\/\n public VolatileImage createCompatibleVolatileImage(int width, int height) {\n return null;\n }\n\n \/**\n * @see java.awt.GraphicsConfiguration#createCompatibleVolatileImage(int, int, int)\n * @since JDK 1.5\n *\/\n public VolatileImage createCompatibleVolatileImage(int width, int height, int transparency) {\n return null;\n }\n\n}","smell":"blob","id":133} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\npackage org.apache.ivyde.internal.eclipse.validator;\n\npublic interface IValidationReaction {\n\n void ok();\n\n void error();\n}","smell_code":"public interface IValidationReaction {\n\n void ok();\n\n void error();\n}","smell":"blob","id":134} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage org.apache.asterix.runtime.aggregates.std;\n\nimport org.apache.asterix.om.functions.BuiltinFunctions;\nimport org.apache.asterix.om.functions.IFunctionDescriptor;\nimport org.apache.asterix.om.functions.IFunctionDescriptorFactory;\nimport org.apache.asterix.runtime.aggregates.base.AbstractAggregateFunctionDynamicDescriptor;\nimport org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;\nimport org.apache.hyracks.algebricks.runtime.base.IAggregateEvaluator;\nimport org.apache.hyracks.algebricks.runtime.base.IAggregateEvaluatorFactory;\nimport org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;\nimport org.apache.hyracks.api.context.IHyracksTaskContext;\nimport org.apache.hyracks.api.exceptions.HyracksDataException;\n\npublic class GlobalSqlStddevPopAggregateDescriptor extends AbstractAggregateFunctionDynamicDescriptor {\n\n private static final long serialVersionUID = 1L;\n\n public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {\n @Override\n public IFunctionDescriptor createFunctionDescriptor() {\n return new GlobalSqlStddevPopAggregateDescriptor();\n }\n };\n\n @Override\n public FunctionIdentifier getIdentifier() {\n return BuiltinFunctions.GLOBAL_SQL_STDDEV_POP;\n }\n\n @Override\n public IAggregateEvaluatorFactory createAggregateEvaluatorFactory(final IScalarEvaluatorFactory[] args) {\n return new IAggregateEvaluatorFactory() {\n private static final long serialVersionUID = 1L;\n\n @Override\n public IAggregateEvaluator createAggregateEvaluator(final IHyracksTaskContext ctx)\n throws HyracksDataException {\n return new GlobalSqlStddevAggregateFunction(args, ctx, true, sourceLoc);\n }\n };\n }\n\n}","smell_code":"public class GlobalSqlStddevPopAggregateDescriptor extends AbstractAggregateFunctionDynamicDescriptor {\n\n private static final long serialVersionUID = 1L;\n\n public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {\n @Override\n public IFunctionDescriptor createFunctionDescriptor() {\n return new GlobalSqlStddevPopAggregateDescriptor();\n }\n };\n\n @Override\n public FunctionIdentifier getIdentifier() {\n return BuiltinFunctions.GLOBAL_SQL_STDDEV_POP;\n }\n\n @Override\n public IAggregateEvaluatorFactory createAggregateEvaluatorFactory(final IScalarEvaluatorFactory[] args) {\n return new IAggregateEvaluatorFactory() {\n private static final long serialVersionUID = 1L;\n\n @Override\n public IAggregateEvaluator createAggregateEvaluator(final IHyracksTaskContext ctx)\n throws HyracksDataException {\n return new GlobalSqlStddevAggregateFunction(args, ctx, true, sourceLoc);\n }\n };\n }\n\n}","smell":"blob","id":135} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2017 the original author or authors.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\npackage org.eclipse.buildship.core.internal.workspace;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Objects;\n\nimport org.gradle.tooling.BuildAction;\nimport org.gradle.tooling.BuildController;\nimport org.gradle.tooling.model.gradle.GradleBuild;\n\n\/**\n * Build action to query a model for all participants in a composite.\n *\n * @param The requested model type\n * @author Donat Csikos\n *\/\npublic final class CompositeModelQuery implements BuildAction> {\n\n private static final long serialVersionUID = 1L;\n\n private final Class modelType;\n\n public CompositeModelQuery(Class modelType) {\n this.modelType = modelType;\n }\n\n @Override\n public Collection execute(BuildController controller) {\n Collection models = new ArrayList<>();\n collectRootModels(controller, controller.getBuildModel(), models);\n return models;\n }\n\n private void collectRootModels(BuildController controller, GradleBuild build, Collection models) {\n models.add(controller.getModel(build.getRootProject(), this.modelType));\n\n for (GradleBuild includedBuild : build.getIncludedBuilds()) {\n collectRootModels(controller, includedBuild, models);\n }\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.modelType);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n CompositeModelQuery other = (CompositeModelQuery) obj;\n return Objects.equals(this.modelType, other.modelType);\n }\n\n\n}","smell_code":"public final class CompositeModelQuery implements BuildAction> {\n\n private static final long serialVersionUID = 1L;\n\n private final Class modelType;\n\n public CompositeModelQuery(Class modelType) {\n this.modelType = modelType;\n }\n\n @Override\n public Collection execute(BuildController controller) {\n Collection models = new ArrayList<>();\n collectRootModels(controller, controller.getBuildModel(), models);\n return models;\n }\n\n private void collectRootModels(BuildController controller, GradleBuild build, Collection models) {\n models.add(controller.getModel(build.getRootProject(), this.modelType));\n\n for (GradleBuild includedBuild : build.getIncludedBuilds()) {\n collectRootModels(controller, includedBuild, models);\n }\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.modelType);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n CompositeModelQuery other = (CompositeModelQuery) obj;\n return Objects.equals(this.modelType, other.modelType);\n }\n\n\n}","smell":"blob","id":136} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage org.apache.isis.core.metamodel.facets.value.imageawt;\n\nimport java.awt.Image;\nimport org.apache.isis.core.metamodel.facetapi.FacetHolder;\nimport org.apache.isis.core.metamodel.facets.object.value.vsp.ValueFacetUsingSemanticsProviderFactory;\n\npublic class JavaAwtImageValueFacetUsingSemanticsProviderFactory extends ValueFacetUsingSemanticsProviderFactory {\n\n public JavaAwtImageValueFacetUsingSemanticsProviderFactory() {\n super();\n }\n\n @Override\n public void process(final ProcessClassContext processClassContext) {\n final Class type = processClassContext.getCls();\n final FacetHolder holder = processClassContext.getFacetHolder();\n\n if (type != java.awt.Image.class) {\n return;\n }\n addFacets(new JavaAwtImageValueSemanticsProvider(holder, getContext()));\n }\n\n}","smell_code":"public class JavaAwtImageValueFacetUsingSemanticsProviderFactory extends ValueFacetUsingSemanticsProviderFactory {\n\n public JavaAwtImageValueFacetUsingSemanticsProviderFactory() {\n super();\n }\n\n @Override\n public void process(final ProcessClassContext processClassContext) {\n final Class type = processClassContext.getCls();\n final FacetHolder holder = processClassContext.getFacetHolder();\n\n if (type != java.awt.Image.class) {\n return;\n }\n addFacets(new JavaAwtImageValueSemanticsProvider(holder, getContext()));\n }\n\n}","smell":"blob","id":137} {"lang_cluster":"Java","source_code":"\/*\nCopyright 2011-2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage com.google.security.zynamics.reil.translators.mips;\n\nimport com.google.security.zynamics.reil.OperandSize;\nimport com.google.security.zynamics.reil.ReilHelpers;\nimport com.google.security.zynamics.reil.ReilInstruction;\nimport com.google.security.zynamics.reil.translators.IInstructionTranslator;\nimport com.google.security.zynamics.reil.translators.ITranslationEnvironment;\nimport com.google.security.zynamics.reil.translators.InternalTranslationException;\nimport com.google.security.zynamics.reil.translators.TranslationHelpers;\nimport com.google.security.zynamics.zylib.disassembly.IInstruction;\nimport com.google.security.zynamics.zylib.disassembly.IOperandTree;\nimport com.google.security.zynamics.zylib.general.Triple;\n\nimport java.util.List;\n\n\npublic class NorTranslator implements IInstructionTranslator {\n\n @Override\n public void translate(final ITranslationEnvironment environment, final IInstruction instruction,\n final List instructions) throws InternalTranslationException {\n TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, \"nor\");\n\n final Triple operands =\n OperandLoader.loadDuplicateFirst(instruction);\n final String targetRegister = operands.first().getRootNode().getChildren().get(0).getValue();\n final String sourceRegister1 = operands.second().getRootNode().getChildren().get(0).getValue();\n final String sourceRegister2 = operands.third().getRootNode().getChildren().get(0).getValue();\n\n final OperandSize dw = OperandSize.DWORD;\n\n final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong();\n long offset = baseOffset;\n\n final String temporaryOrResult = environment.getNextVariableString();\n\n instructions.add(ReilHelpers.createOr(offset++, dw, sourceRegister1, dw, sourceRegister2, dw,\n temporaryOrResult));\n instructions.add(ReilHelpers.createXor(offset, dw, temporaryOrResult, dw,\n String.valueOf(0xFFFFFFFFL), dw, targetRegister));\n }\n}","smell_code":"public class NorTranslator implements IInstructionTranslator {\n\n @Override\n public void translate(final ITranslationEnvironment environment, final IInstruction instruction,\n final List instructions) throws InternalTranslationException {\n TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, \"nor\");\n\n final Triple operands =\n OperandLoader.loadDuplicateFirst(instruction);\n final String targetRegister = operands.first().getRootNode().getChildren().get(0).getValue();\n final String sourceRegister1 = operands.second().getRootNode().getChildren().get(0).getValue();\n final String sourceRegister2 = operands.third().getRootNode().getChildren().get(0).getValue();\n\n final OperandSize dw = OperandSize.DWORD;\n\n final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong();\n long offset = baseOffset;\n\n final String temporaryOrResult = environment.getNextVariableString();\n\n instructions.add(ReilHelpers.createOr(offset++, dw, sourceRegister1, dw, sourceRegister2, dw,\n temporaryOrResult));\n instructions.add(ReilHelpers.createXor(offset, dw, temporaryOrResult, dw,\n String.valueOf(0xFFFFFFFFL), dw, targetRegister));\n }\n}","smell":"blob","id":138} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (C) 2012 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.conscrypt;\n\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.List;\n\n\/**\n * Interface for classes that implement certificate pinning for use in {@link TrustManagerImpl}.\n *\/\n@Internal\npublic interface CertPinManager {\n \/**\n * Given a {@code hostname} and a {@code chain} this verifies that the\n * certificate chain includes pinned certificates if pinning is requested\n * for {@code hostname}.\n *\/\n void checkChainPinning(String hostname, List chain)\n throws CertificateException;\n}","smell_code":"@Internal\npublic interface CertPinManager {\n \/**\n * Given a {@code hostname} and a {@code chain} this verifies that the\n * certificate chain includes pinned certificates if pinning is requested\n * for {@code hostname}.\n *\/\n void checkChainPinning(String hostname, List chain)\n throws CertificateException;\n}","smell":"blob","id":139} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more contributor license\n * agreements. See the NOTICE file distributed with this work for additional information regarding\n * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance with the License. You may obtain a\n * copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n *\/\n\npackage org.apache.fluo.core.metrics;\n\nimport com.google.common.base.Preconditions;\nimport org.apache.fluo.api.config.FluoConfiguration;\n\npublic class MetricNames {\n\n public static final String METRICS_REPORTER_ID_PROP =\n FluoConfiguration.FLUO_PREFIX + \".metrics.reporter.id\";\n\n \/\/ Metrics prefixes for 'default' metrics\n public static final String CLASS_PREFIX = FluoConfiguration.FLUO_PREFIX + \".class\";\n public static final String SYSTEM_PREFIX = FluoConfiguration.FLUO_PREFIX + \".system\";\n\n \/\/ Metrics prefix for 'application' metrics\n public static final String APPLICATION_PREFIX = FluoConfiguration.FLUO_PREFIX + \".app\";\n\n private final String txLockWaitTime;\n private final String txExecTime;\n private final String txWithCollision;\n private final String txCollisions;\n private final String txEntriesSet;\n private final String txEntriesRead;\n private final String txLocksTimedOut;\n private final String txLocksDead;\n private final String txStatusPrefix;\n private final String txCommitting;\n\n private final String notificationsQueued;\n\n private final String oracleResponseTime;\n private final String oracleClientStamps;\n private final String oracleServerStamps;\n\n public MetricNames(String metricsReporterId, String appName) {\n Preconditions.checkArgument(!appName.contains(\".\"),\n \"Fluo App name should not contain '.': \" + appName);\n Preconditions.checkArgument(!metricsReporterId.contains(\".\"),\n \"Metrics Reporter ID should not contain '.': \" + metricsReporterId);\n\n \/\/ Metrics reported for a specific class\n \/\/ FORMAT: fluo.class.APPLICATION.REPORTER_ID.METRIC.CLASS\n final String classMetric = CLASS_PREFIX + \".\" + appName + \".\" + metricsReporterId + \".\";\n txLockWaitTime = classMetric + \"tx_lock_wait_time\";\n txExecTime = classMetric + \"tx_execution_time\";\n txWithCollision = classMetric + \"tx_with_collision\";\n txCollisions = classMetric + \"tx_collisions\";\n txEntriesSet = classMetric + \"tx_entries_set\";\n txEntriesRead = classMetric + \"tx_entries_read\";\n txLocksTimedOut = classMetric + \"tx_locks_timedout\";\n txLocksDead = classMetric + \"tx_locks_dead\";\n txStatusPrefix = classMetric + \"tx_status_\"; \/\/ status appended to metric name\n\n \/\/ System-wide metrics\n \/\/ FORMAT: fluo.system.APPLICATION.REPORTER_ID.METRIC\n final String systemMetric = SYSTEM_PREFIX + \".\" + appName + \".\" + metricsReporterId + \".\";\n txCommitting = systemMetric + \"transactor_committing\";\n notificationsQueued = systemMetric + \"worker_notifications_queued\";\n oracleResponseTime = systemMetric + \"oracle_response_time\";\n oracleClientStamps = systemMetric + \"oracle_client_stamps\";\n oracleServerStamps = systemMetric + \"oracle_server_stamps\";\n }\n\n public String getTxLockWaitTime(String className) {\n return txLockWaitTime + \".\" + className;\n }\n\n public String getTxExecTime(String className) {\n return txExecTime + \".\" + className;\n }\n\n public String getTxWithCollision(String className) {\n return txWithCollision + \".\" + className;\n }\n\n public String getTxCollisions(String className) {\n return txCollisions + \".\" + className;\n }\n\n public String getTxEntriesSet(String className) {\n return txEntriesSet + \".\" + className;\n }\n\n public String getTxEntriesRead(String className) {\n return txEntriesRead + \".\" + className;\n }\n\n public String getTxLocksTimedout(String className) {\n return txLocksTimedOut + \".\" + className;\n }\n\n public String getTxLocksDead(String className) {\n return txLocksDead + \".\" + className;\n }\n\n public String getTxStatus(String status, String className) {\n return txStatusPrefix + status + \".\" + className;\n }\n\n public String getNotificationQueued() {\n return notificationsQueued;\n }\n\n public String getOracleResponseTime() {\n return oracleResponseTime;\n }\n\n public String getOracleClientStamps() {\n return oracleClientStamps;\n }\n\n public String getOracleServerStamps() {\n return oracleServerStamps;\n }\n\n public String getCommitsProcessing() {\n return txCommitting;\n }\n}","smell_code":"public class MetricNames {\n\n public static final String METRICS_REPORTER_ID_PROP =\n FluoConfiguration.FLUO_PREFIX + \".metrics.reporter.id\";\n\n \/\/ Metrics prefixes for 'default' metrics\n public static final String CLASS_PREFIX = FluoConfiguration.FLUO_PREFIX + \".class\";\n public static final String SYSTEM_PREFIX = FluoConfiguration.FLUO_PREFIX + \".system\";\n\n \/\/ Metrics prefix for 'application' metrics\n public static final String APPLICATION_PREFIX = FluoConfiguration.FLUO_PREFIX + \".app\";\n\n private final String txLockWaitTime;\n private final String txExecTime;\n private final String txWithCollision;\n private final String txCollisions;\n private final String txEntriesSet;\n private final String txEntriesRead;\n private final String txLocksTimedOut;\n private final String txLocksDead;\n private final String txStatusPrefix;\n private final String txCommitting;\n\n private final String notificationsQueued;\n\n private final String oracleResponseTime;\n private final String oracleClientStamps;\n private final String oracleServerStamps;\n\n public MetricNames(String metricsReporterId, String appName) {\n Preconditions.checkArgument(!appName.contains(\".\"),\n \"Fluo App name should not contain '.': \" + appName);\n Preconditions.checkArgument(!metricsReporterId.contains(\".\"),\n \"Metrics Reporter ID should not contain '.': \" + metricsReporterId);\n\n \/\/ Metrics reported for a specific class\n \/\/ FORMAT: fluo.class.APPLICATION.REPORTER_ID.METRIC.CLASS\n final String classMetric = CLASS_PREFIX + \".\" + appName + \".\" + metricsReporterId + \".\";\n txLockWaitTime = classMetric + \"tx_lock_wait_time\";\n txExecTime = classMetric + \"tx_execution_time\";\n txWithCollision = classMetric + \"tx_with_collision\";\n txCollisions = classMetric + \"tx_collisions\";\n txEntriesSet = classMetric + \"tx_entries_set\";\n txEntriesRead = classMetric + \"tx_entries_read\";\n txLocksTimedOut = classMetric + \"tx_locks_timedout\";\n txLocksDead = classMetric + \"tx_locks_dead\";\n txStatusPrefix = classMetric + \"tx_status_\"; \/\/ status appended to metric name\n\n \/\/ System-wide metrics\n \/\/ FORMAT: fluo.system.APPLICATION.REPORTER_ID.METRIC\n final String systemMetric = SYSTEM_PREFIX + \".\" + appName + \".\" + metricsReporterId + \".\";\n txCommitting = systemMetric + \"transactor_committing\";\n notificationsQueued = systemMetric + \"worker_notifications_queued\";\n oracleResponseTime = systemMetric + \"oracle_response_time\";\n oracleClientStamps = systemMetric + \"oracle_client_stamps\";\n oracleServerStamps = systemMetric + \"oracle_server_stamps\";\n }\n\n public String getTxLockWaitTime(String className) {\n return txLockWaitTime + \".\" + className;\n }\n\n public String getTxExecTime(String className) {\n return txExecTime + \".\" + className;\n }\n\n public String getTxWithCollision(String className) {\n return txWithCollision + \".\" + className;\n }\n\n public String getTxCollisions(String className) {\n return txCollisions + \".\" + className;\n }\n\n public String getTxEntriesSet(String className) {\n return txEntriesSet + \".\" + className;\n }\n\n public String getTxEntriesRead(String className) {\n return txEntriesRead + \".\" + className;\n }\n\n public String getTxLocksTimedout(String className) {\n return txLocksTimedOut + \".\" + className;\n }\n\n public String getTxLocksDead(String className) {\n return txLocksDead + \".\" + className;\n }\n\n public String getTxStatus(String status, String className) {\n return txStatusPrefix + status + \".\" + className;\n }\n\n public String getNotificationQueued() {\n return notificationsQueued;\n }\n\n public String getOracleResponseTime() {\n return oracleResponseTime;\n }\n\n public String getOracleClientStamps() {\n return oracleClientStamps;\n }\n\n public String getOracleServerStamps() {\n return oracleServerStamps;\n }\n\n public String getCommitsProcessing() {\n return txCommitting;\n }\n}","smell":"blob","id":140} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2013, 2018, Oracle and\/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 3 only, as\n * published by the Free Software Foundation.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 3 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 3 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n *\/\npackage com.oracle.truffle.r.nodes.control;\n\nimport com.oracle.truffle.api.Truffle;\nimport com.oracle.truffle.api.frame.VirtualFrame;\nimport com.oracle.truffle.api.nodes.LoopNode;\nimport com.oracle.truffle.api.profiles.BranchProfile;\nimport com.oracle.truffle.api.profiles.ConditionProfile;\nimport com.oracle.truffle.api.source.SourceSection;\nimport com.oracle.truffle.r.nodes.function.visibility.SetVisibilityNode;\nimport com.oracle.truffle.r.nodes.unary.ConvertBooleanNode;\nimport com.oracle.truffle.r.runtime.ArgumentsSignature;\nimport com.oracle.truffle.r.runtime.RRuntime;\nimport com.oracle.truffle.r.runtime.data.RNull;\nimport com.oracle.truffle.r.runtime.nodes.RNode;\nimport com.oracle.truffle.r.runtime.nodes.RSyntaxCall;\nimport com.oracle.truffle.r.runtime.nodes.RSyntaxElement;\nimport com.oracle.truffle.r.runtime.nodes.RSyntaxLookup;\nimport com.oracle.truffle.r.runtime.nodes.RSyntaxNode;\n\npublic final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall {\n\n @Child private LoopNode loop;\n @Child private SetVisibilityNode visibility = SetVisibilityNode.create();\n\n public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) {\n super(src, operator);\n this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode()));\n }\n\n @Override\n public Object execute(VirtualFrame frame) {\n loop.executeLoop(frame);\n visibility.execute(frame, false);\n return RNull.instance;\n }\n\n private static final class WhileRepeatingNode extends AbstractRepeatingNode {\n\n @Child private ConvertBooleanNode condition;\n\n private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile();\n private final BranchProfile normalBlock = BranchProfile.create();\n private final BranchProfile breakBlock = BranchProfile.create();\n private final BranchProfile nextBlock = BranchProfile.create();\n\n \/\/ only used for toString\n private final WhileNode whileNode;\n\n WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) {\n super(body);\n this.whileNode = whileNode;\n this.condition = condition;\n \/\/ pre-initialize the profile so that loop exits to not deoptimize\n conditionProfile.profile(false);\n }\n\n @Override\n public boolean executeRepeating(VirtualFrame frame) {\n try {\n if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) {\n body.voidExecute(frame);\n normalBlock.enter();\n return true;\n } else {\n return false;\n }\n } catch (BreakException e) {\n breakBlock.enter();\n return false;\n } catch (NextException e) {\n nextBlock.enter();\n return true;\n }\n }\n\n @Override\n public String toString() {\n return whileNode.toString();\n }\n }\n\n @Override\n public RSyntaxElement[] getSyntaxArguments() {\n WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode();\n return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()};\n }\n\n @Override\n public ArgumentsSignature getSyntaxSignature() {\n return ArgumentsSignature.empty(2);\n }\n}","smell_code":"public final class WhileNode extends AbstractLoopNode implements RSyntaxNode, RSyntaxCall {\n\n @Child private LoopNode loop;\n @Child private SetVisibilityNode visibility = SetVisibilityNode.create();\n\n public WhileNode(SourceSection src, RSyntaxLookup operator, RSyntaxNode condition, RSyntaxNode body) {\n super(src, operator);\n this.loop = Truffle.getRuntime().createLoopNode(new WhileRepeatingNode(this, ConvertBooleanNode.create(condition), body.asRNode()));\n }\n\n @Override\n public Object execute(VirtualFrame frame) {\n loop.executeLoop(frame);\n visibility.execute(frame, false);\n return RNull.instance;\n }\n\n private static final class WhileRepeatingNode extends AbstractRepeatingNode {\n\n @Child private ConvertBooleanNode condition;\n\n private final ConditionProfile conditionProfile = ConditionProfile.createCountingProfile();\n private final BranchProfile normalBlock = BranchProfile.create();\n private final BranchProfile breakBlock = BranchProfile.create();\n private final BranchProfile nextBlock = BranchProfile.create();\n\n \/\/ only used for toString\n private final WhileNode whileNode;\n\n WhileRepeatingNode(WhileNode whileNode, ConvertBooleanNode condition, RNode body) {\n super(body);\n this.whileNode = whileNode;\n this.condition = condition;\n \/\/ pre-initialize the profile so that loop exits to not deoptimize\n conditionProfile.profile(false);\n }\n\n @Override\n public boolean executeRepeating(VirtualFrame frame) {\n try {\n if (conditionProfile.profile(condition.executeByte(frame) == RRuntime.LOGICAL_TRUE)) {\n body.voidExecute(frame);\n normalBlock.enter();\n return true;\n } else {\n return false;\n }\n } catch (BreakException e) {\n breakBlock.enter();\n return false;\n } catch (NextException e) {\n nextBlock.enter();\n return true;\n }\n }\n\n @Override\n public String toString() {\n return whileNode.toString();\n }\n }\n\n @Override\n public RSyntaxElement[] getSyntaxArguments() {\n WhileRepeatingNode repeatingNode = (WhileRepeatingNode) loop.getRepeatingNode();\n return new RSyntaxElement[]{repeatingNode.condition.asRSyntaxNode(), repeatingNode.body.asRSyntaxNode()};\n }\n\n @Override\n public ArgumentsSignature getSyntaxSignature() {\n return ArgumentsSignature.empty(2);\n }\n}","smell":"blob","id":141} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2018 Contributors to the Eclipse Foundation\n *\n * See the NOTICE file(s) distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * https:\/\/www.eclipse.org\/legal\/epl-2.0\n *\n * SPDX-License-Identifier: EPL-2.0\n *\/\npackage org.eclipse.vorto.codegen.api;\n\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport org.eclipse.emf.common.util.TreeIterator;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.vorto.core.api.model.datatype.Entity;\nimport org.eclipse.vorto.core.api.model.datatype.Enum;\nimport org.eclipse.vorto.core.api.model.datatype.ObjectPropertyType;\nimport org.eclipse.vorto.core.api.model.datatype.Type;\nimport org.eclipse.vorto.core.api.model.functionblock.FunctionblockModel;\nimport org.eclipse.vorto.core.api.model.functionblock.RefParam;\nimport org.eclipse.vorto.core.api.model.functionblock.ReturnObjectType;\nimport org.eclipse.vorto.core.api.model.informationmodel.FunctionblockProperty;\nimport org.eclipse.vorto.core.api.model.informationmodel.InformationModel;\n\n\/**\n * Generator task that traverses all types used in an information model and generates their platform\n * specific representations\n * \n * @author Alexander Edelmann - Robert Bosch (SEA) Pte. Ltd.\n *\n *\/\npublic class DatatypeGeneratorTask implements ICodeGeneratorTask {\n\n private IFileTemplate entityTemplate;\n private IFileTemplate enumTemplate;\n\n public DatatypeGeneratorTask(IFileTemplate entityTemplate,\n IFileTemplate enumTemplate) {\n this.entityTemplate = entityTemplate;\n this.enumTemplate = enumTemplate;\n }\n\n @Override\n public void generate(InformationModel ctx, InvocationContext context, IGeneratedWriter writer) {\n Set allTypesUsedInModel = new HashSet<>();\n for (FunctionblockProperty prop : ctx.getProperties()) {\n allTypesUsedInModel.addAll(getTypes(prop.getType()));\n }\n\n for (Type type : allTypesUsedInModel) {\n if (type instanceof Entity) {\n writer.write(new Generated(entityTemplate.getFileName((Entity) type),\n entityTemplate.getPath((Entity) type),\n entityTemplate.getContent((Entity) type, context)));\n } else if (type instanceof Enum) {\n writer.write(new Generated(enumTemplate.getFileName((Enum) type),\n enumTemplate.getPath((Enum) type), enumTemplate.getContent((Enum) type, context)));\n }\n }\n }\n\n private static Set getTypes(FunctionblockModel model) {\n Set allTypes = new LinkedHashSet<>();\n TreeIterator iterator = model.eAllContents();\n while (iterator.hasNext()) {\n EObject current = iterator.next();\n if (current instanceof RefParam) {\n addTypeAndReferences(((RefParam) current).getType(), allTypes);\n } else if (current instanceof ReturnObjectType) {\n addTypeAndReferences(((ReturnObjectType) current).getReturnType(), allTypes);\n } else if (current instanceof ObjectPropertyType) {\n addTypeAndReferences(((ObjectPropertyType) current).getType(), allTypes);\n }\n }\n return allTypes;\n }\n\n private static void addTypeAndReferences(Type type, Set container) {\n if (!container.contains(type)) {\n container.add(type);\n Set references = getTypesOfType(type, container);\n container.addAll(references);\n }\n }\n\n private static Set getTypesOfType(Type type, Set container) {\n TreeIterator iterator = type.eAllContents();\n while (iterator.hasNext()) {\n EObject current = iterator.next();\n if (current instanceof ObjectPropertyType) {\n if (!container.contains(current)) {\n container.add(((ObjectPropertyType) current).getType());\n Set moreTypes = getTypesOfType(((ObjectPropertyType) current).getType(), container);\n container.addAll(moreTypes);\n }\n\n }\n }\n\n return container;\n }\n}","smell_code":"public class DatatypeGeneratorTask implements ICodeGeneratorTask {\n\n private IFileTemplate entityTemplate;\n private IFileTemplate enumTemplate;\n\n public DatatypeGeneratorTask(IFileTemplate entityTemplate,\n IFileTemplate enumTemplate) {\n this.entityTemplate = entityTemplate;\n this.enumTemplate = enumTemplate;\n }\n\n @Override\n public void generate(InformationModel ctx, InvocationContext context, IGeneratedWriter writer) {\n Set allTypesUsedInModel = new HashSet<>();\n for (FunctionblockProperty prop : ctx.getProperties()) {\n allTypesUsedInModel.addAll(getTypes(prop.getType()));\n }\n\n for (Type type : allTypesUsedInModel) {\n if (type instanceof Entity) {\n writer.write(new Generated(entityTemplate.getFileName((Entity) type),\n entityTemplate.getPath((Entity) type),\n entityTemplate.getContent((Entity) type, context)));\n } else if (type instanceof Enum) {\n writer.write(new Generated(enumTemplate.getFileName((Enum) type),\n enumTemplate.getPath((Enum) type), enumTemplate.getContent((Enum) type, context)));\n }\n }\n }\n\n private static Set getTypes(FunctionblockModel model) {\n Set allTypes = new LinkedHashSet<>();\n TreeIterator iterator = model.eAllContents();\n while (iterator.hasNext()) {\n EObject current = iterator.next();\n if (current instanceof RefParam) {\n addTypeAndReferences(((RefParam) current).getType(), allTypes);\n } else if (current instanceof ReturnObjectType) {\n addTypeAndReferences(((ReturnObjectType) current).getReturnType(), allTypes);\n } else if (current instanceof ObjectPropertyType) {\n addTypeAndReferences(((ObjectPropertyType) current).getType(), allTypes);\n }\n }\n return allTypes;\n }\n\n private static void addTypeAndReferences(Type type, Set container) {\n if (!container.contains(type)) {\n container.add(type);\n Set references = getTypesOfType(type, container);\n container.addAll(references);\n }\n }\n\n private static Set getTypesOfType(Type type, Set container) {\n TreeIterator iterator = type.eAllContents();\n while (iterator.hasNext()) {\n EObject current = iterator.next();\n if (current instanceof ObjectPropertyType) {\n if (!container.contains(current)) {\n container.add(((ObjectPropertyType) current).getType());\n Set moreTypes = getTypesOfType(((ObjectPropertyType) current).getType(), container);\n container.addAll(moreTypes);\n }\n\n }\n }\n\n return container;\n }\n}","smell":"blob","id":142} {"lang_cluster":"Java","source_code":"package org.apache.taverna.workbench.models.graph;\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\n\/**\n * A graph model of a dataflow.\n * \n * @author David Withers\n *\/\npublic class Graph extends GraphShapeElement {\n\tpublic enum Alignment {\n\t\tHORIZONTAL, VERTICAL\n\t}\n\n\tprivate List nodes = new ArrayList<>();\n\tprivate Set edges = new HashSet<>();\n\tprivate Set subgraphs = new HashSet<>();\n\tprivate Alignment alignment = Alignment.VERTICAL;\n\n\t\/**\n\t * Constructs a Graph that uses the specified GraphEventManager to handle\n\t * any user generated events on GraphElements.\n\t * \n\t * @param eventManager\n\t *\/\n\tpublic Graph(GraphController graphController) {\n\t\tsuper(graphController);\n\t}\n\n\t\/**\n\t * Adds an edge to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param edge\n\t * the edge to add\n\t *\/\n\tpublic void addEdge(GraphEdge edge) {\n\t\tedge.setParent(this);\n\t\tedges.add(edge);\n\t}\n\n\t\/**\n\t * Adds a node to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param node\n\t * the node to add\n\t *\/\n\tpublic void addNode(GraphNode node) {\n\t\tnode.setParent(this);\n\t\tnodes.add(node);\n\t}\n\n\t\/**\n\t * Adds a subgraph to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param subgraph\n\t * the subgraph to add\n\t *\/\n\tpublic void addSubgraph(Graph subgraph) {\n\t\tsubgraph.setParent(this);\n\t\tsubgraphs.add(subgraph);\n\t}\n\n\t\/**\n\t * Returns the alignment of the Graph.\n\t * \n\t * @return the alignment of the Graph\n\t *\/\n\tpublic Alignment getAlignment() {\n\t\treturn alignment;\n\t}\n\n\t\/**\n\t * Returns the edges contained in the Graph.\n\t * \n\t * @return the edges contained in the Graph\n\t *\/\n\tpublic Set getEdges() {\n\t\treturn Collections.unmodifiableSet(edges);\n\t}\n\n\t\/**\n\t * Returns the nodes contained in the Graph.\n\t * \n\t * @return the nodes contained in the Graph\n\t *\/\n\tpublic List getNodes() {\n\t\treturn Collections.unmodifiableList(nodes);\n\t}\n\n\t\/**\n\t * Returns the subgraphs contained in the Graph.\n\t * \n\t * @return the subgraphs contained in the Graph\n\t *\/\n\tpublic Set getSubgraphs() {\n\t\treturn Collections.unmodifiableSet(subgraphs);\n\t}\n\n\t\/**\n\t * Removes an edge from the Graph.\n\t * \n\t * @param edge\n\t * the edge to remove\n\t * @return true if the edge is removed from the Graph\n\t *\/\n\tpublic boolean removeEdge(GraphEdge edge) {\n\t\treturn edges.remove(edge);\n\t}\n\n\t\/**\n\t * Removes a node from the Graph.\n\t * \n\t * @param node\n\t * the node to remove\n\t * @return true if the node is removed from the Graph\n\t *\/\n\tpublic boolean removeNode(GraphNode node) {\n\t\treturn nodes.remove(node);\n\t}\n\n\t\/**\n\t * Removes a subgraph from the Graph.\n\t * \n\t * @param subgraph\n\t * the subgraph to remove\n\t * @return true if the subgraph is removed from the Graph\n\t *\/\n\tpublic boolean removeSubgraph(Graph subgraph) {\n\t\treturn subgraphs.remove(subgraph);\n\t}\n\n\t\/**\n\t * Sets the alignment of the Graph.\n\t * \n\t * @param alignment\n\t * the new alignment\n\t *\/\n\tpublic void setAlignment(Alignment alignment) {\n\t\tthis.alignment = alignment;\n\t}\n}","smell_code":"public class Graph extends GraphShapeElement {\n\tpublic enum Alignment {\n\t\tHORIZONTAL, VERTICAL\n\t}\n\n\tprivate List nodes = new ArrayList<>();\n\tprivate Set edges = new HashSet<>();\n\tprivate Set subgraphs = new HashSet<>();\n\tprivate Alignment alignment = Alignment.VERTICAL;\n\n\t\/**\n\t * Constructs a Graph that uses the specified GraphEventManager to handle\n\t * any user generated events on GraphElements.\n\t * \n\t * @param eventManager\n\t *\/\n\tpublic Graph(GraphController graphController) {\n\t\tsuper(graphController);\n\t}\n\n\t\/**\n\t * Adds an edge to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param edge\n\t * the edge to add\n\t *\/\n\tpublic void addEdge(GraphEdge edge) {\n\t\tedge.setParent(this);\n\t\tedges.add(edge);\n\t}\n\n\t\/**\n\t * Adds a node to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param node\n\t * the node to add\n\t *\/\n\tpublic void addNode(GraphNode node) {\n\t\tnode.setParent(this);\n\t\tnodes.add(node);\n\t}\n\n\t\/**\n\t * Adds a subgraph to the Graph and sets its parent to be this Graph.\n\t * \n\t * @param subgraph\n\t * the subgraph to add\n\t *\/\n\tpublic void addSubgraph(Graph subgraph) {\n\t\tsubgraph.setParent(this);\n\t\tsubgraphs.add(subgraph);\n\t}\n\n\t\/**\n\t * Returns the alignment of the Graph.\n\t * \n\t * @return the alignment of the Graph\n\t *\/\n\tpublic Alignment getAlignment() {\n\t\treturn alignment;\n\t}\n\n\t\/**\n\t * Returns the edges contained in the Graph.\n\t * \n\t * @return the edges contained in the Graph\n\t *\/\n\tpublic Set getEdges() {\n\t\treturn Collections.unmodifiableSet(edges);\n\t}\n\n\t\/**\n\t * Returns the nodes contained in the Graph.\n\t * \n\t * @return the nodes contained in the Graph\n\t *\/\n\tpublic List getNodes() {\n\t\treturn Collections.unmodifiableList(nodes);\n\t}\n\n\t\/**\n\t * Returns the subgraphs contained in the Graph.\n\t * \n\t * @return the subgraphs contained in the Graph\n\t *\/\n\tpublic Set getSubgraphs() {\n\t\treturn Collections.unmodifiableSet(subgraphs);\n\t}\n\n\t\/**\n\t * Removes an edge from the Graph.\n\t * \n\t * @param edge\n\t * the edge to remove\n\t * @return true if the edge is removed from the Graph\n\t *\/\n\tpublic boolean removeEdge(GraphEdge edge) {\n\t\treturn edges.remove(edge);\n\t}\n\n\t\/**\n\t * Removes a node from the Graph.\n\t * \n\t * @param node\n\t * the node to remove\n\t * @return true if the node is removed from the Graph\n\t *\/\n\tpublic boolean removeNode(GraphNode node) {\n\t\treturn nodes.remove(node);\n\t}\n\n\t\/**\n\t * Removes a subgraph from the Graph.\n\t * \n\t * @param subgraph\n\t * the subgraph to remove\n\t * @return true if the subgraph is removed from the Graph\n\t *\/\n\tpublic boolean removeSubgraph(Graph subgraph) {\n\t\treturn subgraphs.remove(subgraph);\n\t}\n\n\t\/**\n\t * Sets the alignment of the Graph.\n\t * \n\t * @param alignment\n\t * the new alignment\n\t *\/\n\tpublic void setAlignment(Alignment alignment) {\n\t\tthis.alignment = alignment;\n\t}\n}","smell":"blob","id":143} {"lang_cluster":"Java","source_code":"package example.service;\n\nimport example.repo.Customer758Repository;\n\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class Customer758Service {\n\tpublic Customer758Service(Customer758Repository repo) {\n\t}\n}","smell_code":"@Service\npublic class Customer758Service {\n\tpublic Customer758Service(Customer758Repository repo) {\n\t}\n}","smell":"blob","id":144} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http:\/\/aws.amazon.com\/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\npackage com.ibm.cloud.objectstorage.services.s3.transfer.internal;\n\nimport com.ibm.cloud.objectstorage.event.ProgressEvent;\nimport com.ibm.cloud.objectstorage.event.SyncProgressListener;\nimport com.ibm.cloud.objectstorage.services.s3.transfer.TransferProgress;\n\npublic class TransferProgressUpdatingListener extends SyncProgressListener {\n private final TransferProgress transferProgress;\n\n public TransferProgressUpdatingListener(TransferProgress transferProgress) {\n this.transferProgress = transferProgress;\n }\n\n public void progressChanged(ProgressEvent progressEvent) {\n long bytes = progressEvent.getBytesTransferred();\n if (bytes == 0)\n return; \/\/ only interested in non-zero bytes\n transferProgress.updateProgress(bytes);\n }\n}","smell_code":"public class TransferProgressUpdatingListener extends SyncProgressListener {\n private final TransferProgress transferProgress;\n\n public TransferProgressUpdatingListener(TransferProgress transferProgress) {\n this.transferProgress = transferProgress;\n }\n\n public void progressChanged(ProgressEvent progressEvent) {\n long bytes = progressEvent.getBytesTransferred();\n if (bytes == 0)\n return; \/\/ only interested in non-zero bytes\n transferProgress.updateProgress(bytes);\n }\n}","smell":"blob","id":145} {"lang_cluster":"Java","source_code":"\/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright 1997-2010 Oracle and\/or its affiliates. All rights reserved.\n *\n * Oracle and Java are registered trademarks of Oracle and\/or its affiliates.\n * Other names may be trademarks of their respective owners.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common\n * Development and Distribution License(\"CDDL\") (collectively, the\n * \"License\"). You may not use this file except in compliance with the\n * License. You can obtain a copy of the License at\n * http:\/\/www.netbeans.org\/cddl-gplv2.html\n * or nbbuild\/licenses\/CDDL-GPL-2-CP. See the License for the\n * specific language governing permissions and limitations under the\n * License. When distributing the software, include this License Header\n * Notice in each file and include the License file at\n * nbbuild\/licenses\/CDDL-GPL-2-CP. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the GPL Version 2 section of the License file that\n * accompanied this code. If applicable, add the following below the\n * License Header, with the fields enclosed by brackets [] replaced by\n * your own identifying information:\n * \"Portions Copyrighted [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * The Original Software is NetBeans. The Initial Developer of the Original\n * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun\n * Microsystems, Inc. All Rights Reserved.\n *\n * If you wish your version of this file to be governed by only the CDDL\n * or only the GPL Version 2, indicate your decision by adding\n * \"[Contributor] elects to include this software in this distribution\n * under the [CDDL or GPL Version 2] license.\" If you do not indicate a\n * single choice of license, a recipient has the option to distribute\n * your version of this file under either the CDDL, the GPL Version 2 or\n * to extend the choice of license to its licensees as provided above.\n * However, if you add GPL Version 2 code and therefore, elected the GPL\n * Version 2 license, then the option applies only if the new code is\n * made subject to such option by the copyright holder.\n *\/\n\npackage org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.rules;\n\nimport org.graalvm.visualvm.lib.jfluid.heap.Heap;\nimport org.graalvm.visualvm.lib.jfluid.heap.Instance;\nimport org.graalvm.visualvm.lib.jfluid.heap.JavaClass;\nimport org.graalvm.visualvm.lib.jfluid.heap.ObjectArrayInstance;\nimport org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.*;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport org.openide.util.NbBundle;\n\n\n\/\/@org.openide.util.lookup.ServiceProvider(service=org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.Rule.class)\npublic class WrongWeakHashMap extends IteratingRule {\n \/\/~ Inner Classes ------------------------------------------------------------------------------------------------------------\n\n private class WHMRecord {\n \/\/~ Instance fields ------------------------------------------------------------------------------------------------------\n\n private Instance hm;\n private Instance key;\n private Instance value;\n\n \/\/~ Constructors ---------------------------------------------------------------------------------------------------------\n\n WHMRecord(Instance hm, Instance key, Instance value) {\n this.hm = hm;\n this.key = key;\n this.value = value;\n }\n\n \/\/~ Methods --------------------------------------------------------------------------------------------------------------\n\n @Override\n public String toString() {\n return NbBundle.getMessage(WrongWeakHashMap.class, \"FMT_WWHM_Entry\",\n new Object[] {\n Utils.printClass(getContext(), getContext().getRootIncommingString(hm)),\n Utils.printInstance(hm),\n Utils.printInstance(key),\n Utils.printInstance(value)\n }\n );\n }\n }\n\n \/\/~ Instance fields ----------------------------------------------------------------------------------------------------------\n\n private FieldAccess fldHMEKey;\n private FieldAccess fldHMENext;\n private FieldAccess fldHMEValue;\n private FieldAccess fldHMTable;\n private JavaClass clsHM;\n private JavaClass clsHME;\n private Set poorWHM = new HashSet();\n\n \/\/~ Constructors -------------------------------------------------------------------------------------------------------------\n\n public WrongWeakHashMap() {\n super(NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_Name\"),\n NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_Desc\"),\n \"java.util.WeakHashMap\");\n \n }\n\n \/\/~ Methods ------------------------------------------------------------------------------------------------------------------\n \n @Override\n public String getHTMLDescription() {\n return NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_LongDesc\");\n }\n\n protected void perform(Instance hm) {\n scanWeakHashmap(hm);\n }\n\n @Override\n protected void prepareRule(MemoryLint context) {\n \/\/ TODO WeakHashMap might not be present in the dump\n Heap heap = context.getHeap();\n clsHM = heap.getJavaClassByName(\"java.util.WeakHashMap\"); \/\/ NOI18N\n clsHME = heap.getJavaClassByName(\"java.util.WeakHashMap$Entry\"); \/\/ NOI18N\n fldHMTable = new FieldAccess(clsHM, \"table\"); \/\/ NOI18N\n\n JavaClass ref = heap.getJavaClassByName(\"java.lang.ref.Reference\"); \/\/ NOI18N\n fldHMEKey = new FieldAccess(ref, \"referent\"); \/\/ NOI18N\n fldHMEValue = new FieldAccess(clsHME, \"value\"); \/\/ NOI18N\n fldHMENext = new FieldAccess(clsHME, \"next\"); \/\/ NOI18N\n }\n\n @Override\n protected void summary() {\n for (WHMRecord whm : poorWHM) {\n getContext().appendResults(whm.toString());\n }\n }\n\n private void scanWeakHashmap(Instance hm) {\n ObjectArrayInstance table = (ObjectArrayInstance) fldHMTable.getRefValue(hm);\n\n if (table == null) { \/\/ ? \n\n return;\n }\n\n @SuppressWarnings(\"unchecked\")\n List tval = table.getValues();\n\n for (Instance entry : tval) {\n while (entry != null) {\n Instance key = fldHMEKey.getRefValue(entry);\n\n if (key != null) { \/\/ XXX can also scan for weak HM pending cleanup\n\n Instance value = fldHMEValue.getRefValue(entry);\n\n if (Utils.isReachableFrom(value, key)) {\n poorWHM.add(new WHMRecord(hm, key, value));\n\n return;\n }\n }\n\n entry = fldHMENext.getRefValue(entry);\n }\n }\n\n return;\n }\n}","smell_code":"public class WrongWeakHashMap extends IteratingRule {\n \/\/~ Inner Classes ------------------------------------------------------------------------------------------------------------\n\n private class WHMRecord {\n \/\/~ Instance fields ------------------------------------------------------------------------------------------------------\n\n private Instance hm;\n private Instance key;\n private Instance value;\n\n \/\/~ Constructors ---------------------------------------------------------------------------------------------------------\n\n WHMRecord(Instance hm, Instance key, Instance value) {\n this.hm = hm;\n this.key = key;\n this.value = value;\n }\n\n \/\/~ Methods --------------------------------------------------------------------------------------------------------------\n\n @Override\n public String toString() {\n return NbBundle.getMessage(WrongWeakHashMap.class, \"FMT_WWHM_Entry\",\n new Object[] {\n Utils.printClass(getContext(), getContext().getRootIncommingString(hm)),\n Utils.printInstance(hm),\n Utils.printInstance(key),\n Utils.printInstance(value)\n }\n );\n }\n }\n\n \/\/~ Instance fields ----------------------------------------------------------------------------------------------------------\n\n private FieldAccess fldHMEKey;\n private FieldAccess fldHMENext;\n private FieldAccess fldHMEValue;\n private FieldAccess fldHMTable;\n private JavaClass clsHM;\n private JavaClass clsHME;\n private Set poorWHM = new HashSet();\n\n \/\/~ Constructors -------------------------------------------------------------------------------------------------------------\n\n public WrongWeakHashMap() {\n super(NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_Name\"),\n NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_Desc\"),\n \"java.util.WeakHashMap\");\n \n }\n\n \/\/~ Methods ------------------------------------------------------------------------------------------------------------------\n \n @Override\n public String getHTMLDescription() {\n return NbBundle.getMessage(WrongWeakHashMap.class, \"LBL_WWHM_LongDesc\");\n }\n\n protected void perform(Instance hm) {\n scanWeakHashmap(hm);\n }\n\n @Override\n protected void prepareRule(MemoryLint context) {\n \/\/ TODO WeakHashMap might not be present in the dump\n Heap heap = context.getHeap();\n clsHM = heap.getJavaClassByName(\"java.util.WeakHashMap\"); \/\/ NOI18N\n clsHME = heap.getJavaClassByName(\"java.util.WeakHashMap$Entry\"); \/\/ NOI18N\n fldHMTable = new FieldAccess(clsHM, \"table\"); \/\/ NOI18N\n\n JavaClass ref = heap.getJavaClassByName(\"java.lang.ref.Reference\"); \/\/ NOI18N\n fldHMEKey = new FieldAccess(ref, \"referent\"); \/\/ NOI18N\n fldHMEValue = new FieldAccess(clsHME, \"value\"); \/\/ NOI18N\n fldHMENext = new FieldAccess(clsHME, \"next\"); \/\/ NOI18N\n }\n\n @Override\n protected void summary() {\n for (WHMRecord whm : poorWHM) {\n getContext().appendResults(whm.toString());\n }\n }\n\n private void scanWeakHashmap(Instance hm) {\n ObjectArrayInstance table = (ObjectArrayInstance) fldHMTable.getRefValue(hm);\n\n if (table == null) { \/\/ ? \n\n return;\n }\n\n @SuppressWarnings(\"unchecked\")\n List tval = table.getValues();\n\n for (Instance entry : tval) {\n while (entry != null) {\n Instance key = fldHMEKey.getRefValue(entry);\n\n if (key != null) { \/\/ XXX can also scan for weak HM pending cleanup\n\n Instance value = fldHMEValue.getRefValue(entry);\n\n if (Utils.isReachableFrom(value, key)) {\n poorWHM.add(new WHMRecord(hm, key, value));\n\n return;\n }\n }\n\n entry = fldHMENext.getRefValue(entry);\n }\n }\n\n return;\n }\n}","smell":"blob","id":146} {"lang_cluster":"Java","source_code":"\/\/ $Id: ary.java,v 1.1 2004-05-22 07:27:00 bfulgham Exp $\n\/\/ http:\/\/www.bagley.org\/~doug\/shootout\/\n\n\/\/ this program is modified from:\n\/\/ http:\/\/cm.bell-labs.com\/cm\/cs\/who\/bwk\/interps\/pap.html\n\/\/ Timing Trials, or, the Trials of Timing: Experiments with Scripting\n\/\/ and User-Interface Languages<\/a> by Brian W. Kernighan and\n\/\/ Christopher J. Van Wyk.\n\nimport java.io.*;\nimport java.util.*;\n\npublic class ary {\n public static void main(String args[]) {\n int i, j, k, n = Integer.parseInt(args[0]);\n int x[] = new int[n];\n int y[] = new int[n];\n\n for (i = 0; i < n; i++)\n x[i] = i + 1;\n for (k = 0; k < 1000; k++ )\n for (j = n-1; j >= 0; j--)\n y[j] += x[j];\n\n System.out.println(y[0] + \" \" + y[n-1]);\n }\n}","smell_code":"public class ary {\n public static void main(String args[]) {\n int i, j, k, n = Integer.parseInt(args[0]);\n int x[] = new int[n];\n int y[] = new int[n];\n\n for (i = 0; i < n; i++)\n x[i] = i + 1;\n for (k = 0; k < 1000; k++ )\n for (j = n-1; j >= 0; j--)\n y[j] += x[j];\n\n System.out.println(y[0] + \" \" + y[n-1]);\n }\n}","smell":"blob","id":147} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2017 the TeXlipse team and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * The TeXlipse team - initial API and implementation\n *******************************************************************************\/\npackage org.eclipse.texlipse.viewer.util;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\n\nimport org.eclipse.texlipse.builder.BuilderRegistry;\n\n\n\/**\n * A helper class to read the viewer error stream if an error occurs.\n * \n * @author Kimmo Karlsson\n *\/\npublic class ViewerErrorScanner implements Runnable {\n\n \/\/ the process to monitor\n private Process process;\n\n public ViewerErrorScanner(Process process) {\n this.process = process;\n }\n \n \/**\n * Wait for the program to exit and read the status.\n *\/\n public void run() {\n \n BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));\n \n ArrayList buffer = new ArrayList();\n String tmp = null;\n try {\n \n \/\/ read the error output stream lines before the program exits\n \/\/ the stream is not available anymore after the program has exit\n while ((tmp = in.readLine()) != null) {\n buffer.add(tmp);\n }\n in.close();\n \n } catch (IOException e) {\n }\n \n int exitCode = 0;\n try {\n exitCode = process.waitFor();\n } catch (InterruptedException e) {\n }\n\n \/\/ if there was an error, the viewer exited with non-zero status\n if (exitCode != 0) {\n \/\/ print the error messages\n for (int i = 0; i < buffer.size(); i++) {\n tmp = (String) buffer.get(i);\n BuilderRegistry.printToConsole(\"viewer> \" + tmp);\n }\n }\n }\n}","smell_code":"public class ViewerErrorScanner implements Runnable {\n\n \/\/ the process to monitor\n private Process process;\n\n public ViewerErrorScanner(Process process) {\n this.process = process;\n }\n \n \/**\n * Wait for the program to exit and read the status.\n *\/\n public void run() {\n \n BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));\n \n ArrayList buffer = new ArrayList();\n String tmp = null;\n try {\n \n \/\/ read the error output stream lines before the program exits\n \/\/ the stream is not available anymore after the program has exit\n while ((tmp = in.readLine()) != null) {\n buffer.add(tmp);\n }\n in.close();\n \n } catch (IOException e) {\n }\n \n int exitCode = 0;\n try {\n exitCode = process.waitFor();\n } catch (InterruptedException e) {\n }\n\n \/\/ if there was an error, the viewer exited with non-zero status\n if (exitCode != 0) {\n \/\/ print the error messages\n for (int i = 0; i < buffer.size(); i++) {\n tmp = (String) buffer.get(i);\n BuilderRegistry.printToConsole(\"viewer> \" + tmp);\n }\n }\n }\n}","smell":"blob","id":148} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.taverna.workbench.ui.views.contextualviews;\n\nimport static java.awt.BorderLayout.CENTER;\n\nimport java.awt.BorderLayout;\nimport java.awt.Frame;\n\nimport javax.swing.Action;\nimport javax.swing.JComponent;\nimport javax.swing.JPanel;\n\n\/**\n * An abstract class defining the base container to hold a contextual view over\n * Dataflow element.\n *

\n * The specific implementation of this class to support a given dataflow element\n * needs to implement the {@link #getMainFrame()} and {@link #getViewTitle()}.\n *

\n * If a view is associated with an action handler to configure this component,\n * then the {@link #getConfigureAction(Frame) getConfigureAction} handler must\n * be over-ridden. If this returns null then the configure button is left\n * disabled and it is not possible to configure the element.\n * \n * @author Stuart Owen\n * @author Ian Dunlop\n * @author Alan R Williams\n *\/\n@SuppressWarnings(\"serial\")\npublic abstract class ContextualView extends JPanel {\n\t\/**\n\t * When implemented, this method should define the main frame that is placed\n\t * in this container, and provides a static view of the Dataflow element.\n\t * \n\t * @return a JComponent that represents the dataflow element.\n\t *\/\n\tpublic abstract JComponent getMainFrame();\n\n\t\/**\n\t * @return a String providing a title for the view\n\t *\/\n\tpublic abstract String getViewTitle();\n\n\t\/**\n\t * Allows the item to be configured, but returning an action handler that\n\t * will be invoked when selecting to configure. By default this is provided\n\t * by a button.\n\t *

\n\t * If there is no ability to configure the given item, then this should\n\t * return null.\n\t * \n\t * @param owner\n\t * the owning dialog to be used when displaying dialogues for\n\t * configuration options\n\t * @return an action that allows the element being viewed to be configured.\n\t *\/\n\tpublic Action getConfigureAction(Frame owner) {\n\t\treturn null;\n\t}\n\n\t\/**\n\t * This must<\/i> be called by any sub-classes after they have initialised\n\t * their own view since it gets their main panel and adds it to the main\n\t * contextual view. If you don't do this you will get a very empty frame\n\t * popping up!\n\t *\/\n\tpublic void initView() {\n\t\tsetLayout(new BorderLayout());\n\t\tadd(getMainFrame(), CENTER);\n\t\tsetName(getViewTitle());\n\t}\n\n\tpublic abstract void refreshView();\n\n\tpublic abstract int getPreferredPosition();\n\n\tpublic static String getTextFromDepth(String kind, Integer depth) {\n\t\tString labelText = \"The last prediction said the \" + kind;\n\t\tif (depth == null) {\n\t\t\tlabelText += \" would not transmit a value\";\n\t\t} else if (depth == -1) {\n\t\t\tlabelText += \" was invalid\/unpredicted\";\n\t\t} else if (depth == 0) {\n\t\t\tlabelText += \" would carry a single value\";\n\t\t} else {\n\t\t\tlabelText += \" would carry a list of depth \" + depth;\n\t\t}\n\t\treturn labelText;\n\t}\n}","smell_code":"@SuppressWarnings(\"serial\")\npublic abstract class ContextualView extends JPanel {\n\t\/**\n\t * When implemented, this method should define the main frame that is placed\n\t * in this container, and provides a static view of the Dataflow element.\n\t * \n\t * @return a JComponent that represents the dataflow element.\n\t *\/\n\tpublic abstract JComponent getMainFrame();\n\n\t\/**\n\t * @return a String providing a title for the view\n\t *\/\n\tpublic abstract String getViewTitle();\n\n\t\/**\n\t * Allows the item to be configured, but returning an action handler that\n\t * will be invoked when selecting to configure. By default this is provided\n\t * by a button.\n\t *

\n\t * If there is no ability to configure the given item, then this should\n\t * return null.\n\t * \n\t * @param owner\n\t * the owning dialog to be used when displaying dialogues for\n\t * configuration options\n\t * @return an action that allows the element being viewed to be configured.\n\t *\/\n\tpublic Action getConfigureAction(Frame owner) {\n\t\treturn null;\n\t}\n\n\t\/**\n\t * This must<\/i> be called by any sub-classes after they have initialised\n\t * their own view since it gets their main panel and adds it to the main\n\t * contextual view. If you don't do this you will get a very empty frame\n\t * popping up!\n\t *\/\n\tpublic void initView() {\n\t\tsetLayout(new BorderLayout());\n\t\tadd(getMainFrame(), CENTER);\n\t\tsetName(getViewTitle());\n\t}\n\n\tpublic abstract void refreshView();\n\n\tpublic abstract int getPreferredPosition();\n\n\tpublic static String getTextFromDepth(String kind, Integer depth) {\n\t\tString labelText = \"The last prediction said the \" + kind;\n\t\tif (depth == null) {\n\t\t\tlabelText += \" would not transmit a value\";\n\t\t} else if (depth == -1) {\n\t\t\tlabelText += \" was invalid\/unpredicted\";\n\t\t} else if (depth == 0) {\n\t\t\tlabelText += \" would carry a single value\";\n\t\t} else {\n\t\t\tlabelText += \" would carry a list of depth \" + depth;\n\t\t}\n\t\treturn labelText;\n\t}\n}","smell":"blob","id":149} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2009-2010 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/**\n * \n *\/\npackage org.springframework.batch.admin.web;\n\npublic class LaunchRequest {\n\tprivate String jobName;\n\n\tString jobParameters;\n\n\tpublic String getJobName() {\n\t\treturn jobName;\n\t}\n\n\tpublic void setJobName(String jobName) {\n\t\tthis.jobName = jobName;\n\t}\n\n\tpublic String getJobParameters() {\n\t\treturn jobParameters;\n\t}\n\n\tpublic void setJobParameters(String jobParameters) {\n\t\tthis.jobParameters = jobParameters;\n\t}\n\n}","smell_code":"public class LaunchRequest {\n\tprivate String jobName;\n\n\tString jobParameters;\n\n\tpublic String getJobName() {\n\t\treturn jobName;\n\t}\n\n\tpublic void setJobName(String jobName) {\n\t\tthis.jobName = jobName;\n\t}\n\n\tpublic String getJobParameters() {\n\t\treturn jobParameters;\n\t}\n\n\tpublic void setJobParameters(String jobParameters) {\n\t\tthis.jobParameters = jobParameters;\n\t}\n\n}","smell":"blob","id":150} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.apache.deltaspike.jsf.impl.injection;\n\nimport javax.enterprise.context.spi.CreationalContext;\nimport javax.enterprise.inject.spi.Bean;\nimport java.io.Serializable;\n\nclass DependentBeanEntry implements Serializable\n{\n private static final long serialVersionUID = 7148484695430831322L;\n\n private final T instance;\n private final Bean bean;\n private final CreationalContext creationalContext;\n\n DependentBeanEntry(T instance, Bean bean, CreationalContext creationalContext)\n {\n this.instance = instance;\n this.bean = bean;\n this.creationalContext = creationalContext;\n }\n\n T getInstance()\n {\n return instance;\n }\n\n Bean getBean()\n {\n return bean;\n }\n\n CreationalContext getCreationalContext()\n {\n return creationalContext;\n }\n}","smell_code":" DependentBeanEntry(T instance, Bean bean, CreationalContext creationalContext)\n {\n this.instance = instance;\n this.bean = bean;\n this.creationalContext = creationalContext;\n }","smell":"long method","id":151} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2016, 2019, Oracle and\/or its affiliates. All rights reserved.\n *\/\npackage com.oracle.bmc.waas.requests;\n\nimport com.oracle.bmc.waas.model.*;\n\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20181116\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\")\n@lombok.Getter\npublic class CreateCertificateRequest extends com.oracle.bmc.requests.BmcRequest {\n\n \/**\n * The details of the SSL certificate resource to create.\n *\/\n private CreateCertificateDetails createCertificateDetails;\n\n \/**\n * The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID.\n *\/\n private String opcRequestId;\n\n \/**\n * A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations\n * *Example:* If a resource has been deleted and purged from the system, then a retry of the original delete request may be rejected.\n *\/\n private String opcRetryToken;\n\n public static class Builder {\n private com.oracle.bmc.util.internal.Consumer\n invocationCallback = null;\n\n \/**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n *\/\n public Builder invocationCallback(\n com.oracle.bmc.util.internal.Consumer\n invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n \/**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n *\/\n public Builder copy(CreateCertificateRequest o) {\n createCertificateDetails(o.getCreateCertificateDetails());\n opcRequestId(o.getOpcRequestId());\n opcRetryToken(o.getOpcRetryToken());\n invocationCallback(o.getInvocationCallback());\n return this;\n }\n\n \/**\n * Build the instance of CreateCertificateRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of CreateCertificateRequest\n *\/\n public CreateCertificateRequest build() {\n CreateCertificateRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n return request;\n }\n }\n}","smell_code":" public CreateCertificateRequest build() {\n CreateCertificateRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n return request;\n }","smell":"long method","id":152} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2012-2018 Red Hat, Inc.\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https:\/\/www.eclipse.org\/legal\/epl-2.0\/\n *\n * SPDX-License-Identifier: EPL-2.0\n *\n * Contributors:\n * Red Hat, Inc. - initial API and implementation\n *\/\npackage org.eclipse.che.api.factory.server.jpa;\n\nimport com.google.inject.AbstractModule;\nimport org.eclipse.che.api.factory.server.jpa.JpaFactoryDao.RemoveFactoriesBeforeUserRemovedEventSubscriber;\nimport org.eclipse.che.api.factory.server.spi.FactoryDao;\n\n\/** @author Yevhenii Voevodin *\/\npublic class FactoryJpaModule extends AbstractModule {\n @Override\n protected void configure() {\n bind(FactoryDao.class).to(JpaFactoryDao.class);\n bind(RemoveFactoriesBeforeUserRemovedEventSubscriber.class).asEagerSingleton();\n }\n}","smell_code":" @Override\n protected void configure() {\n bind(FactoryDao.class).to(JpaFactoryDao.class);\n bind(RemoveFactoriesBeforeUserRemovedEventSubscriber.class).asEagerSingleton();\n }","smell":"long method","id":153} {"lang_cluster":"Java","source_code":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\npackage org.apache.cloudstack.api.response;\n\nimport com.google.gson.annotations.SerializedName;\n\nimport org.apache.cloudstack.api.BaseResponse;\n\nimport com.cloud.serializer.Param;\n\npublic class SuccessResponse extends BaseResponse {\n @SerializedName(\"success\")\n @Param(description = \"true if operation is executed successfully\")\n private Boolean success = true;\n\n @SerializedName(\"displaytext\")\n @Param(description = \"any text associated with the success or failure\")\n private String displayText;\n\n public Boolean getSuccess() {\n return success;\n }\n\n public void setSuccess(Boolean success) {\n this.success = success;\n }\n\n public String getDisplayText() {\n return displayText;\n }\n\n public void setDisplayText(String displayText) {\n this.displayText = displayText;\n }\n\n public SuccessResponse() {\n }\n\n public SuccessResponse(String responseName) {\n super.setResponseName(responseName);\n }\n}","smell_code":" public String getDisplayText() {\n return displayText;\n }","smell":"long method","id":154} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2011, 2016, Oracle and\/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n *\/\n\npackage sun.lwawt.macosx;\n\nimport java.awt.*;\nimport java.awt.event.FocusEvent;\n\nimport sun.java2d.SurfaceData;\nimport sun.java2d.opengl.CGLLayer;\nimport sun.lwawt.LWWindowPeer;\nimport sun.lwawt.PlatformWindow;\nimport sun.util.logging.PlatformLogger;\n\n\/*\n * Provides a lightweight implementation of the EmbeddedFrame.\n *\/\npublic class CPlatformEmbeddedFrame implements PlatformWindow {\n\n private static final PlatformLogger focusLogger = PlatformLogger.getLogger(\n \"sun.lwawt.macosx.focus.CPlatformEmbeddedFrame\");\n\n private CGLLayer windowLayer;\n private LWWindowPeer peer;\n private CEmbeddedFrame target;\n\n private volatile int screenX = 0;\n private volatile int screenY = 0;\n\n @Override \/\/ PlatformWindow\n public void initialize(Window target, final LWWindowPeer peer, PlatformWindow owner) {\n this.peer = peer;\n this.windowLayer = new CGLLayer(peer);\n this.target = (CEmbeddedFrame)target;\n }\n\n @Override\n public LWWindowPeer getPeer() {\n return peer;\n }\n\n @Override\n public long getLayerPtr() {\n return windowLayer.getPointer();\n }\n\n @Override\n public void dispose() {\n windowLayer.dispose();\n }\n\n @Override\n public void setBounds(int x, int y, int w, int h) {\n \/\/ This is a lightweight implementation of the EmbeddedFrame\n \/\/ and we simply synthesize a reshape request.\n screenX = x;\n screenY = y;\n peer.notifyReshape(x, y, w, h);\n }\n\n @Override\n public GraphicsDevice getGraphicsDevice() {\n \/\/ REMIND: return the main screen for the initial implementation\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n return ge.getDefaultScreenDevice();\n }\n\n @Override\n public Point getLocationOnScreen() {\n return new Point(screenX, screenY);\n }\n\n @Override\n public FontMetrics getFontMetrics(Font f) {\n throw new RuntimeException(\"Not implemented\");\n }\n\n @Override\n public SurfaceData getScreenSurface() {\n return windowLayer.getSurfaceData();\n }\n\n @Override\n public SurfaceData replaceSurfaceData() {\n return windowLayer.replaceSurfaceData();\n }\n\n @Override\n public void setVisible(boolean visible) {}\n\n @Override\n public void setTitle(String title) {}\n\n @Override\n public Insets getInsets() {\n return new Insets(0, 0, 0, 0);\n }\n\n @Override\n public void toFront() {}\n\n @Override\n public void toBack() {}\n\n @Override\n public void setMenuBar(MenuBar mb) {}\n\n @Override\n public void setAlwaysOnTop(boolean value) {}\n\n @Override\n public void updateFocusableWindowState() {}\n\n @Override\n public boolean rejectFocusRequest(FocusEvent.Cause cause) {\n \/\/ Cross-app activation requests are not allowed.\n if (cause != FocusEvent.Cause.MOUSE_EVENT &&\n !target.isParentWindowActive())\n {\n focusLogger.fine(\"the embedder is inactive, so the request is rejected\");\n return true;\n }\n return false;\n }\n\n @Override\n public boolean requestWindowFocus() {\n CEmbeddedFrame.updateGlobalFocusedWindow(target);\n target.synthesizeWindowActivation(true);\n return true;\n }\n\n @Override\n public boolean isActive() {\n return true;\n }\n\n @Override\n public void setResizable(boolean resizable) {}\n\n @Override\n public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {}\n\n @Override\n public void updateIconImages() {}\n\n @Override\n public void setOpacity(float opacity) {}\n\n @Override\n public void setOpaque(boolean isOpaque) {}\n\n @Override\n public void enterFullScreenMode() {}\n\n @Override\n public void exitFullScreenMode() {}\n\n @Override\n public boolean isFullScreenMode() {\n return false;\n }\n\n @Override\n public void setWindowState(int windowState) {}\n\n @Override\n public void setModalBlocked(boolean blocked) {}\n\n \/*\n * The method could not be implemented due to CALayer restrictions.\n * The exeption enforce clients not to use it.\n *\/\n @Override\n public boolean isUnderMouse() {\n throw new RuntimeException(\"Not implemented\");\n }\n}","smell_code":" @Override\n public boolean requestWindowFocus() {\n CEmbeddedFrame.updateGlobalFocusedWindow(target);\n target.synthesizeWindowActivation(true);\n return true;\n }","smell":"long method","id":155} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (C) 2006 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n *\/\n\npackage com.google.common.util.concurrent;\n\nimport static com.google.common.util.concurrent.MoreExecutors.directExecutor;\n\nimport com.google.common.annotations.GwtIncompatible;\nimport com.google.common.base.Preconditions;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport org.checkerframework.checker.nullness.compatqual.NullableDecl;\n\n\/**\n * Implementation of {@code Futures#withTimeout}.\n *\n *

Future that delegates to another but will finish early (via a {@link TimeoutException} wrapped\n * in an {@link ExecutionException}) if the specified duration expires. The delegate future is\n * interrupted and cancelled if it times out.\n *\/\n@GwtIncompatible\nfinal class TimeoutFuture extends FluentFuture.TrustedFuture {\n static ListenableFuture create(\n ListenableFuture delegate,\n long time,\n TimeUnit unit,\n ScheduledExecutorService scheduledExecutor) {\n TimeoutFuture result = new TimeoutFuture<>(delegate);\n Fire fire = new Fire<>(result);\n result.timer = scheduledExecutor.schedule(fire, time, unit);\n delegate.addListener(fire, directExecutor());\n return result;\n }\n\n \/*\n * Memory visibility of these fields. There are two cases to consider.\n *\n * 1. visibility of the writes to these fields to Fire.run:\n *\n * The initial write to delegateRef is made definitely visible via the semantics of\n * addListener\/SES.schedule. The later racy write in cancel() is not guaranteed to be observed,\n * however that is fine since the correctness is based on the atomic state in our base class. The\n * initial write to timer is never definitely visible to Fire.run since it is assigned after\n * SES.schedule is called. Therefore Fire.run has to check for null. However, it should be visible\n * if Fire.run is called by delegate.addListener since addListener is called after the assignment\n * to timer, and importantly this is the main situation in which we need to be able to see the\n * write.\n *\n * 2. visibility of the writes to an afterDone() call triggered by cancel():\n *\n * Since these fields are non-final that means that TimeoutFuture is not being 'safely published',\n * thus a motivated caller may be able to expose the reference to another thread that would then\n * call cancel() and be unable to cancel the delegate.\n * There are a number of ways to solve this, none of which are very pretty, and it is currently\n * believed to be a purely theoretical problem (since the other actions should supply sufficient\n * write-barriers).\n *\/\n\n @NullableDecl private ListenableFuture delegateRef;\n @NullableDecl private ScheduledFuture timer;\n\n private TimeoutFuture(ListenableFuture delegate) {\n this.delegateRef = Preconditions.checkNotNull(delegate);\n }\n\n \/** A runnable that is called when the delegate or the timer completes. *\/\n private static final class Fire implements Runnable {\n @NullableDecl TimeoutFuture timeoutFutureRef;\n\n Fire(TimeoutFuture timeoutFuture) {\n this.timeoutFutureRef = timeoutFuture;\n }\n\n @Override\n public void run() {\n \/\/ If either of these reads return null then we must be after a successful cancel or another\n \/\/ call to this method.\n TimeoutFuture timeoutFuture = timeoutFutureRef;\n if (timeoutFuture == null) {\n return;\n }\n ListenableFuture delegate = timeoutFuture.delegateRef;\n if (delegate == null) {\n return;\n }\n\n \/*\n * If we're about to complete the TimeoutFuture, we want to release our reference to it.\n * Otherwise, we'll pin it (and its result) in memory until the timeout task is GCed. (The\n * need to clear our reference to the TimeoutFuture is the reason we use a *static* nested\n * class with a manual reference back to the \"containing\" class.)\n *\n * This has the nice-ish side effect of limiting reentrancy: run() calls\n * timeoutFuture.setException() calls run(). That reentrancy would already be harmless, since\n * timeoutFuture can be set (and delegate cancelled) only once. (And \"set only once\" is\n * important for other reasons: run() can still be invoked concurrently in different threads,\n * even with the above null checks.)\n *\/\n timeoutFutureRef = null;\n if (delegate.isDone()) {\n timeoutFuture.setFuture(delegate);\n } else {\n try {\n ScheduledFuture timer = timeoutFuture.timer;\n String message = \"Timed out\";\n if (timer != null) {\n long overDelayMs = Math.abs(timer.getDelay(TimeUnit.MILLISECONDS));\n if (overDelayMs > 10) { \/\/ Not all timing drift is worth reporting\n message += \" (timeout delayed by \" + overDelayMs + \" ms after scheduled time)\";\n }\n }\n timeoutFuture.timer = null; \/\/ Don't include already elapsed delay in delegate.toString()\n timeoutFuture.setException(new TimeoutFutureException(message + \": \" + delegate));\n } finally {\n delegate.cancel(true);\n }\n }\n }\n }\n\n private static final class TimeoutFutureException extends TimeoutException {\n private TimeoutFutureException(String message) {\n super(message);\n }\n\n @Override\n public synchronized Throwable fillInStackTrace() {\n setStackTrace(new StackTraceElement[0]);\n return this; \/\/ no stack trace, wouldn't be useful anyway\n }\n }\n\n @Override\n protected String pendingToString() {\n ListenableFuture localInputFuture = delegateRef;\n ScheduledFuture localTimer = timer;\n if (localInputFuture != null) {\n String message = \"inputFuture=[\" + localInputFuture + \"]\";\n if (localTimer != null) {\n final long delay = localTimer.getDelay(TimeUnit.MILLISECONDS);\n \/\/ Negative delays look confusing in an error message\n if (delay > 0) {\n message += \", remaining delay=[\" + delay + \" ms]\";\n }\n }\n return message;\n }\n return null;\n }\n\n @Override\n protected void afterDone() {\n maybePropagateCancellationTo(delegateRef);\n\n Future localTimer = timer;\n \/\/ Try to cancel the timer as an optimization.\n \/\/ timer may be null if this call to run was by the timer task since there is no happens-before\n \/\/ edge between the assignment to timer and an execution of the timer task.\n if (localTimer != null) {\n localTimer.cancel(false);\n }\n\n delegateRef = null;\n timer = null;\n }\n}","smell_code":" @Override\n protected String pendingToString() {\n ListenableFuture localInputFuture = delegateRef;\n ScheduledFuture localTimer = timer;\n if (localInputFuture != null) {\n String message = \"inputFuture=[\" + localInputFuture + \"]\";\n if (localTimer != null) {\n final long delay = localTimer.getDelay(TimeUnit.MILLISECONDS);\n \/\/ Negative delays look confusing in an error message\n if (delay > 0) {\n message += \", remaining delay=[\" + delay + \" ms]\";\n }\n }\n return message;\n }\n return null;\n }","smell":"long method","id":156} {"lang_cluster":"Java","source_code":"\npackage main;\n\npublic class Main {\n public static void main (String[] args) {\n }\n}","smell_code":" public static void main (String[] args) {\n }","smell":"long method","id":157} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2012-2018 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.springframework.boot.actuate.autoconfigure.web.server;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.springframework.beans.factory.BeanClassLoaderAware;\nimport org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration;\nimport org.springframework.boot.actuate.autoconfigure.web.ManagementContextType;\nimport org.springframework.context.annotation.DeferredImportSelector;\nimport org.springframework.core.OrderComparator;\nimport org.springframework.core.Ordered;\nimport org.springframework.core.annotation.Order;\nimport org.springframework.core.io.support.SpringFactoriesLoader;\nimport org.springframework.core.type.AnnotationMetadata;\nimport org.springframework.core.type.classreading.MetadataReader;\nimport org.springframework.core.type.classreading.SimpleMetadataReaderFactory;\nimport org.springframework.util.StringUtils;\n\n\/**\n * Selects configuration classes for the management context configuration. Entries are\n * loaded from {@code \/META-INF\/spring.factories} under the\n * {@code org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration}\n * key.\n *\n * @author Dave Syer\n * @author Phillip Webb\n * @author Andy Wilkinson\n * @see ManagementContextConfiguration\n *\/\n@Order(Ordered.LOWEST_PRECEDENCE)\nclass ManagementContextConfigurationImportSelector\n\t\timplements DeferredImportSelector, BeanClassLoaderAware {\n\n\tprivate ClassLoader classLoader;\n\n\t@Override\n\tpublic String[] selectImports(AnnotationMetadata metadata) {\n\t\tManagementContextType contextType = (ManagementContextType) metadata\n\t\t\t\t.getAnnotationAttributes(EnableManagementContext.class.getName())\n\t\t\t\t.get(\"value\");\n\t\t\/\/ Find all management context configuration classes, filtering duplicates\n\t\tList configurations = getConfigurations();\n\t\tOrderComparator.sort(configurations);\n\t\tList names = new ArrayList<>();\n\t\tfor (ManagementConfiguration configuration : configurations) {\n\t\t\tif (configuration.getContextType() == ManagementContextType.ANY\n\t\t\t\t\t|| configuration.getContextType() == contextType) {\n\t\t\t\tnames.add(configuration.getClassName());\n\t\t\t}\n\t\t}\n\t\treturn StringUtils.toStringArray(names);\n\t}\n\n\tprivate List getConfigurations() {\n\t\tSimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(\n\t\t\t\tthis.classLoader);\n\t\tList configurations = new ArrayList<>();\n\t\tfor (String className : loadFactoryNames()) {\n\t\t\taddConfiguration(readerFactory, configurations, className);\n\t\t}\n\t\treturn configurations;\n\t}\n\n\tprivate void addConfiguration(SimpleMetadataReaderFactory readerFactory,\n\t\t\tList configurations, String className) {\n\t\ttry {\n\t\t\tMetadataReader metadataReader = readerFactory.getMetadataReader(className);\n\t\t\tconfigurations.add(new ManagementConfiguration(metadataReader));\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Failed to read annotation metadata for '\" + className + \"'\", ex);\n\t\t}\n\t}\n\n\tprotected List loadFactoryNames() {\n\t\treturn SpringFactoriesLoader\n\t\t\t\t.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader);\n\t}\n\n\t@Override\n\tpublic void setBeanClassLoader(ClassLoader classLoader) {\n\t\tthis.classLoader = classLoader;\n\t}\n\n\t\/**\n\t * A management configuration class which can be sorted according to {@code @Order}.\n\t *\/\n\tprivate static final class ManagementConfiguration implements Ordered {\n\n\t\tprivate final String className;\n\n\t\tprivate final int order;\n\n\t\tprivate final ManagementContextType contextType;\n\n\t\tManagementConfiguration(MetadataReader metadataReader) {\n\t\t\tAnnotationMetadata annotationMetadata = metadataReader\n\t\t\t\t\t.getAnnotationMetadata();\n\t\t\tthis.order = readOrder(annotationMetadata);\n\t\t\tthis.className = metadataReader.getClassMetadata().getClassName();\n\t\t\tthis.contextType = readContextType(annotationMetadata);\n\t\t}\n\n\t\tprivate ManagementContextType readContextType(\n\t\t\t\tAnnotationMetadata annotationMetadata) {\n\t\t\tMap annotationAttributes = annotationMetadata\n\t\t\t\t\t.getAnnotationAttributes(\n\t\t\t\t\t\t\tManagementContextConfiguration.class.getName());\n\t\t\treturn (annotationAttributes != null)\n\t\t\t\t\t? (ManagementContextType) annotationAttributes.get(\"value\")\n\t\t\t\t\t: ManagementContextType.ANY;\n\t\t}\n\n\t\tprivate int readOrder(AnnotationMetadata annotationMetadata) {\n\t\t\tMap attributes = annotationMetadata\n\t\t\t\t\t.getAnnotationAttributes(Order.class.getName());\n\t\t\tInteger order = (attributes != null) ? (Integer) attributes.get(\"value\")\n\t\t\t\t\t: null;\n\t\t\treturn (order != null) ? order : Ordered.LOWEST_PRECEDENCE;\n\t\t}\n\n\t\tpublic String getClassName() {\n\t\t\treturn this.className;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getOrder() {\n\t\t\treturn this.order;\n\t\t}\n\n\t\tpublic ManagementContextType getContextType() {\n\t\t\treturn this.contextType;\n\t\t}\n\n\t}\n\n}","smell_code":"\t\tprivate int readOrder(AnnotationMetadata annotationMetadata) {\n\t\t\tMap attributes = annotationMetadata\n\t\t\t\t\t.getAnnotationAttributes(Order.class.getName());\n\t\t\tInteger order = (attributes != null) ? (Integer) attributes.get(\"value\")\n\t\t\t\t\t: null;\n\t\t\treturn (order != null) ? order : Ordered.LOWEST_PRECEDENCE;\n\t\t}","smell":"long method","id":158} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.tez.runtime.library.common.shuffle.orderedgrouped;\n\nimport java.io.DataInput;\nimport java.io.DataOutput;\nimport java.io.IOException;\n\nimport org.apache.hadoop.classification.InterfaceAudience;\nimport org.apache.hadoop.classification.InterfaceStability;\nimport org.apache.hadoop.io.Text;\nimport org.apache.hadoop.io.Writable;\nimport org.apache.hadoop.io.WritableUtils;\n\n\/**\n * Shuffle Header information that is sent by the TaskTracker and \n * deciphered by the Fetcher thread of Reduce task\n *\n *\/\n@InterfaceAudience.Private\n@InterfaceStability.Stable\npublic class ShuffleHeader implements Writable {\n \n \/** Header info of the shuffle http request\/response *\/\n public static final String HTTP_HEADER_NAME = \"name\";\n public static final String DEFAULT_HTTP_HEADER_NAME = \"mapreduce\";\n public static final String HTTP_HEADER_VERSION = \"version\";\n public static final String DEFAULT_HTTP_HEADER_VERSION = \"1.0.0\";\n\n \/**\n * The longest possible length of task attempt id that we will accept.\n *\/\n private static final int MAX_ID_LENGTH = 1000;\n\n String mapId;\n long uncompressedLength;\n long compressedLength;\n int forReduce;\n \n public ShuffleHeader() { }\n \n public ShuffleHeader(String mapId, long compressedLength,\n long uncompressedLength, int forReduce) {\n this.mapId = mapId;\n this.compressedLength = compressedLength;\n this.uncompressedLength = uncompressedLength;\n this.forReduce = forReduce;\n }\n \n public String getMapId() {\n return this.mapId;\n }\n \n public int getPartition() {\n return this.forReduce;\n }\n \n public long getUncompressedLength() {\n return uncompressedLength;\n }\n\n public long getCompressedLength() {\n return compressedLength;\n }\n\n public void readFields(DataInput in) throws IOException {\n mapId = WritableUtils.readStringSafely(in, MAX_ID_LENGTH);\n compressedLength = WritableUtils.readVLong(in);\n uncompressedLength = WritableUtils.readVLong(in);\n forReduce = WritableUtils.readVInt(in);\n }\n\n public int writeLength() throws IOException {\n int length = 0;\n int mapIdLength = Text.encode(mapId).limit();\n length += mapIdLength;\n\n length += WritableUtils.getVIntSize(mapIdLength);\n length += WritableUtils.getVIntSize(compressedLength);\n length += WritableUtils.getVIntSize(uncompressedLength);\n length += WritableUtils.getVIntSize(forReduce);\n\n return length;\n }\n public void write(DataOutput out) throws IOException {\n Text.writeString(out, mapId);\n WritableUtils.writeVLong(out, compressedLength);\n WritableUtils.writeVLong(out, uncompressedLength);\n WritableUtils.writeVInt(out, forReduce);\n }\n}","smell_code":" public int writeLength() throws IOException {\n int length = 0;\n int mapIdLength = Text.encode(mapId).limit();\n length += mapIdLength;\n\n length += WritableUtils.getVIntSize(mapIdLength);\n length += WritableUtils.getVIntSize(compressedLength);\n length += WritableUtils.getVIntSize(uncompressedLength);\n length += WritableUtils.getVIntSize(forReduce);\n\n return length;\n }","smell":"long method","id":159} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/*\n * $Id$\n *\/\npackage org.apache.xml.dtm.ref;\n\n\/**\n * The class ExtendedType represents an extended type object used by\n * ExpandedNameTable.\n *\/\npublic final class ExtendedType\n{\n private int nodetype;\n private String namespace;\n private String localName;\n private int hash;\n\n \/**\n * Create an ExtendedType object from node type, namespace and local name.\n * The hash code is calculated from the node type, namespace and local name.\n * \n * @param nodetype Type of the node\n * @param namespace Namespace of the node\n * @param localName Local name of the node\n *\/\n public ExtendedType (int nodetype, String namespace, String localName)\n {\n this.nodetype = nodetype;\n this.namespace = namespace;\n this.localName = localName;\n this.hash = nodetype + namespace.hashCode() + localName.hashCode();\n }\n\n \/**\n * Create an ExtendedType object from node type, namespace, local name\n * and a given hash code.\n * \n * @param nodetype Type of the node\n * @param namespace Namespace of the node\n * @param localName Local name of the node\n * @param hash The given hash code\n *\/\n public ExtendedType (int nodetype, String namespace, String localName, int hash)\n {\n this.nodetype = nodetype;\n this.namespace = namespace;\n this.localName = localName;\n this.hash = hash;\n }\n\n \/** \n * Redefine this ExtendedType object to represent a different extended type.\n * This is intended to be used ONLY on the hashET object. Using it elsewhere\n * will mess up existing hashtable entries!\n *\/\n protected void redefine(int nodetype, String namespace, String localName)\n {\n this.nodetype = nodetype;\n this.namespace = namespace;\n this.localName = localName;\n this.hash = nodetype + namespace.hashCode() + localName.hashCode();\n }\n\n \/** \n * Redefine this ExtendedType object to represent a different extended type.\n * This is intended to be used ONLY on the hashET object. Using it elsewhere\n * will mess up existing hashtable entries!\n *\/\n protected void redefine(int nodetype, String namespace, String localName, int hash)\n {\n this.nodetype = nodetype;\n this.namespace = namespace;\n this.localName = localName;\n this.hash = hash;\n }\n\n \/**\n * Override the hashCode() method in the Object class\n *\/\n public int hashCode()\n {\n return hash;\n }\n\n \/**\n * Test if this ExtendedType object is equal to the given ExtendedType.\n * \n * @param other The other ExtendedType object to test for equality\n * @return true if the two ExtendedType objects are equal.\n *\/\n public boolean equals(ExtendedType other)\n {\n try\n {\n return other.nodetype == this.nodetype &&\n other.localName.equals(this.localName) &&\n other.namespace.equals(this.namespace);\n }\n catch(NullPointerException e)\n {\n return false;\n }\n }\n \n \/**\n * Return the node type\n *\/\n public int getNodeType()\n {\n return nodetype;\n }\n \n \/**\n * Return the local name\n *\/\n public String getLocalName()\n {\n return localName;\n }\n \n \/**\n * Return the namespace\n *\/\n public String getNamespace()\n {\n return namespace;\n }\n\n}","smell_code":" public boolean equals(ExtendedType other)\n {\n try\n {\n return other.nodetype == this.nodetype &&\n other.localName.equals(this.localName) &&\n other.namespace.equals(this.namespace);\n }\n catch(NullPointerException e)\n {\n return false;\n }\n }","smell":"long method","id":160} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.camel.processor.aggregate;\n\n\/**\n * A default {@link org.apache.camel.processor.aggregate.AggregateController} that offers Java and JMX API.\n *\/\npublic class DefaultAggregateController implements AggregateController {\n\n private AggregateProcessor processor;\n\n public void onStart(AggregateProcessor processor) {\n this.processor = processor;\n }\n\n public void onStop(AggregateProcessor processor) {\n this.processor = null;\n }\n\n public int forceCompletionOfGroup(String key) {\n if (processor != null) {\n return processor.forceCompletionOfGroup(key);\n } else {\n return 0;\n }\n }\n\n public int forceCompletionOfAllGroups() {\n if (processor != null) {\n return processor.forceCompletionOfAllGroups();\n } else {\n return 0;\n }\n }\n\n}","smell_code":" public int forceCompletionOfGroup(String key) {\n if (processor != null) {\n return processor.forceCompletionOfGroup(key);\n } else {\n return 0;\n }\n }","smell":"long method","id":161} {"lang_cluster":"Java","source_code":"\/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.karaf.cellar.config.shell;\n\nimport org.apache.karaf.cellar.config.Constants;\nimport org.apache.karaf.cellar.config.shell.completers.ClusterConfigCompleter;\nimport org.apache.karaf.cellar.core.CellarSupport;\nimport org.apache.karaf.cellar.core.Configurations;\nimport org.apache.karaf.cellar.core.Group;\nimport org.apache.karaf.cellar.core.event.EventType;\nimport org.apache.karaf.cellar.core.shell.CellarCommandSupport;\nimport org.apache.karaf.cellar.core.shell.completer.AllGroupsCompleter;\nimport org.apache.karaf.shell.api.action.Argument;\nimport org.apache.karaf.shell.api.action.Command;\nimport org.apache.karaf.shell.api.action.Completion;\nimport org.apache.karaf.shell.api.action.Option;\nimport org.apache.karaf.shell.api.action.lifecycle.Service;\n\nimport java.util.Set;\n\n@Command(scope = \"cluster\", name = \"config-block\", description = \"Change the blocking policy for a bundle\")\n@Service\npublic class BlockCommand extends CellarCommandSupport {\n\n @Argument(index = 0, name = \"group\", description = \"The cluster group name\", required = true, multiValued = false)\n @Completion(AllGroupsCompleter.class)\n String groupName;\n\n @Argument(index = 1, name = \"pidPattern\", description = \"The configuration PID pattern\", required = false, multiValued = false)\n @Completion(ClusterConfigCompleter.class)\n String pid;\n\n @Option(name = \"-in\", description = \"Update the inbound direction\", required = false, multiValued = false)\n boolean in = false;\n\n @Option(name = \"-out\", description = \"Update the outbound direction\", required = false, multiValued = false)\n boolean out = false;\n\n @Option(name = \"-whitelist\", description = \"Allow the feature by updating the whitelist (false by default)\", required = false, multiValued = false)\n boolean whitelist = false;\n\n @Option(name = \"-blacklist\", description = \"Block the feature by updating the blacklist (true by default)\", required = false, multiValued = false)\n boolean blacklist = false;\n\n public Object doExecute() throws Exception {\n\n Group group = groupManager.findGroupByName(groupName);\n if (group == null) {\n System.err.println(\"Cluster group \" + groupName + \" doesn't exist\");\n return null;\n }\n\n CellarSupport support = new CellarSupport();\n support.setClusterManager(clusterManager);\n support.setGroupManager(groupManager);\n support.setConfigurationAdmin(configurationAdmin);\n\n if (!in && !out) {\n in = true;\n out = true;\n }\n if (!whitelist && !blacklist) {\n whitelist = true;\n blacklist = true;\n }\n\n if (pid == null || pid.isEmpty()) {\n \/\/ display mode\n if (in) {\n System.out.println(\"INBOUND:\");\n if (whitelist) {\n System.out.print(\"\\twhitelist: \");\n Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND);\n System.out.println(list.toString());\n }\n if (blacklist) {\n System.out.print(\"\\tblacklist: \");\n Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND);\n System.out.println(list.toString());\n }\n }\n if (out) {\n System.out.println(\"OUTBOUND:\");\n if (whitelist) {\n System.out.print(\"\\twhitelist: \");\n Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);\n System.out.println(list.toString());\n }\n if (blacklist) {\n System.out.print(\"\\tblacklist: \");\n Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);\n System.out.println(list.toString());\n }\n }\n } else {\n \/\/ edit mode\n System.out.println(\"Updating blocking policy for \" + pid);\n if (in) {\n if (whitelist) {\n System.out.println(\"\\tinbound whitelist ...\");\n support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);\n }\n if (blacklist) {\n System.out.println(\"\\tinbound blacklist ...\");\n support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);\n }\n }\n if (out) {\n if (whitelist) {\n System.out.println(\"\\toutbound whitelist ...\");\n support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);\n }\n if (blacklist) {\n System.out.println(\"\\toutbound blacklist ...\");\n support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);\n }\n }\n }\n\n return null;\n }\n\n}","smell_code":" public Object doExecute() throws Exception {\n\n Group group = groupManager.findGroupByName(groupName);\n if (group == null) {\n System.err.println(\"Cluster group \" + groupName + \" doesn't exist\");\n return null;\n }\n\n CellarSupport support = new CellarSupport();\n support.setClusterManager(clusterManager);\n support.setGroupManager(groupManager);\n support.setConfigurationAdmin(configurationAdmin);\n\n if (!in && !out) {\n in = true;\n out = true;\n }\n if (!whitelist && !blacklist) {\n whitelist = true;\n blacklist = true;\n }\n\n if (pid == null || pid.isEmpty()) {\n \/\/ display mode\n if (in) {\n System.out.println(\"INBOUND:\");\n if (whitelist) {\n System.out.print(\"\\twhitelist: \");\n Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND);\n System.out.println(list.toString());\n }\n if (blacklist) {\n System.out.print(\"\\tblacklist: \");\n Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND);\n System.out.println(list.toString());\n }\n }\n if (out) {\n System.out.println(\"OUTBOUND:\");\n if (whitelist) {\n System.out.print(\"\\twhitelist: \");\n Set list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);\n System.out.println(list.toString());\n }\n if (blacklist) {\n System.out.print(\"\\tblacklist: \");\n Set list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);\n System.out.println(list.toString());\n }\n }\n } else {\n \/\/ edit mode\n System.out.println(\"Updating blocking policy for \" + pid);\n if (in) {\n if (whitelist) {\n System.out.println(\"\\tinbound whitelist ...\");\n support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);\n }\n if (blacklist) {\n System.out.println(\"\\tinbound blacklist ...\");\n support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);\n }\n }\n if (out) {\n if (whitelist) {\n System.out.println(\"\\toutbound whitelist ...\");\n support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);\n }\n if (blacklist) {\n System.out.println(\"\\toutbound blacklist ...\");\n support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);\n }\n }\n }\n\n return null;\n }","smell":"long method","id":162} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.tajo.storage.jdbc;\n\nimport com.google.common.base.Function;\nimport org.apache.tajo.catalog.Column;\nimport org.apache.tajo.exception.TajoRuntimeException;\nimport org.apache.tajo.exception.UnsupportedException;\nimport org.apache.tajo.plan.Target;\nimport org.apache.tajo.plan.expr.EvalNode;\nimport org.apache.tajo.plan.logical.*;\nimport org.apache.tajo.util.StringUtils;\n\nimport javax.annotation.Nullable;\nimport java.sql.DatabaseMetaData;\nimport java.util.List;\nimport java.util.Stack;\n\n\/**\n * Generator to build a SQL statement from a plan fragment\n *\/\npublic class SQLBuilder {\n @SuppressWarnings(\"unused\")\n private final DatabaseMetaData dbMetaData;\n private final SQLExpressionGenerator sqlExprGen;\n\n public static class SQLBuilderContext {\n StringBuilder sb;\n }\n\n public SQLBuilder(DatabaseMetaData dbMetaData, SQLExpressionGenerator exprGen) {\n this.dbMetaData = dbMetaData;\n this.sqlExprGen = exprGen;\n }\n\n public String build(String tableName, Column [] targets, @Nullable EvalNode filter, @Nullable Long limit) {\n\n StringBuilder selectClause = new StringBuilder(\"SELECT \");\n if (targets.length > 0) {\n selectClause.append(StringUtils.join(targets, \",\", new Function() {\n @Override\n public String apply(@Nullable Column input) {\n return input.getSimpleName();\n }\n }));\n } else {\n selectClause.append(\"1\");\n }\n selectClause.append(\" \");\n\n StringBuilder fromClause = new StringBuilder(\"FROM \");\n fromClause.append(tableName).append(\" \");\n\n StringBuilder whereClause = null;\n if (filter != null) {\n whereClause = new StringBuilder(\"WHERE \");\n whereClause.append(sqlExprGen.generate(filter)).append(\" \");\n }\n\n StringBuilder limitClause = null;\n if (limit != null) {\n limitClause = new StringBuilder(\"LIMIT \");\n limitClause.append(limit).append(\" \");\n }\n\n return generateSelectStmt(selectClause, fromClause, whereClause, limitClause);\n }\n\n public String generateSelectStmt(StringBuilder selectClause,\n StringBuilder fromClause,\n @Nullable StringBuilder whereClause,\n @Nullable StringBuilder limitClause) {\n return\n selectClause.toString() +\n fromClause.toString() +\n (whereClause != null ? whereClause.toString() : \"\") +\n (limitClause != null ? limitClause.toString() : \"\");\n }\n\n public String build(LogicalNode planPart) {\n SQLBuilderContext context = new SQLBuilderContext();\n visit(context, planPart, new Stack());\n return context.sb.toString();\n }\n\n public void visit(SQLBuilderContext context, LogicalNode node, Stack stack) {\n stack.push(node);\n\n switch (node.getType()) {\n case SCAN:\n visitScan(context, (ScanNode) node, stack);\n break;\n\n case GROUP_BY:\n visitGroupBy(context, (GroupbyNode) node, stack);\n break;\n\n case SELECTION:\n visitFilter(context, (SelectionNode) node, stack);\n break;\n\n case PROJECTION:\n visitProjection(context, (ProjectionNode) node, stack);\n break;\n\n case TABLE_SUBQUERY:\n visitDerivedSubquery(context, (TableSubQueryNode) node, stack);\n break;\n\n default:\n throw new TajoRuntimeException(new UnsupportedException(\"plan node '\" + node.getType().name() + \"'\"));\n }\n\n stack.pop();\n }\n\n public void visitDerivedSubquery(SQLBuilderContext ctx, TableSubQueryNode derivedSubquery, Stack stack) {\n ctx.sb.append(\" (\");\n visit(ctx, derivedSubquery.getSubQuery(), stack);\n ctx.sb.append(\" ) \").append(derivedSubquery.getTableName());\n }\n\n public void visitProjection(SQLBuilderContext ctx, ProjectionNode projection, Stack stack) {\n\n visit(ctx, projection.getChild(), stack);\n }\n\n public void visitGroupBy(SQLBuilderContext ctx, GroupbyNode groupby, Stack stack) {\n visit(ctx, groupby.getChild(), stack);\n ctx.sb.append(\"GROUP BY \").append(StringUtils.join(groupby.getGroupingColumns(), \",\", 0)).append(\" \");\n }\n\n public void visitFilter(SQLBuilderContext ctx, SelectionNode filter, Stack stack) {\n visit(ctx, filter.getChild(), stack);\n ctx.sb.append(\"WHERE \" + sqlExprGen.generate(filter.getQual()));\n }\n\n public void visitScan(SQLBuilderContext ctx, ScanNode scan, Stack stack) {\n\n StringBuilder selectClause = new StringBuilder(\"SELECT \");\n if (scan.getTargets().size() > 0) {\n selectClause.append(generateTargetList(scan.getTargets()));\n } else {\n selectClause.append(\"1\");\n }\n\n selectClause.append(\" \");\n\n ctx.sb.append(\"FROM \").append(scan.getTableName()).append(\" \");\n\n if (scan.hasAlias()) {\n ctx.sb.append(\"AS \").append(scan.getAlias()).append(\" \");\n }\n\n if (scan.hasQual()) {\n ctx.sb.append(\"WHERE \" + sqlExprGen.generate(scan.getQual()));\n }\n }\n\n public String generateTargetList(List targets) {\n return StringUtils.join(targets, \",\", new Function() {\n @Override\n public String apply(@Nullable Target t) {\n StringBuilder sb = new StringBuilder(sqlExprGen.generate(t.getEvalTree()));\n if (t.hasAlias()) {\n sb.append(\" AS \").append(t.getAlias());\n }\n return sb.toString();\n }\n });\n }\n}","smell_code":" public void visit(SQLBuilderContext context, LogicalNode node, Stack stack) {\n stack.push(node);\n\n switch (node.getType()) {\n case SCAN:\n visitScan(context, (ScanNode) node, stack);\n break;\n\n case GROUP_BY:\n visitGroupBy(context, (GroupbyNode) node, stack);\n break;\n\n case SELECTION:\n visitFilter(context, (SelectionNode) node, stack);\n break;\n\n case PROJECTION:\n visitProjection(context, (ProjectionNode) node, stack);\n break;\n\n case TABLE_SUBQUERY:\n visitDerivedSubquery(context, (TableSubQueryNode) node, stack);\n break;\n\n default:\n throw new TajoRuntimeException(new UnsupportedException(\"plan node '\" + node.getType().name() + \"'\"));\n }\n\n stack.pop();\n }","smell":"long method","id":163} {"lang_cluster":"Java","source_code":"package basic;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class StreamC2 {\n\n public static void main(String[] args) {\n System.out.println(\"This is Java8\");\n }\n\n public static int run() {\n List integers = Arrays.asList(1, 2, 3, 4);\n List mapped = integers.stream().map(n -> n).collect(Collectors.toList());\n return mapped.size();\n }\n\n}","smell_code":" public static int run() {\n List integers = Arrays.asList(1, 2, 3, 4);\n List mapped = integers.stream().map(n -> n).collect(Collectors.toList());\n return mapped.size();\n }","smell":"long method","id":164} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.zookeeper.server;\n\n\n\nimport org.apache.zookeeper.common.Time;\nimport org.apache.zookeeper.server.metric.AvgMinMaxCounter;\nimport org.apache.zookeeper.server.quorum.BufferStats;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.concurrent.atomic.AtomicLong;\n\n\/**\n * Basic Server Statistics\n *\/\npublic class ServerStats {\n private static final Logger LOG = LoggerFactory.getLogger(ServerStats.class);\n\n private final AtomicLong packetsSent = new AtomicLong();\n private final AtomicLong packetsReceived = new AtomicLong();\n\n private final AvgMinMaxCounter requestLatency = new AvgMinMaxCounter(\"request_latency\");\n\n private AtomicLong fsyncThresholdExceedCount = new AtomicLong(0);\n\n private final BufferStats clientResponseStats = new BufferStats();\n\n private final Provider provider;\n private final long startTime = Time.currentElapsedTime();\n\n public interface Provider {\n public long getOutstandingRequests();\n public long getLastProcessedZxid();\n public String getState();\n public int getNumAliveConnections();\n public long getDataDirSize();\n public long getLogDirSize();\n }\n \n public ServerStats(Provider provider) {\n this.provider = provider;\n }\n \n \/\/ getters\n public long getMinLatency() {\n return requestLatency.getMin();\n }\n\n public double getAvgLatency() {\n return requestLatency.getAvg();\n }\n\n public long getMaxLatency() {\n return requestLatency.getMax();\n }\n\n public long getOutstandingRequests() {\n return provider.getOutstandingRequests();\n }\n \n public long getLastProcessedZxid(){\n return provider.getLastProcessedZxid();\n }\n\n public long getDataDirSize() {\n return provider.getDataDirSize();\n }\n\n public long getLogDirSize() {\n return provider.getLogDirSize();\n }\n \n public long getPacketsReceived() {\n return packetsReceived.get();\n }\n\n public long getPacketsSent() {\n return packetsSent.get();\n }\n\n public String getServerState() {\n return provider.getState();\n }\n \n \/** The number of client connections alive to this server *\/\n public int getNumAliveClientConnections() {\n \treturn provider.getNumAliveConnections();\n }\n\n public long getUptime() {\n return Time.currentElapsedTime() - startTime;\n }\n\n public boolean isProviderNull() {\n return provider == null;\n }\n\n @Override\n public String toString(){\n StringBuilder sb = new StringBuilder();\n sb.append(\"Latency min\/avg\/max: \" + getMinLatency() + \"\/\"\n + getAvgLatency() + \"\/\" + getMaxLatency() + \"\\n\");\n sb.append(\"Received: \" + getPacketsReceived() + \"\\n\");\n sb.append(\"Sent: \" + getPacketsSent() + \"\\n\");\n sb.append(\"Connections: \" + getNumAliveClientConnections() + \"\\n\");\n\n if (provider != null) {\n sb.append(\"Outstanding: \" + getOutstandingRequests() + \"\\n\");\n sb.append(\"Zxid: 0x\"+ Long.toHexString(getLastProcessedZxid())+ \"\\n\");\n }\n sb.append(\"Mode: \" + getServerState() + \"\\n\");\n return sb.toString();\n }\n\n \/**\n * Update request statistic. This should only be called from a request\n * that originated from that machine.\n *\/\n public void updateLatency(Request request, long currentTime) {\n long latency = currentTime - request.createTime;\n if (latency < 0) {\n return;\n }\n requestLatency.addDataPoint(latency);\n if (request.getHdr() != null) {\n \/\/ Only quorum request should have header\n ServerMetrics.UPDATE_LATENCY.add(latency);\n } else {\n \/\/ All read request should goes here\n ServerMetrics.READ_LATENCY.add(latency);\n }\n }\n\n public void resetLatency() {\n requestLatency.reset();\n }\n\n public void resetMaxLatency() {\n requestLatency.resetMax();\n }\n\n public void incrementPacketsReceived() {\n packetsReceived.incrementAndGet();\n }\n\n public void incrementPacketsSent() {\n packetsSent.incrementAndGet();\n }\n\n public void resetRequestCounters(){\n packetsReceived.set(0);\n packetsSent.set(0);\n }\n\n public long getFsyncThresholdExceedCount() {\n return fsyncThresholdExceedCount.get();\n }\n\n public void incrementFsyncThresholdExceedCount() {\n fsyncThresholdExceedCount.incrementAndGet();\n }\n\n public void resetFsyncThresholdExceedCount() {\n fsyncThresholdExceedCount.set(0);\n }\n\n public void reset() {\n resetLatency();\n resetRequestCounters();\n clientResponseStats.reset();\n ServerMetrics.resetAll();\n }\n\n public void updateClientResponseSize(int size) {\n clientResponseStats.setLastBufferSize(size);\n }\n\n public BufferStats getClientResponseStats() {\n return clientResponseStats;\n }\n}","smell_code":" public long getLastProcessedZxid(){\n return provider.getLastProcessedZxid();\n }","smell":"long method","id":165} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.pluto.container.impl;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.Collection;\n\nimport javax.portlet.ClientDataRequest;\nimport javax.portlet.PortletException;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.Part;\n\nimport org.apache.pluto.container.PortletRequestContext;\nimport org.apache.pluto.container.PortletResponseContext;\n\n\/**\n * Implementation of the javax.portlet.ClientDataRequest<\/code> interface.\n *\/\npublic abstract class ClientDataRequestImpl extends PortletRequestImpl implements ClientDataRequest\n{\n \/** Flag indicating if the HTTP body reader has been accessed. *\/\n protected boolean readerAccessed = false;\n\n public ClientDataRequestImpl(PortletRequestContext requestContext, PortletResponseContext responseContext, String lifecyclePhase)\n {\n super(requestContext, responseContext, lifecyclePhase);\n }\n\n private void checkPostedFormData() \n {\n if (getMethod().equals(\"POST\"))\n {\n String contentType = getContentType();\n if (contentType == null || contentType.equals(\"application\/x-www-form-urlencoded\"))\n {\n throw new IllegalStateException(\"User request HTTP POST data is of type \"\n + \"application\/x-www-form-urlencoded. \"\n + \"This data has been already processed \"\n + \"by the portlet-container and is available \"\n + \"as request parameters.\");\n }\n }\n }\n \n public java.lang.String getCharacterEncoding()\n {\n return getServletRequest().getCharacterEncoding();\n }\n\n public int getContentLength()\n {\n return getServletRequest().getContentLength();\n }\n\n @Override\n public long getContentLengthLong()\n {\n return getServletRequest().getContentLengthLong();\n }\n\n @Override\n public Part getPart(String name) throws IOException, PortletException\n {\n try {\n return getServletRequest().getPart(name);\n } catch (ServletException e) {\n throw new PortletException(e);\n }\n }\n\n @Override\n public Collection getParts() throws IOException, PortletException\n {\n try {\n return getServletRequest().getParts();\n } catch (ServletException e) {\n throw new PortletException(e);\n }\n }\n\n public java.lang.String getContentType()\n {\n return getServletRequest().getContentType();\n }\n \n public String getMethod()\n {\n return getServletRequest().getMethod();\n }\n\n public InputStream getPortletInputStream() throws IOException\n {\n checkPostedFormData();\n \/\/ the HttpServletRequest will ensure that a IllegalStateException is thrown\n \/\/ if getReader() was called earlier \n return getServletRequest().getInputStream();\n }\n\n public BufferedReader getReader()\n throws UnsupportedEncodingException, IOException \n {\n checkPostedFormData();\n \/\/ the HttpServletRequest will ensure that a IllegalStateException is thrown\n \/\/ if getInputStream() was called earlier\n BufferedReader reader = getServletRequest().getReader();\n readerAccessed = true;\n return reader;\n\n }\n \n public void setCharacterEncoding(String encoding)\n throws UnsupportedEncodingException \n {\n if (readerAccessed) \n {\n throw new IllegalStateException(\"Cannot set character encoding \"\n + \"after HTTP body reader is accessed.\");\n }\n getServletRequest().setCharacterEncoding(encoding);\n }\n}","smell_code":" private void checkPostedFormData() \n {\n if (getMethod().equals(\"POST\"))\n {\n String contentType = getContentType();\n if (contentType == null || contentType.equals(\"application\/x-www-form-urlencoded\"))\n {\n throw new IllegalStateException(\"User request HTTP POST data is of type \"\n + \"application\/x-www-form-urlencoded. \"\n + \"This data has been already processed \"\n + \"by the portlet-container and is available \"\n + \"as request parameters.\");\n }\n }\n }","smell":"long method","id":166} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.storm.starter.tools;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\n\nimport java.io.Serializable;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Rankings implements Serializable {\n \n private static final long serialVersionUID = -1549827195410578903L;\n private static final int DEFAULT_COUNT = 10;\n \n private final int maxSize;\n private final List rankedItems = Lists.newArrayList();\n \n public Rankings() {\n this(DEFAULT_COUNT);\n }\n \n public Rankings(int topN) {\n if (topN < 1) {\n throw new IllegalArgumentException(\"topN must be >= 1\");\n }\n maxSize = topN;\n }\n \n \/**\n * Copy constructor.\n * \n * @param other\n *\/\n public Rankings(Rankings other) {\n this(other.maxSize());\n updateWith(other);\n }\n \n \/**\n * @return the maximum possible number (size) of ranked objects this\n * instance can hold\n *\/\n public int maxSize() {\n return maxSize;\n }\n \n \/**\n * @return the number (size) of ranked objects this instance is currently\n * holding\n *\/\n public int size() {\n return rankedItems.size();\n }\n \n \/**\n * The returned defensive copy is only \"somewhat\" defensive. We do, for\n * instance, return a defensive copy of the enclosing List instance, and we\n * do try to defensively copy any contained Rankable objects, too. However,\n * the contract of {@link org.apache.storm.starter.tools.Rankable#copy()}\n * does not guarantee that any Object's embedded within a Rankable will be\n * defensively copied, too.\n *\n * @return a somewhat defensive copy of ranked items\n *\/\n public List getRankings() {\n List copy = Lists.newLinkedList();\n for (Rankable r : rankedItems) {\n copy.add(r.copy());\n }\n return ImmutableList.copyOf(copy);\n }\n \n public void updateWith(Rankings other) {\n for (Rankable r : other.getRankings()) {\n updateWith(r);\n }\n }\n \n public void updateWith(Rankable r) {\n synchronized (rankedItems) {\n addOrReplace(r);\n rerank();\n shrinkRankingsIfNeeded();\n }\n }\n \n private void addOrReplace(Rankable r) {\n Integer rank = findRankOf(r);\n if (rank != null) {\n rankedItems.set(rank, r);\n } else {\n rankedItems.add(r);\n }\n }\n \n private Integer findRankOf(Rankable r) {\n Object tag = r.getObject();\n for (int rank = 0; rank < rankedItems.size(); rank++) {\n Object cur = rankedItems.get(rank).getObject();\n if (cur.equals(tag)) {\n return rank;\n }\n }\n return null;\n }\n \n private void rerank() {\n Collections.sort(rankedItems);\n Collections.reverse(rankedItems);\n }\n \n private void shrinkRankingsIfNeeded() {\n if (rankedItems.size() > maxSize) {\n rankedItems.remove(maxSize);\n }\n }\n \n \/**\n * Removes ranking entries that have a count of zero.\n *\/\n public void pruneZeroCounts() {\n int i = 0;\n while (i < rankedItems.size()) {\n if (rankedItems.get(i).getCount() == 0) {\n rankedItems.remove(i);\n } else {\n i++;\n }\n }\n }\n \n public String toString() {\n return rankedItems.toString();\n }\n \n \/**\n * Creates a (defensive) copy of itself.\n *\/\n public Rankings copy() {\n return new Rankings(this);\n }\n}","smell_code":" private Integer findRankOf(Rankable r) {\n Object tag = r.getObject();\n for (int rank = 0; rank < rankedItems.size(); rank++) {\n Object cur = rankedItems.get(rank).getObject();\n if (cur.equals(tag)) {\n return rank;\n }\n }\n return null;\n }","smell":"long method","id":167} {"lang_cluster":"Java","source_code":"\/* ====================================================================\n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to You under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n==================================================================== *\/\npackage org.apache.poi.hssf.converter;\n\nimport org.apache.poi.POIDataSamples;\nimport org.apache.poi.hssf.usermodel.HSSFWorkbook;\nimport org.apache.poi.util.XMLHelper;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\n\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.io.StringWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport static org.junit.Assert.assertNotNull;\n\n@RunWith(Parameterized.class)\npublic class TestExcelConverterSuite\n{\n \/**\n * YK: a quick hack to exclude failing documents from the suite.\n *\/\n @SuppressWarnings(\"ArraysAsListWithZeroOrOneArgument\")\n private static List failingFiles = Arrays.asList(\n \/* not failing, but requires more memory *\/\n \"ex45698-22488.xls\" );\n\n @Parameterized.Parameters(name=\"{index}: {0}\")\n public static Iterable files() {\n List files = new ArrayList<>();\n File directory = POIDataSamples.getDocumentInstance().getFile(\n \"..\/spreadsheet\" );\n for ( final File child : directory.listFiles( new FilenameFilter()\n {\n @Override\n public boolean accept( File dir, String name )\n {\n return name.endsWith( \".xls\" ) && !failingFiles.contains( name );\n }\n } ) )\n {\n files.add(new Object[] { child });\n }\n\n return files;\n }\n\n\n @Parameterized.Parameter\n public File child;\n\n @Test\n public void testFo() throws Exception\n {\n HSSFWorkbook workbook;\n try {\n workbook = ExcelToHtmlUtils.loadXls( child );\n } catch ( Exception exc ) {\n \/\/ unable to parse file -- not ExcelToFoConverter fault\n return;\n }\n\n ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(\n XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() );\n excelToHtmlConverter.processWorkbook( workbook );\n\n StringWriter stringWriter = new StringWriter();\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty( OutputKeys.ENCODING, \"utf-8\" );\n transformer.setOutputProperty( OutputKeys.INDENT, \"yes\" );\n transformer.setOutputProperty( OutputKeys.METHOD, \"xml\" );\n transformer.transform(\n new DOMSource( excelToHtmlConverter.getDocument() ),\n new StreamResult( stringWriter ) );\n\n assertNotNull(stringWriter.toString());\n }\n\n @Test\n public void testHtml() throws Exception\n {\n HSSFWorkbook workbook;\n try {\n workbook = ExcelToHtmlUtils.loadXls( child );\n } catch ( Exception exc ) {\n \/\/ unable to parse file -- not ExcelToFoConverter fault\n return;\n }\n\n ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(\n XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() );\n excelToHtmlConverter.processWorkbook( workbook );\n\n StringWriter stringWriter = new StringWriter();\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty( OutputKeys.ENCODING, \"utf-8\" );\n transformer.setOutputProperty( OutputKeys.INDENT, \"no\" );\n transformer.setOutputProperty( OutputKeys.METHOD, \"html\" );\n transformer.transform(\n new DOMSource( excelToHtmlConverter.getDocument() ),\n new StreamResult( stringWriter ) );\n\n assertNotNull(stringWriter.toString());\n }\n}","smell_code":" @Test\n public void testHtml() throws Exception\n {\n HSSFWorkbook workbook;\n try {\n workbook = ExcelToHtmlUtils.loadXls( child );\n } catch ( Exception exc ) {\n \/\/ unable to parse file -- not ExcelToFoConverter fault\n return;\n }\n\n ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(\n XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() );\n excelToHtmlConverter.processWorkbook( workbook );\n\n StringWriter stringWriter = new StringWriter();\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty( OutputKeys.ENCODING, \"utf-8\" );\n transformer.setOutputProperty( OutputKeys.INDENT, \"no\" );\n transformer.setOutputProperty( OutputKeys.METHOD, \"html\" );\n transformer.transform(\n new DOMSource( excelToHtmlConverter.getDocument() ),\n new StreamResult( stringWriter ) );\n\n assertNotNull(stringWriter.toString());\n }","smell":"long method","id":168} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.apache.syncope.core.provisioning.java.data;\n\nimport java.util.Iterator;\nimport java.util.stream.Collectors;\nimport org.apache.syncope.common.lib.SyncopeClientException;\nimport org.apache.syncope.common.lib.to.ApplicationTO;\nimport org.apache.syncope.common.lib.to.PrivilegeTO;\nimport org.apache.syncope.common.lib.types.ClientExceptionType;\nimport org.apache.syncope.core.persistence.api.dao.ApplicationDAO;\nimport org.apache.syncope.core.persistence.api.entity.Application;\nimport org.apache.syncope.core.persistence.api.entity.EntityFactory;\nimport org.apache.syncope.core.persistence.api.entity.Privilege;\nimport org.apache.syncope.core.provisioning.api.data.ApplicationDataBinder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class ApplicationDataBinderImpl implements ApplicationDataBinder {\n\n private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBinder.class);\n\n @Autowired\n private ApplicationDAO applicationDAO;\n\n @Autowired\n private EntityFactory entityFactory;\n\n @Override\n public Application create(final ApplicationTO applicationTO) {\n return update(entityFactory.newEntity(Application.class), applicationTO);\n }\n\n @Override\n public Application update(final Application toBeUpdated, final ApplicationTO applicationTO) {\n toBeUpdated.setKey(applicationTO.getKey());\n Application application = applicationDAO.save(toBeUpdated);\n\n application.setDescription(applicationTO.getDescription());\n\n \/\/ 1. add or update all (valid) privileges from TO\n applicationTO.getPrivileges().forEach(privilegeTO -> {\n if (privilegeTO == null) {\n LOG.error(\"Null {}\", PrivilegeTO.class.getSimpleName());\n } else {\n Privilege privilege = applicationDAO.findPrivilege(privilegeTO.getKey());\n if (privilege == null) {\n privilege = entityFactory.newEntity(Privilege.class);\n privilege.setKey(privilegeTO.getKey());\n privilege.setApplication(application);\n\n application.add(privilege);\n } else if (!application.equals(privilege.getApplication())) {\n SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidPrivilege);\n sce.getElements().add(\n \"Privilege \" + privilege.getKey() + \" already owned by \" + privilege.getApplication());\n throw sce;\n }\n\n privilege.setDescription(privilegeTO.getDescription());\n privilege.setSpec(privilegeTO.getSpec());\n }\n });\n\n \/\/ 2. remove all privileges not contained in the TO\n for (Iterator itor = application.getPrivileges().iterator(); itor.hasNext();) {\n Privilege privilege = itor.next();\n if (!applicationTO.getPrivileges().stream().\n anyMatch(privilegeTO -> privilege.getKey().equals(privilegeTO.getKey()))) {\n\n privilege.setApplication(null);\n itor.remove();\n }\n }\n\n return application;\n }\n\n @Override\n public PrivilegeTO getPrivilegeTO(final Privilege privilege) {\n PrivilegeTO privilegeTO = new PrivilegeTO();\n privilegeTO.setKey(privilege.getKey());\n privilegeTO.setDescription(privilege.getDescription());\n privilegeTO.setApplication(privilege.getApplication().getKey());\n privilegeTO.setSpec(privilege.getSpec());\n return privilegeTO;\n }\n\n @Override\n public ApplicationTO getApplicationTO(final Application application) {\n ApplicationTO applicationTO = new ApplicationTO();\n\n applicationTO.setKey(application.getKey());\n applicationTO.setDescription(application.getDescription());\n applicationTO.getPrivileges().addAll(\n application.getPrivileges().stream().map(privilege -> getPrivilegeTO(privilege)).\n collect(Collectors.toList()));\n\n return applicationTO;\n }\n\n}","smell_code":" @Override\n public PrivilegeTO getPrivilegeTO(final Privilege privilege) {\n PrivilegeTO privilegeTO = new PrivilegeTO();\n privilegeTO.setKey(privilege.getKey());\n privilegeTO.setDescription(privilege.getDescription());\n privilegeTO.setApplication(privilege.getApplication().getKey());\n privilegeTO.setSpec(privilege.getSpec());\n return privilegeTO;\n }","smell":"long method","id":169} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2017 Pivotal Software, Inc.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * https:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * Pivotal Software, Inc. - initial API and implementation\n *******************************************************************************\/\npackage org.springframework.ide.eclipse.boot.wizard;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.eclipse.jface.layout.GridDataFactory;\nimport org.eclipse.jface.layout.GridLayoutFactory;\nimport org.eclipse.swt.SWT;\nimport org.eclipse.swt.graphics.Point;\nimport org.eclipse.swt.widgets.Composite;\nimport org.eclipse.swt.widgets.Display;\nimport org.springframework.ide.eclipse.boot.core.initializr.InitializrServiceSpec.Dependency;\nimport org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;\nimport org.springsource.ide.eclipse.commons.livexp.ui.ExpandableSection;\nimport org.springsource.ide.eclipse.commons.livexp.ui.IPageWithSections;\nimport org.springsource.ide.eclipse.commons.livexp.ui.Scroller;\nimport org.springsource.ide.eclipse.commons.livexp.ui.WizardPageSection;\nimport org.springsource.ide.eclipse.commons.livexp.util.Filter;\n\npublic class FilteredDependenciesSection extends WizardPageSection {\n\n\tprivate Composite dependencyArea;\n\tprivate Scroller scroller;\n\n\tprivate LiveExpression> filter;\n\n\tprivate Point sizeHint = new Point(SWT.DEFAULT, SWT.DEFAULT);\n\n\tprivate int columns = 1;\n\tprivate HierarchicalMultiSelectionFieldModel dependencies;\n\n\tpublic FilteredDependenciesSection(IPageWithSections owner, NewSpringBootWizardModel model,\n\t\t\tLiveExpression> filter) {\n\t\tthis(owner, model.dependencies, filter);\n\t}\n\n\tpublic FilteredDependenciesSection(IPageWithSections owner, HierarchicalMultiSelectionFieldModel dependencies,\n\t\t\tLiveExpression> filter) {\n\t\tsuper(owner);\n\t\tthis.dependencies = dependencies;\n\t\tthis.filter = filter;\n\t}\n\n\tpublic FilteredDependenciesSection sizeHint(Point sizeHint) {\n\t\tif (sizeHint != null) {\n\t\t\tthis.sizeHint = sizeHint;\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic FilteredDependenciesSection columns(int columns) {\n\t\tthis.columns = columns;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic void createContents(Composite page) {\n\t\tscroller = new Scroller(page);\n\t\tGridDataFactory.fillDefaults().grab(true, true).minSize(sizeHint).hint(sizeHint).applyTo(scroller);\n\t\tdependencyArea = scroller.getBody();\n\t\tGridLayoutFactory.fillDefaults().applyTo(dependencyArea);\n\t\tGridDataFactory.fillDefaults().grab(true, true).applyTo(dependencyArea);\n\t\tMap> sectionsToRefresh = new HashMap<>();\n\t\tfor (String cat : dependencies.getCategories()) {\n\t\t\tMultiSelectionFieldModel dependencyGroup = dependencies.getContents(cat);\n\t\t\tCheckBoxesSection checkboxesSection = new CheckBoxesSection<>(owner,\n\t\t\t\t\tdependencyGroup.getCheckBoxModels()).columns(columns);\n\t\t\tCheckboxExpandableSection expandable = new CheckboxExpandableSection<>(owner, dependencyGroup.getLabel(), checkboxesSection);\n\t\t\texpandable.createContents(dependencyArea);\n\n\t\t\t\/\/ Always expanded as it only shows selections. If there are no\n\t\t\t\/\/ selections, the expandable\n\t\t\t\/\/ section itself is hidden\n\t\t\texpandable.getExpansionState().setValue(false);\n\n\t\t\tsectionsToRefresh.put(cat, expandable);\n\t\t}\n\t\tthis.filter.addListener((exp, value) -> {\n\t\t\t\/\/ PT 143003753: there is a bit of lag when deleting characters in text filter that produce a lot of\n\t\t\t\/\/ results. Consequently running this asynchronously.\n\t\t\tDisplay.getCurrent().asyncExec(() -> {\n\t\t\t\tfor (String cat : dependencies.getCategories()) {\n\t\t\t\t\tCheckboxExpandableSection expandable = sectionsToRefresh.get(cat);\n\t\t\t\t\tif (expandable != null) {\n\t\t\t\t\t\tonFilter(expandable, expandable.getCheckBoxSection(), cat);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate void onFilter(ExpandableSection expandable, CheckBoxesSection checkboxesSection, String cat) {\n\t\tFilter filter = this.filter.getValue();\n\t\tcheckboxesSection.applyFilter(filter);\n\t\tboolean isTrivialFilter = filter==null || filter.isTrivial();\n\t\tif (checkboxesSection.isCreated()) {\n\t\t\tboolean hasVisible = checkboxesSection.hasVisible();\n\t\t\texpandable.setVisible(hasVisible);\n\t\t\tif (hasVisible) {\n\t\t\t\texpandable.getExpansionState().setValue(!isTrivialFilter);\n\t\t\t}\n\t\t}\n\t\tlayout();\n\t}\n\n\tprivate void layout() {\n\t\tif (dependencyArea != null && !dependencyArea.isDisposed()) {\n\t\t\tdependencyArea.layout(true);\n\t\t\tdependencyArea.getParent().layout(true);\n\t\t}\n\t}\n\n\tstatic class CheckboxExpandableSection extends ExpandableSection {\n\n\t\tprivate CheckBoxesSection checkBoxSection;\n\t\tpublic CheckboxExpandableSection(IPageWithSections owner, String title, CheckBoxesSection checkBoxSection) {\n\t\t\tsuper(owner, title, checkBoxSection);\n\t\t\tthis.checkBoxSection = checkBoxSection;\n\t\t}\n\n\t\tpublic CheckBoxesSection getCheckBoxSection() {\n\t\t\treturn checkBoxSection;\n\t\t}\n\n\t}\n}","smell_code":"\tprivate void onFilter(ExpandableSection expandable, CheckBoxesSection checkboxesSection, String cat) {\n\t\tFilter filter = this.filter.getValue();\n\t\tcheckboxesSection.applyFilter(filter);\n\t\tboolean isTrivialFilter = filter==null || filter.isTrivial();\n\t\tif (checkboxesSection.isCreated()) {\n\t\t\tboolean hasVisible = checkboxesSection.hasVisible();\n\t\t\texpandable.setVisible(hasVisible);\n\t\t\tif (hasVisible) {\n\t\t\t\texpandable.getExpansionState().setValue(!isTrivialFilter);\n\t\t\t}\n\t\t}\n\t\tlayout();\n\t}","smell":"long method","id":170} {"lang_cluster":"Java","source_code":"\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See License.txt in the repository root.\n\npackage com.microsoft.tfs.client.eclipse.project;\n\nimport java.text.MessageFormat;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.eclipse.core.resources.IProject;\nimport org.eclipse.core.resources.IResourceChangeEvent;\nimport org.eclipse.core.resources.IResourceChangeListener;\nimport org.eclipse.core.runtime.CoreException;\n\nimport com.microsoft.tfs.client.common.repository.TFSRepository;\nimport com.microsoft.tfs.client.eclipse.TFSRepositoryProvider;\nimport com.microsoft.tfs.client.eclipse.util.TeamUtils;\nimport com.microsoft.tfs.util.Check;\n\npublic class ProjectCloseListener implements IResourceChangeListener {\n private final Log log = LogFactory.getLog(ProjectCloseListener.class);\n\n private final ProjectRepositoryManager projectManager;\n\n public ProjectCloseListener(final ProjectRepositoryManager projectManager) {\n Check.notNull(projectManager, \"projectManager\"); \/\/$NON-NLS-1$\n\n this.projectManager = projectManager;\n }\n\n @Override\n public void resourceChanged(final IResourceChangeEvent event) {\n if (event.getType() != IResourceChangeEvent.PRE_CLOSE || !(event.getResource() instanceof IProject)) {\n return;\n }\n\n final IProject project = (IProject) event.getResource();\n\n if (!project.isOpen()) {\n \/* Sanity check *\/\n log.error(\n MessageFormat.format(\n \"Project Manager received close notification for project {0} (already closed)\", \/\/$NON-NLS-1$\n project.getName()));\n\n return;\n }\n\n \/* Exit if we don't manage this project *\/\n String providerName;\n try {\n providerName = project.getPersistentProperty(TeamUtils.PROVIDER_PROP_KEY);\n } catch (final CoreException e) {\n log.warn(\n MessageFormat.format(\n \"Could not query repository manager for project {0} (when handling close notification)\", \/\/$NON-NLS-1$\n project.getName()),\n e);\n return;\n }\n\n if (providerName == null || !providerName.equals(TFSRepositoryProvider.PROVIDER_ID)) {\n return;\n }\n\n \/*\n * If this is the only project for this connection, it will be\n * disconnected, thus we need to prompt for unsaved WIT changes.\n *\/\n final TFSRepository repository = projectManager.getRepository(project);\n\n if (repository != null) {\n final IProject[] allRepositoryProjects = projectManager.getProjectsForRepository(repository);\n\n if (allRepositoryProjects.length == 1 && allRepositoryProjects[0] == project) {\n \/*\n * Note: we have to ignore the cancel button here, there is no\n * way to prevent the close from occurring.\n *\/\n ProjectManagerDataProviderFactory.getDataProvider().promptForDisconnect();\n }\n }\n\n projectManager.close(project);\n }\n}","smell_code":" public ProjectCloseListener(final ProjectRepositoryManager projectManager) {\n Check.notNull(projectManager, \"projectManager\"); \/\/$NON-NLS-1$\n\n this.projectManager = projectManager;\n }","smell":"long method","id":171} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.nifi.remote.cluster;\n\npublic class NodeInformation {\n\n private final String siteToSiteHostname;\n private final Integer siteToSitePort;\n private final Integer siteToSiteHttpApiPort;\n private final int apiPort;\n private final boolean isSiteToSiteSecure;\n private final int totalFlowFiles;\n\n public NodeInformation(final String siteToSiteHostname, final Integer siteToSitePort, final Integer siteToSiteHttpApiPort,\n final int apiPort, final boolean isSiteToSiteSecure, final int totalFlowFiles) {\n this.siteToSiteHostname = siteToSiteHostname;\n this.siteToSitePort = siteToSitePort;\n this.siteToSiteHttpApiPort = siteToSiteHttpApiPort;\n this.apiPort = apiPort;\n this.isSiteToSiteSecure = isSiteToSiteSecure;\n this.totalFlowFiles = totalFlowFiles;\n }\n\n public String getSiteToSiteHostname() {\n return siteToSiteHostname;\n }\n\n public int getAPIPort() {\n return apiPort;\n }\n\n public Integer getSiteToSitePort() {\n return siteToSitePort;\n }\n\n public Integer getSiteToSiteHttpApiPort() {\n return siteToSiteHttpApiPort;\n }\n\n public boolean isSiteToSiteSecure() {\n return isSiteToSiteSecure;\n }\n\n public int getTotalFlowFiles() {\n return totalFlowFiles;\n }\n\n @Override\n public boolean equals(final Object obj) {\n if (obj == this) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (!(obj instanceof NodeInformation)) {\n return false;\n }\n\n final NodeInformation other = (NodeInformation) obj;\n if (!siteToSiteHostname.equals(other.siteToSiteHostname)) {\n return false;\n }\n if (siteToSitePort == null && other.siteToSitePort != null) {\n return false;\n }\n if (siteToSitePort != null && other.siteToSitePort == null) {\n return false;\n } else if (siteToSitePort != null && siteToSitePort.intValue() != other.siteToSitePort.intValue()) {\n return false;\n }\n\n if (siteToSiteHttpApiPort == null && other.siteToSiteHttpApiPort != null) {\n return false;\n }\n if (siteToSiteHttpApiPort != null && other.siteToSiteHttpApiPort == null) {\n return false;\n } else if (siteToSiteHttpApiPort != null && siteToSiteHttpApiPort.intValue() != other.siteToSiteHttpApiPort.intValue()) {\n return false;\n }\n\n if (apiPort != other.apiPort) {\n return false;\n }\n if (isSiteToSiteSecure != other.isSiteToSiteSecure) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n return 83832 + siteToSiteHostname.hashCode() + (siteToSitePort == null ? 8 : siteToSitePort.hashCode()) + apiPort + (isSiteToSiteSecure ? 3829 : 0);\n }\n\n @Override\n public String toString() {\n return \"Node[\" + siteToSiteHostname + \":\" + apiPort + \"]\";\n }\n}","smell_code":" public boolean isSiteToSiteSecure() {\n return isSiteToSiteSecure;\n }","smell":"long method","id":172} {"lang_cluster":"Java","source_code":"\/****************************************************************\n * Licensed to the Apache Software Foundation (ASF) under one *\n * or more contributor license agreements. See the NOTICE file *\n * distributed with this work for additional information *\n * regarding copyright ownership. The ASF licenses this file *\n * to you under the Apache License, Version 2.0 (the *\n * \"License\"); you may not use this file except in compliance *\n * with the License. You may obtain a copy of the License at *\n * *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\n * *\n * Unless required by applicable law or agreed to in writing, *\n * software distributed under the License is distributed on an *\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *\n * KIND, either express or implied. See the License for the *\n * specific language governing permissions and limitations *\n * under the License. *\n ****************************************************************\/\npackage org.apache.james.modules.data;\n\nimport static org.apache.james.modules.data.JPAConfiguration.Credential.NO_CREDENTIAL;\nimport static org.apache.james.modules.data.JPAConfiguration.ReadyToBuild.NO_TEST_ON_BORROW;\nimport static org.apache.james.modules.data.JPAConfiguration.ReadyToBuild.NO_VALIDATION_QUERY;\nimport static org.apache.james.modules.data.JPAConfiguration.ReadyToBuild.NO_VALIDATION_QUERY_TIMEOUT_SEC;\n\nimport java.util.Optional;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Preconditions;\n\npublic class JPAConfiguration {\n\n public static class Credential {\n private static final Logger LOGGER = LoggerFactory.getLogger(Credential.class);\n static final Optional NO_CREDENTIAL = Optional.empty();\n\n public static Optional of(String username, String password) {\n if (StringUtils.isBlank(username) && StringUtils.isBlank(password)) {\n LOGGER.debug(\"username and password are blank, returns no credential by default\");\n return NO_CREDENTIAL;\n }\n\n return Optional.of(new Credential(username, password));\n }\n\n private final String username;\n private final String password;\n\n private Credential(String username, String password) {\n Preconditions.checkArgument(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password),\n \"username and password for connecting to database can't be blank\");\n this.username = username;\n this.password = password;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n return password;\n }\n }\n\n @FunctionalInterface\n public interface RequireDriverName {\n RequireDriverURL driverName(String driverName);\n }\n\n @FunctionalInterface\n public interface RequireDriverURL {\n ReadyToBuild driverURL(String driverUrl);\n }\n\n public static class ReadyToBuild {\n static final Optional NO_TEST_ON_BORROW = Optional.empty();\n static final Optional NO_VALIDATION_QUERY_TIMEOUT_SEC = Optional.empty();\n static final Optional NO_VALIDATION_QUERY = Optional.empty();\n\n private final String driverName;\n private final String driverURL;\n\n private Optional credential;\n private Optional testOnBorrow;\n private Optional validationQueryTimeoutSec;\n private Optional validationQuery;\n\n\n private ReadyToBuild(String driverName, String driverURL, Optional credential,\n Optional testOnBorrow, Optional validationQueryTimeoutSec,\n Optional validationQuery) {\n this.driverName = driverName;\n this.driverURL = driverURL;\n this.credential = credential;\n this.testOnBorrow = testOnBorrow;\n this.validationQueryTimeoutSec = validationQueryTimeoutSec;\n this.validationQuery = validationQuery;\n }\n\n public JPAConfiguration build() {\n return new JPAConfiguration(driverName, driverURL, credential, testOnBorrow, validationQueryTimeoutSec, validationQuery);\n }\n\n public RequirePassword username(String username) {\n return password -> new ReadyToBuild(driverName, driverURL, Credential.of(username, password),\n testOnBorrow, validationQueryTimeoutSec, validationQuery);\n }\n\n public ReadyToBuild testOnBorrow(Boolean testOnBorrow) {\n this.testOnBorrow = Optional.ofNullable(testOnBorrow);\n return this;\n }\n\n public ReadyToBuild validationQueryTimeoutSec(Integer validationQueryTimeoutSec) {\n this.validationQueryTimeoutSec = Optional.ofNullable(validationQueryTimeoutSec);\n return this;\n }\n\n public ReadyToBuild validationQuery(String validationQuery) {\n this.validationQuery = Optional.ofNullable(validationQuery);\n return this;\n }\n }\n\n @FunctionalInterface\n public interface RequirePassword {\n ReadyToBuild password(String password);\n }\n\n public static RequireDriverName builder() {\n return driverName -> driverURL -> new ReadyToBuild(driverName, driverURL, NO_CREDENTIAL, NO_TEST_ON_BORROW,\n NO_VALIDATION_QUERY_TIMEOUT_SEC, NO_VALIDATION_QUERY);\n }\n\n private final String driverName;\n private final String driverURL;\n private final Optional testOnBorrow;\n private final Optional validationQueryTimeoutSec;\n private final Optional credential;\n private final Optional validationQuery;\n\n @VisibleForTesting\n JPAConfiguration(String driverName, String driverURL, Optional credential, Optional testOnBorrow,\n Optional validationQueryTimeoutSec, Optional validationQuery) {\n Preconditions.checkNotNull(driverName, \"driverName cannot be null\");\n Preconditions.checkNotNull(driverURL, \"driverURL cannot be null\");\n validationQueryTimeoutSec.ifPresent(timeoutInSec ->\n Preconditions.checkArgument(timeoutInSec > 0, \"validationQueryTimeoutSec is required to be greater than 0\"));\n\n this.driverName = driverName;\n this.driverURL = driverURL;\n this.credential = credential;\n this.testOnBorrow = testOnBorrow;\n this.validationQueryTimeoutSec = validationQueryTimeoutSec;\n this.validationQuery = validationQuery;\n }\n\n public String getDriverName() {\n return driverName;\n }\n\n public String getDriverURL() {\n return driverURL;\n }\n\n public Optional isTestOnBorrow() {\n return testOnBorrow;\n }\n\n public Optional getValidationQueryTimeoutSec() {\n return validationQueryTimeoutSec;\n }\n\n public Optional getValidationQuery() {\n return validationQuery;\n }\n\n public Optional getCredential() {\n return credential;\n }\n}","smell_code":" public String getUsername() {\n return username;\n }","smell":"long method","id":173} {"lang_cluster":"Java","source_code":"\/\/\n\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\/\/\n\npackage com.cloud.agent.api.sync;\n\nimport java.util.Objects;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\nimport com.cloud.agent.api.Answer;\nimport com.cloud.agent.api.Command;\n\npublic class SyncNuageVspCmsIdAnswer extends Answer {\n\n private final boolean _success;\n private final String _nuageVspCmsId;\n private final SyncNuageVspCmsIdCommand.SyncType _syncType;\n\n public SyncNuageVspCmsIdAnswer(boolean success, String nuageVspCmsId, SyncNuageVspCmsIdCommand.SyncType syncType) {\n super();\n this._success = success;\n this._nuageVspCmsId = nuageVspCmsId;\n this._syncType = syncType;\n }\n\n public SyncNuageVspCmsIdAnswer(Command command, Exception e, SyncNuageVspCmsIdCommand.SyncType syncType) {\n super(command, e);\n this._nuageVspCmsId = null;\n this._success = false;\n this._syncType = syncType;\n }\n\n public boolean getSuccess() {\n return _success;\n }\n\n public String getNuageVspCmsId() {\n return _nuageVspCmsId;\n }\n\n public SyncNuageVspCmsIdCommand.SyncType getSyncType() {\n return _syncType;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n\n if (!(o instanceof SyncNuageVspCmsIdAnswer)) {\n return false;\n }\n\n SyncNuageVspCmsIdAnswer that = (SyncNuageVspCmsIdAnswer) o;\n\n return super.equals(that)\n && _success == that._success\n && Objects.equals(_syncType, that._syncType)\n && Objects.equals(_nuageVspCmsId, that._nuageVspCmsId);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder()\n .appendSuper(super.hashCode())\n .append(_syncType)\n .append(_nuageVspCmsId)\n .append(_success)\n .toHashCode();\n }\n}","smell_code":" @Override\n public int hashCode() {\n return new HashCodeBuilder()\n .appendSuper(super.hashCode())\n .append(_syncType)\n .append(_nuageVspCmsId)\n .append(_success)\n .toHashCode();\n }","smell":"long method","id":174} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.hadoop.hive.llap.counters;\n\nimport java.util.concurrent.atomic.AtomicLongArray;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hive.conf.HiveConf;\nimport org.apache.hadoop.hive.conf.HiveConf.ConfVars;\nimport org.apache.hadoop.hive.llap.cache.LowLevelCacheCounters;\nimport org.apache.tez.common.counters.TezCounters;\n\n\/**\n * Per query counters.\n *\/\npublic class QueryFragmentCounters implements LowLevelCacheCounters {\n private final boolean doUseTimeCounters;\n\n public static enum Desc {\n MACHINE,\n TABLE,\n FILE,\n STRIPES\n }\n\n private final AtomicLongArray fixedCounters;\n private final Object[] descs;\n private final TezCounters tezCounters;\n\n public QueryFragmentCounters(Configuration conf, final TezCounters tezCounters) {\n fixedCounters = new AtomicLongArray(LlapIOCounters.values().length);\n descs = new Object[Desc.values().length];\n doUseTimeCounters = HiveConf.getBoolVar(conf, ConfVars.LLAP_ORC_ENABLE_TIME_COUNTERS);\n this.tezCounters = tezCounters;\n if (!doUseTimeCounters) {\n setCounter(LlapIOCounters.TOTAL_IO_TIME_NS, -1);\n setCounter(LlapIOCounters.DECODE_TIME_NS, -1);\n setCounter(LlapIOCounters.HDFS_TIME_NS, -1);\n setCounter(LlapIOCounters.CONSUMER_TIME_NS, -1);\n }\n }\n\n public void incrCounter(LlapIOCounters counter) {\n incrCounter(counter, 1);\n }\n\n public void incrCounter(LlapIOCounters counter, long delta) {\n fixedCounters.addAndGet(counter.ordinal(), delta);\n if (tezCounters != null) {\n tezCounters.findCounter(LlapIOCounters.values()[counter.ordinal()]).increment(delta);\n }\n }\n\n @Override\n public final long startTimeCounter() {\n return (doUseTimeCounters ? System.nanoTime() : 0);\n }\n\n public void incrWallClockCounter(LlapIOCounters counter, long startTime) {\n if (!doUseTimeCounters) return;\n long delta = System.nanoTime() - startTime;\n fixedCounters.addAndGet(counter.ordinal(), delta);\n if (tezCounters != null) {\n tezCounters.findCounter(LlapIOCounters.values()[counter.ordinal()]).increment(delta);\n }\n }\n\n public void setCounter(LlapIOCounters counter, long value) {\n fixedCounters.set(counter.ordinal(), value);\n if (tezCounters != null) {\n tezCounters.findCounter(LlapIOCounters.values()[counter.ordinal()]).setValue(value);\n }\n }\n\n public void setDesc(Desc key, Object desc) {\n descs[key.ordinal()] = desc;\n }\n\n @Override\n public void recordCacheHit(long bytesHit) {\n incrCounter(LlapIOCounters.CACHE_HIT_BYTES, bytesHit);\n }\n\n @Override\n public void recordCacheMiss(long bytesMissed) {\n incrCounter(LlapIOCounters.CACHE_MISS_BYTES, bytesMissed);\n }\n\n @Override\n public void recordAllocBytes(long bytesUsed, long bytesAllocated) {\n incrCounter(LlapIOCounters.ALLOCATED_USED_BYTES, bytesUsed);\n incrCounter(LlapIOCounters.ALLOCATED_BYTES, bytesAllocated);\n }\n\n @Override\n public void recordHdfsTime(long startTime) {\n incrWallClockCounter(LlapIOCounters.HDFS_TIME_NS, startTime);\n }\n\n @Override\n public void recordThreadTimes(long cpuNs, long userNs) {\n incrCounter(LlapIOCounters.IO_CPU_NS, cpuNs);\n incrCounter(LlapIOCounters.IO_USER_NS, userNs);\n }\n\n @Override\n public String toString() {\n \/\/ We rely on NDC information in the logs to map counters to attempt.\n \/\/ If that is not available, appId should either be passed in, or extracted from NDC.\n StringBuilder sb = new StringBuilder(\"Fragment counters for [\");\n for (int i = 0; i < descs.length; ++i) {\n if (i != 0) {\n sb.append(\", \");\n }\n if (descs[i] != null) {\n sb.append(descs[i]);\n }\n }\n sb.append(\"]: [ \");\n for (int i = 0; i < fixedCounters.length(); ++i) {\n if (i != 0) {\n sb.append(\", \");\n }\n sb.append(LlapIOCounters.values()[i].name()).append(\"=\").append(fixedCounters.get(i));\n }\n sb.append(\" ]\");\n return sb.toString();\n }\n\n public TezCounters getTezCounters() {\n return tezCounters;\n }\n}","smell_code":" @Override\n public void recordAllocBytes(long bytesUsed, long bytesAllocated) {\n incrCounter(LlapIOCounters.ALLOCATED_USED_BYTES, bytesUsed);\n incrCounter(LlapIOCounters.ALLOCATED_BYTES, bytesAllocated);\n }","smell":"long method","id":175} {"lang_cluster":"Java","source_code":"package org.springframework.issues.config;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.RequestMapping;\n\n@Controller\npublic class HomeController {\n\n\t@RequestMapping(\"\/\")\n\tpublic String index() {\n\t\treturn \"forward:\/home\";\n\t}\n\n\t@RequestMapping(\"\/home\")\n\tpublic String home(Model model) {\n\t\tmodel.addAttribute(\"name\", \"spring\");\n\t\treturn \"home\";\n\t}\n\n}","smell_code":"\t@RequestMapping(\"\/home\")\n\tpublic String home(Model model) {\n\t\tmodel.addAttribute(\"name\", \"spring\");\n\t\treturn \"home\";\n\t}","smell":"feature envy","id":176} {"lang_cluster":"Java","source_code":"\/*\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\npackage org.apache.qpid.server.store;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\nimport org.apache.qpid.server.model.ConfiguredObject;\nimport org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler;\n\npublic abstract class AbstractMemoryStore implements DurableConfigurationStore, MessageStoreProvider\n{\n private final MessageStore _messageStore = new MemoryMessageStore();\n private final Class _rootClass;\n\n enum State { CLOSED, CONFIGURED, OPEN };\n\n private State _state = State.CLOSED;\n private final Object _lock = new Object();\n\n private final ConcurrentMap _configuredObjectRecords = new ConcurrentHashMap();\n\n protected AbstractMemoryStore(final Class rootClass)\n {\n _rootClass = rootClass;\n }\n\n @Override\n public void create(ConfiguredObjectRecord record)\n {\n assertState(State.OPEN);\n if (_configuredObjectRecords.putIfAbsent(record.getId(), record) != null)\n {\n throw new StoreException(\"Record with id \" + record.getId() + \" is already present\");\n }\n }\n\n @Override\n public void update(boolean createIfNecessary, ConfiguredObjectRecord... records)\n {\n assertState(State.OPEN);\n for (ConfiguredObjectRecord record : records)\n {\n if(createIfNecessary)\n {\n _configuredObjectRecords.put(record.getId(), record);\n }\n else\n {\n ConfiguredObjectRecord previousValue = _configuredObjectRecords.replace(record.getId(), record);\n if (previousValue == null)\n {\n throw new StoreException(\"Record with id \" + record.getId() + \" does not exist\");\n }\n }\n }\n }\n\n @Override\n public UUID[] remove(final ConfiguredObjectRecord... objects)\n {\n assertState(State.OPEN);\n List removed = new ArrayList();\n for (ConfiguredObjectRecord record : objects)\n {\n if (_configuredObjectRecords.remove(record.getId()) != null)\n {\n removed.add(record.getId());\n }\n }\n return removed.toArray(new UUID[removed.size()]);\n }\n\n @Override\n public void init(ConfiguredObject parent)\n {\n changeState(State.CLOSED, State.CONFIGURED);\n }\n\n @Override\n public void upgradeStoreStructure() throws StoreException\n {\n\n }\n\n @Override\n public void closeConfigurationStore()\n {\n synchronized (_lock)\n {\n _state = State.CLOSED;\n }\n _configuredObjectRecords.clear();\n }\n\n\n @Override\n public boolean openConfigurationStore(ConfiguredObjectRecordHandler handler,\n final ConfiguredObjectRecord... initialRecords) throws StoreException\n {\n changeState(State.CONFIGURED, State.OPEN);\n boolean isNew = _configuredObjectRecords.isEmpty();\n if(isNew)\n {\n for(ConfiguredObjectRecord record : initialRecords)\n {\n _configuredObjectRecords.put(record.getId(), record);\n }\n }\n for (ConfiguredObjectRecord record : _configuredObjectRecords.values())\n {\n handler.handle(record);\n }\n return isNew;\n }\n\n @Override\n public void reload(ConfiguredObjectRecordHandler handler) throws StoreException\n {\n assertState(State.OPEN);\n for (ConfiguredObjectRecord record : _configuredObjectRecords.values())\n {\n handler.handle(record);\n }\n }\n\n\n @Override\n public MessageStore getMessageStore()\n {\n return _messageStore;\n }\n\n @Override\n public void onDelete(ConfiguredObject parent)\n {\n }\n\n private void assertState(State state)\n {\n synchronized (_lock)\n {\n if(_state != state)\n {\n throw new IllegalStateException(\"The store must be in state \" + state + \" to perform this operation, but it is in state \" + _state + \" instead\");\n }\n }\n }\n\n private void changeState(State oldState, State newState)\n {\n synchronized (_lock)\n {\n assertState(oldState);\n _state = newState;\n }\n }\n\n\n public List getConfiguredObjectRecords()\n {\n return new ArrayList<>(_configuredObjectRecords.values());\n }\n\n}","smell_code":" @Override\n public UUID[] remove(final ConfiguredObjectRecord... objects)\n {\n assertState(State.OPEN);\n List removed = new ArrayList();\n for (ConfiguredObjectRecord record : objects)\n {\n if (_configuredObjectRecords.remove(record.getId()) != null)\n {\n removed.add(record.getId());\n }\n }\n return removed.toArray(new UUID[removed.size()]);\n }","smell":"feature envy","id":177} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.ignite.internal.processors.platform.client.cache;\n\nimport org.apache.ignite.internal.binary.BinaryRawWriterEx;\nimport org.apache.ignite.internal.processors.platform.client.ClientResponse;\n\n\/**\n * Scan query response.\n *\/\nclass ClientCacheQueryResponse extends ClientResponse {\n \/** Cursor. *\/\n private final ClientCacheQueryCursor cursor;\n\n \/**\n * Ctor.\n *\n * @param requestId Request id.\n * @param cursor Cursor.\n *\/\n ClientCacheQueryResponse(long requestId, ClientCacheQueryCursor cursor) {\n super(requestId);\n\n assert cursor != null;\n\n this.cursor = cursor;\n }\n\n \/** {@inheritDoc} *\/\n @Override public void encode(BinaryRawWriterEx writer) {\n super.encode(writer);\n\n writer.writeLong(cursor.id());\n\n cursor.writePage(writer);\n }\n}","smell_code":" ClientCacheQueryResponse(long requestId, ClientCacheQueryCursor cursor) {\n super(requestId);\n\n assert cursor != null;\n\n this.cursor = cursor;\n }","smell":"feature envy","id":178} {"lang_cluster":"Java","source_code":"\/*\n * MIT License\n *\n * Copyright (c) 2016 EPAM Systems\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\npackage com.epam.catgenome.entity.track;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\nimport com.epam.catgenome.component.MessageHelper;\n\n\/**\n * Source: Track.java\n * Created: 10\/8\/15, 5:35 PM\n * Project: CATGenome Browser\n * Make: IntelliJ IDEA 14.1.4, JDK 1.8\n *

\n * {@code Track} represents a general business entity used to manage data which is required\n * to present on UI a diverse collection of datasets, including reference sequence, variants,\n * genes etc.\n *

\n * The certain type of item in a dataset is defined through corresponded generic parameter\n * which should extend base {@code Block} entity.\n *\/\npublic class Track extends AbstractTrack {\n private static final String HASH_DELIMITER = \"_\";\n\n \/**\n * {@code List} specifies list of blocks that are defined by window<\/tt> coordinates\n * and should be displayed on visible area.\n *\/\n private List blocks;\n\n public Track() {\n blocks = new ArrayList<>();\n }\n\n public Track(final Track track) {\n this.setId(track.getId());\n this.chromosome = track.getChromosome();\n this.endIndex = track.getEndIndex();\n this.scaleFactor = track.getScaleFactor();\n this.startIndex = track.getStartIndex();\n this.type = track.getType();\n this.mode = track.getMode();\n }\n\n public Track(final TrackType type) {\n this();\n this.type = type;\n }\n\n public final List getBlocks() {\n return blocks;\n }\n\n public final void setBlocks(final List blocks) {\n this.blocks = blocks;\n }\n\n public String myCacheKey() {\n if (getChromosome() == null || getChromosome().getId() == null ||\n getStartIndex() == null || getEndIndex() == null || getId() == null) {\n throw new IllegalArgumentException(MessageHelper.getMessage(\"error.hash\"));\n }\n\n StringBuilder sb = new StringBuilder();\n sb = sb.append(getId())\n .append(HASH_DELIMITER)\n .append(getChromosome().getId())\n .append(HASH_DELIMITER)\n .append(getStartIndex())\n .append(HASH_DELIMITER)\n .append(getEndIndex());\n return sb.toString();\n }\n\n public String proteinCacheKey(final Long referenceId) {\n String myCacheKey = myCacheKey();\n if (StringUtils.isEmpty(myCacheKey) || referenceId == null) {\n return null;\n }\n return myCacheKey + referenceId.toString();\n }\n}","smell_code":" public String myCacheKey() {\n if (getChromosome() == null || getChromosome().getId() == null ||\n getStartIndex() == null || getEndIndex() == null || getId() == null) {\n throw new IllegalArgumentException(MessageHelper.getMessage(\"error.hash\"));\n }\n\n StringBuilder sb = new StringBuilder();\n sb = sb.append(getId())\n .append(HASH_DELIMITER)\n .append(getChromosome().getId())\n .append(HASH_DELIMITER)\n .append(getStartIndex())\n .append(HASH_DELIMITER)\n .append(getEndIndex());\n return sb.toString();\n }","smell":"feature envy","id":179} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2004 Actuate Corporation.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * Actuate Corporation - initial API and implementation\n *******************************************************************************\/\n\npackage org.eclipse.birt.report.designer.internal.ui.views.attributes.page;\n\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ComboPropertyDescriptorProvider;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.ExpressionPropertyDescriptorProvider;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.IDescriptorProvider;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.TextPropertyDescriptorProvider;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ComboSection;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.section.ExpressionSection;\nimport org.eclipse.birt.report.designer.internal.ui.views.attributes.section.TextSection;\nimport org.eclipse.birt.report.model.api.elements.ReportDesignConstants;\nimport org.eclipse.birt.report.model.elements.interfaces.IDesignElementModel;\nimport org.eclipse.birt.report.model.elements.interfaces.IVariableElementModel;\n\n\/**\n *\n *\/\n\npublic class VariablePage extends GeneralPage\n{\n\n\tprotected void buildContent( )\n\t{\n\n\t\t\/\/ Defines provider.\n\n\t\tIDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\n\t\t\/\/ Defines section.\n\n\t\tTextSection nameSection = new TextSection( nameProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\n\t\tnameSection.setProvider( nameProvider );\n\t\tnameSection.setLayoutNum( 6 );\n\t\tnameSection.setWidth( 500 );\n\t\taddSection( PageSectionId.VARIABLE_NAME, nameSection ); \/\/$NON-NLS-1$\n\n\t\tComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\t\tvariableTypeProvider.enableReset( true );\n\n\t\tComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\t\tvariableTypeSection.setProvider( variableTypeProvider );\n\t\tvariableTypeSection.setLayoutNum( 6 );\n\t\tvariableTypeSection.setWidth( 500 );\n\t\taddSection( PageSectionId.VARIABLE_TYPE, variableTypeSection );\n\n\t\tExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\t\tExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\t\tvariableValueSection.setMulti(false);\n\t\tvariableValueSection.setProvider( variableValueProvider );\n\t\tvariableValueSection.setWidth( 500 );\n\t\tvariableValueSection.setLayoutNum( 6 );\n\t\taddSection( PageSectionId.VARIABLE_VALUE, variableValueSection );\n\n\t}\n\n\tpublic boolean canReset( )\n\t{\n\t\treturn false;\n\t}\n}","smell_code":"\tprotected void buildContent( )\n\t{\n\n\t\t\/\/ Defines provider.\n\n\t\tIDescriptorProvider nameProvider = new TextPropertyDescriptorProvider( IDesignElementModel.NAME_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\n\t\t\/\/ Defines section.\n\n\t\tTextSection nameSection = new TextSection( nameProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\n\t\tnameSection.setProvider( nameProvider );\n\t\tnameSection.setLayoutNum( 6 );\n\t\tnameSection.setWidth( 500 );\n\t\taddSection( PageSectionId.VARIABLE_NAME, nameSection ); \/\/$NON-NLS-1$\n\n\t\tComboPropertyDescriptorProvider variableTypeProvider = new ComboPropertyDescriptorProvider( IVariableElementModel.TYPE_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\t\tvariableTypeProvider.enableReset( true );\n\n\t\tComboSection variableTypeSection = new ComboSection( variableTypeProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\t\tvariableTypeSection.setProvider( variableTypeProvider );\n\t\tvariableTypeSection.setLayoutNum( 6 );\n\t\tvariableTypeSection.setWidth( 500 );\n\t\taddSection( PageSectionId.VARIABLE_TYPE, variableTypeSection );\n\n\t\tExpressionPropertyDescriptorProvider variableValueProvider = new ExpressionPropertyDescriptorProvider( IVariableElementModel.VALUE_PROP,\n\t\t\t\tReportDesignConstants.VARIABLE_ELEMENT );\n\t\tExpressionSection variableValueSection = new ExpressionSection( variableValueProvider.getDisplayName( ),\n\t\t\t\tcontainer,\n\t\t\t\ttrue );\n\t\tvariableValueSection.setMulti(false);\n\t\tvariableValueSection.setProvider( variableValueProvider );\n\t\tvariableValueSection.setWidth( 500 );\n\t\tvariableValueSection.setLayoutNum( 6 );\n\t\taddSection( PageSectionId.VARIABLE_VALUE, variableValueSection );\n\n\t}","smell":"feature envy","id":180} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage reactor.core.publisher;\n\n\nimport org.reactivestreams.Subscription;\nimport reactor.core.CoreSubscriber;\nimport reactor.util.annotation.Nullable;\n\n\/**\n * Ignores normal values and passes only the terminal signals along.\n *\n * @param the value type\n * @see Reactive-Streams-Commons<\/a>\n *\/\nfinal class MonoIgnoreElements extends MonoFromFluxOperator {\n\n\tMonoIgnoreElements(Flux source) {\n\t\tsuper(source);\n\t}\n\n\t@Override\n\tpublic void subscribe(CoreSubscriber actual) {\n\t\tsource.subscribe(new IgnoreElementsSubscriber<>(actual));\n\t}\n\n\tstatic final class IgnoreElementsSubscriber implements InnerOperator {\n\t\tfinal CoreSubscriber actual;\n\n\t\tSubscription s;\n\n\t\tIgnoreElementsSubscriber(CoreSubscriber actual) {\n\t\t\tthis.actual = actual;\n\t\t}\n\n\t\t@Override\n\t\t@Nullable\n\t\tpublic Object scanUnsafe(Attr key) {\n\t\t\tif (key == Attr.PARENT) return s;\n\n\t\t\treturn InnerOperator.super.scanUnsafe(key);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onSubscribe(Subscription s) {\n\t\t\tif (Operators.validate(this.s, s)) {\n\t\t\t\tthis.s = s;\n\n\t\t\t\tactual.onSubscribe(this);\n\n\t\t\t\ts.request(Long.MAX_VALUE);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onNext(T t) {\n\t\t\t\/\/ deliberately ignored\n\t\t\tOperators.onDiscard(t, actual.currentContext()); \/\/FIXME cache context\n\t\t}\n\n\t\t@Override\n\t\tpublic void onError(Throwable t) {\n\t\t\tactual.onError(t);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onComplete() {\n\t\t\tactual.onComplete();\n\t\t}\n\n\t\t@Override\n\t\tpublic CoreSubscriber actual() {\n\t\t\treturn actual;\n\t\t}\n\n\t\t@Override\n\t\tpublic void request(long n) {\n\t\t\t\/\/ requests Long.MAX_VALUE anyway\n\t\t}\n\n\t\t@Override\n\t\tpublic void cancel() {\n\t\t\ts.cancel();\n\t\t}\n\t}\n}","smell_code":"\t\t@Override\n\t\t@Nullable\n\t\tpublic Object scanUnsafe(Attr key) {\n\t\t\tif (key == Attr.PARENT) return s;\n\n\t\t\treturn InnerOperator.super.scanUnsafe(key);\n\t\t}","smell":"feature envy","id":181} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2016 NumberFour AG.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * NumberFour AG - Initial API and implementation\n *\/\npackage org.eclipse.n4js.jsdoc2spec;\n\nimport java.util.function.Consumer;\n\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.NullProgressMonitor;\nimport org.eclipse.core.runtime.SubMonitor;\n\n\/**\n * This class is a {@link SubMonitor} that also relays the task names to a given callback method.
\n * Note: Unfortunately a {@link SubMonitor} is final.\n *\/\npublic class SubMonitorMsg implements IProgressMonitor {\n\tprivate final IProgressMonitor monitor;\n\tprivate final SubMonitor subMonitor;\n\tprivate final Consumer callbackMsg;\n\tprivate final Consumer callbackErr;\n\tprivate final CheckCanceled checkCanceled;\n\n\t\/**\n\t * get a NullProgressMonitor here!\n\t *\/\n\tstatic public SubMonitorMsg nullProgressMonitor() {\n\t\treturn new SubMonitorMsg();\n\t}\n\n\t\/**\n\t * Wraps a {@link SubMonitor}\n\t *\/\n\tprivate SubMonitorMsg() {\n\t\tthis.subMonitor = null;\n\t\tthis.monitor = new NullProgressMonitor();\n\t\tthis.callbackMsg = this::devNull;\n\t\tthis.callbackErr = this::devNull;\n\t\tthis.checkCanceled = this::noCheck;\n\t}\n\n\tvoid devNull(@SuppressWarnings(\"unused\") String str) {\n\t\t\/\/ for Null constructor only\n\t}\n\n\tvoid noCheck(@SuppressWarnings(\"unused\") IProgressMonitor m) {\n\t\t\/\/ for Null constructor only\n\t}\n\n\t\/**\n\t * Wraps a {@link SubMonitor}\n\t *\/\n\tpublic SubMonitorMsg(SubMonitor subMonitor, Consumer callbackMsg, CheckCanceled checkCanceled) {\n\t\tthis(subMonitor, callbackMsg, callbackMsg, checkCanceled);\n\t}\n\n\t\/**\n\t * Wraps a {@link SubMonitor}\n\t *\/\n\tpublic SubMonitorMsg(SubMonitor subMonitor, Consumer callbackMsg, Consumer callbackErr,\n\t\t\tCheckCanceled checkCanceled) {\n\n\t\tthis.subMonitor = subMonitor;\n\t\tthis.monitor = subMonitor;\n\t\tthis.callbackMsg = callbackMsg;\n\t\tthis.callbackErr = callbackErr;\n\t\tthis.checkCanceled = checkCanceled;\n\t}\n\n\t\/**\n\t * c.f. {@link SubMonitor#newChild(int)}\n\t *\/\n\tpublic SubMonitorMsg newChild(int i) {\n\t\tSubMonitor child = subMonitor.newChild(i);\n\t\treturn new SubMonitorMsg(child, callbackMsg, callbackErr, checkCanceled);\n\t}\n\n\t\/**\n\t * c.f. {@link SubMonitor#convert(org.eclipse.core.runtime.IProgressMonitor, int)}\n\t *\/\n\tpublic SubMonitorMsg convert(int i) {\n\t\tSubMonitor sub = SubMonitor.convert(subMonitor, i);\n\t\treturn new SubMonitorMsg(sub, callbackMsg, callbackErr, checkCanceled);\n\t}\n\n\t@Override\n\tpublic void beginTask(String name, int totalWork) {\n\t\tmonitor.beginTask(name, totalWork);\n\t\tfireMsgString(name);\n\t}\n\n\t@Override\n\tpublic void done() {\n\t\tmonitor.done();\n\t}\n\n\t@Override\n\tpublic void internalWorked(double work) {\n\t\tmonitor.internalWorked(work);\n\t}\n\n\t@Override\n\tpublic boolean isCanceled() {\n\t\treturn monitor.isCanceled();\n\t}\n\n\t@Override\n\tpublic void setCanceled(boolean value) {\n\t\tmonitor.setCanceled(value);\n\t}\n\n\t@Override\n\tpublic void setTaskName(String name) {\n\t\tmonitor.setTaskName(name);\n\t\tfireMsgString(name);\n\t}\n\n\t@Override\n\tpublic void subTask(String name) {\n\t\tmonitor.subTask(name);\n\t\tfireMsgString(name);\n\t}\n\n\t@Override\n\tpublic void worked(int work) {\n\t\tmonitor.worked(work);\n\t}\n\n\tprivate void fireMsgString(String msg) {\n\t\tcallbackMsg.accept(msg);\n\t}\n\n\tprivate void fireErrString(String msg) {\n\t\tcallbackErr.accept(msg);\n\t}\n\n\t\/**\n\t * Relays the message to the callback function. The subtask name is not modified.\n\t *\/\n\tpublic String pushMessage(String msg) {\n\t\tfireMsgString(msg);\n\t\treturn msg;\n\t}\n\n\t\/**\n\t * Relays the message to the callback function. The subtask name is not modified.\n\t *\/\n\tpublic String pushError(String msg) {\n\t\tfireErrString(msg);\n\t\treturn msg;\n\t}\n\n\t\/**\n\t * Relays the check for cancellation events.\n\t *\/\n\tpublic void checkCanceled() throws InterruptedException {\n\t\tcheckCanceled.check(monitor);\n\t}\n}","smell_code":"\t@Override\n\tpublic void beginTask(String name, int totalWork) {\n\t\tmonitor.beginTask(name, totalWork);\n\t\tfireMsgString(name);\n\t}","smell":"feature envy","id":182} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2007, 2018, Oracle and\/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n *\/\n\/*\n *\/\n\n\npackage org.graalvm.compiler.jtt.lang;\n\nimport org.junit.Test;\n\nimport org.graalvm.compiler.jtt.JTTTest;\n\npublic final class Class_forName02 extends JTTTest {\n\n public static String test(int i) throws ClassNotFoundException {\n String clname = null;\n Class cl = null;\n if (i == 0) {\n clname = \"java.lang.Object\";\n cl = Object.class;\n } else if (i == 1) {\n clname = \"java.lang.String\";\n cl = String.class;\n } else if (i == 2) {\n clname = \"org.graalvm.compiler.jtt.lang.Class_forName02\";\n cl = Class_forName02.class;\n } else if (i == 3) {\n clname = \"xyzz.zyxy.XYXY\";\n cl = Class_forName02.class;\n }\n if (clname != null) {\n return Class.forName(clname, false, cl.getClassLoader()).toString();\n }\n return null;\n }\n\n @Test\n public void run0() throws Throwable {\n runTest(\"test\", 0);\n }\n\n @Test\n public void run1() throws Throwable {\n runTest(\"test\", 1);\n }\n\n @Test\n public void run2() throws Throwable {\n runTest(\"test\", 2);\n }\n\n @Test\n public void run3() throws Throwable {\n runTest(\"test\", 3);\n }\n\n @Test\n public void run4() throws Throwable {\n runTest(\"test\", 4);\n }\n\n}","smell_code":" @Test\n public void run2() throws Throwable {\n runTest(\"test\", 2);\n }","smell":"feature envy","id":183} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2016-2018 TypeFox and others.\n * \n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v. 2.0 which is available at\n * http:\/\/www.eclipse.org\/legal\/epl-2.0,\n * or the Eclipse Distribution License v. 1.0 which is available at\n * http:\/\/www.eclipse.org\/org\/documents\/edl-v10.php.\n * \n * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause\n *\/\npackage org.eclipse.lsp4j;\n\nimport org.eclipse.lsp4j.Position;\nimport org.eclipse.lsp4j.TextDocumentIdentifier;\nimport org.eclipse.lsp4j.jsonrpc.validation.NonNull;\nimport org.eclipse.lsp4j.util.Preconditions;\nimport org.eclipse.xtext.xbase.lib.Pure;\nimport org.eclipse.xtext.xbase.lib.util.ToStringBuilder;\n\n\/**\n * The rename request is sent from the client to the server to do a workspace wide rename of a symbol.\n *\/\n@SuppressWarnings(\"all\")\npublic class RenameParams {\n \/**\n * The document in which to find the symbol.\n *\/\n @NonNull\n private TextDocumentIdentifier textDocument;\n \n \/**\n * The position at which this request was send.\n *\/\n @NonNull\n private Position position;\n \n \/**\n * The new name of the symbol. If the given name is not valid the request must return a\n * ResponseError with an appropriate message set.\n *\/\n @NonNull\n private String newName;\n \n public RenameParams() {\n }\n \n public RenameParams(@NonNull final TextDocumentIdentifier textDocument, @NonNull final Position position, @NonNull final String newName) {\n this.textDocument = Preconditions.checkNotNull(textDocument, \"textDocument\");\n this.position = Preconditions.checkNotNull(position, \"position\");\n this.newName = Preconditions.checkNotNull(newName, \"newName\");\n }\n \n \/**\n * The document in which to find the symbol.\n *\/\n @Pure\n @NonNull\n public TextDocumentIdentifier getTextDocument() {\n return this.textDocument;\n }\n \n \/**\n * The document in which to find the symbol.\n *\/\n public void setTextDocument(@NonNull final TextDocumentIdentifier textDocument) {\n if (textDocument == null) {\n throw new IllegalArgumentException(\"Property must not be null: textDocument\");\n }\n this.textDocument = textDocument;\n }\n \n \/**\n * The position at which this request was send.\n *\/\n @Pure\n @NonNull\n public Position getPosition() {\n return this.position;\n }\n \n \/**\n * The position at which this request was send.\n *\/\n public void setPosition(@NonNull final Position position) {\n if (position == null) {\n throw new IllegalArgumentException(\"Property must not be null: position\");\n }\n this.position = position;\n }\n \n \/**\n * The new name of the symbol. If the given name is not valid the request must return a\n * ResponseError with an appropriate message set.\n *\/\n @Pure\n @NonNull\n public String getNewName() {\n return this.newName;\n }\n \n \/**\n * The new name of the symbol. If the given name is not valid the request must return a\n * ResponseError with an appropriate message set.\n *\/\n public void setNewName(@NonNull final String newName) {\n if (newName == null) {\n throw new IllegalArgumentException(\"Property must not be null: newName\");\n }\n this.newName = newName;\n }\n \n @Override\n @Pure\n public String toString() {\n ToStringBuilder b = new ToStringBuilder(this);\n b.add(\"textDocument\", this.textDocument);\n b.add(\"position\", this.position);\n b.add(\"newName\", this.newName);\n return b.toString();\n }\n \n @Override\n @Pure\n public boolean equals(final Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n RenameParams other = (RenameParams) obj;\n if (this.textDocument == null) {\n if (other.textDocument != null)\n return false;\n } else if (!this.textDocument.equals(other.textDocument))\n return false;\n if (this.position == null) {\n if (other.position != null)\n return false;\n } else if (!this.position.equals(other.position))\n return false;\n if (this.newName == null) {\n if (other.newName != null)\n return false;\n } else if (!this.newName.equals(other.newName))\n return false;\n return true;\n }\n \n @Override\n @Pure\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((this.textDocument== null) ? 0 : this.textDocument.hashCode());\n result = prime * result + ((this.position== null) ? 0 : this.position.hashCode());\n return prime * result + ((this.newName== null) ? 0 : this.newName.hashCode());\n }\n}","smell_code":" @Pure\n @NonNull\n public Position getPosition() {\n return this.position;\n }","smell":"feature envy","id":184} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2016, 2019, Oracle and\/or its affiliates. All rights reserved.\n *\/\npackage com.oracle.bmc.core.requests;\n\nimport com.oracle.bmc.core.model.*;\n\n@javax.annotation.Generated(value = \"OracleSDKGenerator\", comments = \"API Version: 20160918\")\n@lombok.Builder(builderClassName = \"Builder\", buildMethodName = \"buildWithoutInvocationCallback\")\n@lombok.Getter\npublic class GetRouteTableRequest extends com.oracle.bmc.requests.BmcRequest {\n\n \/**\n * The OCID of the route table.\n *\/\n private String rtId;\n\n public static class Builder {\n private com.oracle.bmc.util.internal.Consumer\n invocationCallback = null;\n\n \/**\n * Set the invocation callback for the request to be built.\n * @param invocationCallback the invocation callback to be set for the request\n * @return this builder instance\n *\/\n public Builder invocationCallback(\n com.oracle.bmc.util.internal.Consumer\n invocationCallback) {\n this.invocationCallback = invocationCallback;\n return this;\n }\n\n \/**\n * Copy method to populate the builder with values from the given instance.\n * @return this builder instance\n *\/\n public Builder copy(GetRouteTableRequest o) {\n rtId(o.getRtId());\n invocationCallback(o.getInvocationCallback());\n return this;\n }\n\n \/**\n * Build the instance of GetRouteTableRequest as configured by this builder\n *\n * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,\n * while the method {@link Builder#buildWithoutInvocationCallback} does not.\n *\n * This is the preferred method to build an instance.\n *\n * @return instance of GetRouteTableRequest\n *\/\n public GetRouteTableRequest build() {\n GetRouteTableRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n return request;\n }\n }\n}","smell_code":" public GetRouteTableRequest build() {\n GetRouteTableRequest request = buildWithoutInvocationCallback();\n request.setInvocationCallback(invocationCallback);\n return request;\n }","smell":"feature envy","id":185} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.flink.graph.types.valuearray;\n\nimport org.apache.flink.api.common.ExecutionConfig;\nimport org.apache.flink.api.common.functions.InvalidTypesException;\nimport org.apache.flink.api.common.typeinfo.AtomicType;\nimport org.apache.flink.api.common.typeinfo.TypeInformation;\nimport org.apache.flink.api.common.typeutils.TypeComparator;\nimport org.apache.flink.api.common.typeutils.TypeSerializer;\nimport org.apache.flink.api.java.typeutils.ValueTypeInfo;\nimport org.apache.flink.types.ByteValue;\nimport org.apache.flink.types.CharValue;\nimport org.apache.flink.types.DoubleValue;\nimport org.apache.flink.types.FloatValue;\nimport org.apache.flink.types.IntValue;\nimport org.apache.flink.types.LongValue;\nimport org.apache.flink.types.NullValue;\nimport org.apache.flink.types.ShortValue;\nimport org.apache.flink.types.StringValue;\nimport org.apache.flink.types.Value;\nimport org.apache.flink.util.Preconditions;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n\/**\n * A {@link TypeInformation} for the {@link ValueArray} type.\n *\n * @param the {@link Value} type\n *\/\npublic class ValueArrayTypeInfo extends TypeInformation> implements AtomicType> {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static final ValueArrayTypeInfo BYTE_VALUE_ARRAY_TYPE_INFO = new ValueArrayTypeInfo<>(ValueTypeInfo.BYTE_VALUE_TYPE_INFO);\n\tpublic static final ValueArrayTypeInfo INT_VALUE_ARRAY_TYPE_INFO = new ValueArrayTypeInfo<>(ValueTypeInfo.INT_VALUE_TYPE_INFO);\n\tpublic static final ValueArrayTypeInfo LONG_VALUE_ARRAY_TYPE_INFO = new ValueArrayTypeInfo<>(ValueTypeInfo.LONG_VALUE_TYPE_INFO);\n\tpublic static final ValueArrayTypeInfo NULL_VALUE_ARRAY_TYPE_INFO = new ValueArrayTypeInfo<>(ValueTypeInfo.NULL_VALUE_TYPE_INFO);\n\tpublic static final ValueArrayTypeInfo STRING_VALUE_ARRAY_TYPE_INFO = new ValueArrayTypeInfo<>(ValueTypeInfo.STRING_VALUE_TYPE_INFO);\n\n\tprivate final TypeInformation valueType;\n\n\tprivate final Class type;\n\n\tpublic ValueArrayTypeInfo(TypeInformation valueType) {\n\t\tthis.valueType = valueType;\n\t\tthis.type = valueType == null ? null : valueType.getTypeClass();\n\t}\n\n\t@Override\n\tpublic int getArity() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic int getTotalFields() {\n\t\treturn 1;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic Class> getTypeClass() {\n\t\treturn (Class>) (Class) ValueArray.class;\n\t}\n\n\t@Override\n\tpublic boolean isBasicType() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isTupleType() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isKeyType() {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\treturn Comparable.class.isAssignableFrom(type);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic TypeSerializer> createSerializer(ExecutionConfig executionConfig) {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\tif (ByteValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new ByteValueArraySerializer();\n\t\t} else if (CharValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new CharValueArraySerializer();\n\t\t} else if (DoubleValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new DoubleValueArraySerializer();\n\t\t} else if (FloatValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new FloatValueArraySerializer();\n\t\t} else if (IntValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new IntValueArraySerializer();\n\t\t} else if (LongValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new LongValueArraySerializer();\n\t\t} else if (NullValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new NullValueArraySerializer();\n\t\t} else if (ShortValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new ShortValueArraySerializer();\n\t\t} else if (StringValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeSerializer>) (TypeSerializer) new StringValueArraySerializer();\n\t\t} else {\n\t\t\tthrow new InvalidTypesException(\"No ValueArray class exists for \" + type);\n\t\t}\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\t@Override\n\tpublic TypeComparator> createComparator(boolean sortOrderAscending, ExecutionConfig executionConfig) {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\tif (ByteValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new ByteValueArrayComparator(sortOrderAscending);\n\t\t} else if (CharValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new CharValueArrayComparator(sortOrderAscending);\n\t\t} else if (DoubleValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new DoubleValueArrayComparator(sortOrderAscending);\n\t\t} else if (FloatValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new FloatValueArrayComparator(sortOrderAscending);\n\t\t} else if (IntValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new IntValueArrayComparator(sortOrderAscending);\n\t\t} else if (LongValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new LongValueArrayComparator(sortOrderAscending);\n\t\t} else if (NullValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new NullValueArrayComparator(sortOrderAscending);\n\t\t} else if (ShortValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new ShortValueArrayComparator(sortOrderAscending);\n\t\t} else if (StringValue.class.isAssignableFrom(type)) {\n\t\t\treturn (TypeComparator>) (TypeComparator) new StringValueArrayComparator(sortOrderAscending);\n\t\t} else {\n\t\t\tthrow new InvalidTypesException(\"No ValueArray class exists for \" + type);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Map> getGenericParameters() {\n\t\tMap> m = new HashMap<>(1);\n\t\tm.put(\"T\", valueType);\n\t\treturn m;\n\t}\n\n\t\/\/ --------------------------------------------------------------------------------------------\n\n\t@Override\n\tpublic int hashCode() {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\treturn type.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj instanceof ValueArrayTypeInfo) {\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tValueArrayTypeInfo valueArrayTypeInfo = (ValueArrayTypeInfo) obj;\n\n\t\t\treturn valueArrayTypeInfo.canEqual(this) &&\n\t\t\t\ttype == valueArrayTypeInfo.type;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean canEqual(Object obj) {\n\t\treturn obj instanceof ValueArrayTypeInfo;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\treturn \"ValueArrayType<\" + type.getSimpleName() + \">\";\n\t}\n}","smell_code":"\t@Override\n\tpublic int hashCode() {\n\t\tPreconditions.checkNotNull(type, \"TypeInformation type class is required\");\n\n\t\treturn type.hashCode();\n\t}","smell":"feature envy","id":186} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2002-2016 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.springframework.aop.aspectj;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Type;\n\nimport org.springframework.aop.AfterAdvice;\nimport org.springframework.aop.AfterReturningAdvice;\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.ClassUtils;\nimport org.springframework.util.TypeUtils;\n\n\/**\n * Spring AOP advice wrapping an AspectJ after-returning advice method.\n *\n * @author Rod Johnson\n * @author Juergen Hoeller\n * @author Ramnivas Laddad\n * @since 2.0\n *\/\n@SuppressWarnings(\"serial\")\npublic class AspectJAfterReturningAdvice extends AbstractAspectJAdvice\n\t\timplements AfterReturningAdvice, AfterAdvice, Serializable {\n\n\tpublic AspectJAfterReturningAdvice(\n\t\t\tMethod aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {\n\n\t\tsuper(aspectJBeforeAdviceMethod, pointcut, aif);\n\t}\n\n\n\t@Override\n\tpublic boolean isBeforeAdvice() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isAfterAdvice() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void setReturningName(String name) {\n\t\tsetReturningNameNoCheck(name);\n\t}\n\n\t@Override\n\tpublic void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) throws Throwable {\n\t\tif (shouldInvokeOnReturnValueOf(method, returnValue)) {\n\t\t\tinvokeAdviceMethod(getJoinPointMatch(), returnValue, null);\n\t\t}\n\t}\n\n\n\t\/**\n\t * Following AspectJ semantics, if a returning clause was specified, then the\n\t * advice is only invoked if the returned value is an instance of the given\n\t * returning type and generic type parameters, if any, match the assignment\n\t * rules. If the returning type is Object, the advice is *always* invoked.\n\t * @param returnValue the return value of the target method\n\t * @return whether to invoke the advice method for the given return value\n\t *\/\n\tprivate boolean shouldInvokeOnReturnValueOf(Method method, @Nullable Object returnValue) {\n\t\tClass type = getDiscoveredReturningType();\n\t\tType genericType = getDiscoveredReturningGenericType();\n\t\t\/\/ If we aren't dealing with a raw type, check if generic parameters are assignable.\n\t\treturn (matchesReturnValue(type, method, returnValue) &&\n\t\t\t\t(genericType == null || genericType == type ||\n\t\t\t\t\t\tTypeUtils.isAssignable(genericType, method.getGenericReturnType())));\n\t}\n\n\t\/**\n\t * Following AspectJ semantics, if a return value is null (or return type is void),\n\t * then the return type of target method should be used to determine whether advice\n\t * is invoked or not. Also, even if the return type is void, if the type of argument\n\t * declared in the advice method is Object, then the advice must still get invoked.\n\t * @param type the type of argument declared in advice method\n\t * @param method the advice method\n\t * @param returnValue the return value of the target method\n\t * @return whether to invoke the advice method for the given return value and type\n\t *\/\n\tprivate boolean matchesReturnValue(Class type, Method method, @Nullable Object returnValue) {\n\t\tif (returnValue != null) {\n\t\t\treturn ClassUtils.isAssignableValue(type, returnValue);\n\t\t}\n\t\telse if (Object.class == type && void.class == method.getReturnType()) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn ClassUtils.isAssignable(type, method.getReturnType());\n\t\t}\n\t}\n\n}","smell_code":"\tprivate boolean matchesReturnValue(Class type, Method method, @Nullable Object returnValue) {\n\t\tif (returnValue != null) {\n\t\t\treturn ClassUtils.isAssignableValue(type, returnValue);\n\t\t}\n\t\telse if (Object.class == type && void.class == method.getReturnType()) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn ClassUtils.isAssignable(type, method.getReturnType());\n\t\t}\n\t}","smell":"feature envy","id":187} {"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2015, 2017 Red Hat, Inc. \n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * \tContributors:\n * \t\t Red Hat Inc. - initial API and implementation and\/or initial documentation\n * \t\t IBM Corporation - initial API and implementation\n *******************************************************************************\/\npackage org.eclipse.thym.core.internal.cordova;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Map;\n\nimport org.eclipse.core.externaltools.internal.IExternalToolConstants;\nimport org.eclipse.core.runtime.CoreException;\nimport org.eclipse.core.runtime.IProgressMonitor;\nimport org.eclipse.core.runtime.IStatus;\nimport org.eclipse.core.runtime.Status;\nimport org.eclipse.debug.core.DebugPlugin;\nimport org.eclipse.debug.core.ILaunchConfiguration;\nimport org.eclipse.debug.core.ILaunchConfigurationType;\nimport org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;\nimport org.eclipse.debug.core.ILaunchManager;\nimport org.eclipse.debug.core.IStreamListener;\nimport org.eclipse.debug.core.model.IProcess;\nimport org.eclipse.debug.core.model.IStreamsProxy;\nimport org.eclipse.thym.core.HybridCore;\nimport org.eclipse.thym.core.internal.util.ExternalProcessUtility;\n\n\/**\n * Wrapper around Cordova CLI. Provides low level \n * access to Cordova CLI.\n *\n *@author Gorkem Ercan\n *\n *\/\n@SuppressWarnings(\"restriction\")\npublic class CordovaCLI {\n\t\n\tprivate Map additionalEnvProps;\n\t\n\tpublic CordovaCLI(){\n\t\tadditionalEnvProps = HybridCore.getEnvVariables();\n\t}\n\t\n\tpublic CordovaCLIResult version(final IProgressMonitor monitor) throws CoreException{\n\t\tfinal CordovaCLIStreamListener streamListener = new CordovaCLIStreamListener();\n\t\tIProcess process = startShell(streamListener, monitor, getLaunchConfiguration(\"cordova -version\"));\n\t\tString cordovaCommand = \"cordova -version\\n\";\n\t\tsendCordovaCommand(process, cordovaCommand, monitor);\n\t\tCordovaCLIResult result = new CordovaCLIResult(streamListener.getMessage());\n\t\treturn result;\t\t\n\t}\n\t\n\tpublic CordovaCLIResult nodeVersion(final IProgressMonitor monitor) throws CoreException{\n\t\tfinal CordovaCLIStreamListener streamListener = new CordovaCLIStreamListener();\n\t\tIProcess process = startShell(streamListener, monitor, getLaunchConfiguration(\"node -v\"));\n\t\tString command = \"node -v\\n\";\n\t\tsendCordovaCommand(process, command, monitor);\n\t\tCordovaCLIResult result= new CordovaCLIResult(streamListener.getMessage());\n\t\treturn result;\n\t}\n\n\tprotected void sendCordovaCommand(final IProcess process, final String cordovaCommand,\n\t\t\tfinal IProgressMonitor monitor) throws CoreException {\n\t\ttry {\n\t\t\tfinal IStreamsProxy streamProxy = process.getStreamsProxy();\n\t\t\tstreamProxy.write(cordovaCommand.toString());\n\t\t\twhile (!process.isTerminated()) {\n\t\t\t\t\/\/exit the shell after sending the command\n\t\t\t\ttry{\n\t\t\t\t\tstreamProxy.write(\"exit\\n\");\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\/\/ignore\n\t\t\t\t}\n\t\t\t\tif (monitor.isCanceled()) {\n\t\t\t\t\tprocess.terminate();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tThread.sleep(50);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, \"Fatal error invoking cordova CLI\", e));\n\t\t} catch (InterruptedException e) {\n\t\t\tHybridCore.log(IStatus.INFO, \"Exception waiting for process to terminate\", e);\n\t\t}\n\t}\n\t\n\t\/\/public visibility to support testing\n\tpublic IProcess startShell(final IStreamListener listener, final IProgressMonitor monitor, \n\t\t\tfinal ILaunchConfiguration launchConfiguration) throws CoreException{\n\t\tArrayList commandList = new ArrayList();\n\t\tif(isWindows()){\n\t\t\tcommandList.add(\"cmd\");\n\t\t}else{\n\t\t\tcommandList.add(\"\/bin\/bash\");\n\t\t\tcommandList.add(\"-l\");\n\t\t}\n\t\t\n\t\tExternalProcessUtility ep = new ExternalProcessUtility();\n\t\tIProcess process = ep.exec(commandList.toArray(new String[commandList.size()]), getWorkingDirectory(), \n\t\t\t\tmonitor, null, launchConfiguration, listener, listener);\n\t\t return process;\n\t}\n\t\n\tprotected boolean isWindows(){\n\t\tString OS = System.getProperty(\"os.name\",\"unknown\");\n\t\treturn OS.toLowerCase().indexOf(\"win\")>-1;\n\t}\n\t\n\tprotected ILaunchConfiguration getLaunchConfiguration(String label){\n\t\tILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();\n\t\tILaunchConfigurationType type = manager.getLaunchConfigurationType(IExternalToolConstants.ID_PROGRAM_LAUNCH_CONFIGURATION_TYPE);\n\t\ttry {\n\t\t\tILaunchConfiguration cfg = type.newInstance(null, \"cordova\");\n\t\t\tILaunchConfigurationWorkingCopy wc = cfg.getWorkingCopy();\n\t\t\twc.setAttribute(IProcess.ATTR_PROCESS_LABEL, label);\n\t\t\tif(additionalEnvProps != null && !additionalEnvProps.isEmpty()){\n\t\t\t\twc.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES,additionalEnvProps);\n\t\t\t}\n\t\t\tcfg = wc.doSave();\n\t\t\treturn cfg;\n\t\t} catch (CoreException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tprotected File getWorkingDirectory(){\n\t\treturn null;\n\t}\n}","smell_code":"\tpublic CordovaCLIResult version(final IProgressMonitor monitor) throws CoreException{\n\t\tfinal CordovaCLIStreamListener streamListener = new CordovaCLIStreamListener();\n\t\tIProcess process = startShell(streamListener, monitor, getLaunchConfiguration(\"cordova -version\"));\n\t\tString cordovaCommand = \"cordova -version\\n\";\n\t\tsendCordovaCommand(process, cordovaCommand, monitor);\n\t\tCordovaCLIResult result = new CordovaCLIResult(streamListener.getMessage());\n\t\treturn result;\t\t\n\t}","smell":"feature envy","id":188} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.phoenix.optimize;\n\nimport java.util.Objects;\n\n\/**\n * Optimizer cost in terms of CPU, memory, and I\/O usage, the unit of which is now the\n * number of bytes processed.\n *\n *\/\npublic class Cost implements Comparable {\n \/** The unknown cost. *\/\n public static Cost UNKNOWN = new Cost(Double.NaN, Double.NaN, Double.NaN) {\n @Override\n public String toString() {\n return \"{unknown}\";\n }\n };\n\n \/** The zero cost. *\/\n public static Cost ZERO = new Cost(0, 0, 0) {\n @Override\n public String toString() {\n return \"{zero}\";\n } \n };\n\n private final double cpu;\n private final double memory;\n private final double io;\n\n public Cost(double cpu, double memory, double io) {\n this.cpu = cpu;\n this.memory = memory;\n this.io = io;\n }\n\n public double getCpu() {\n return cpu;\n }\n\n public double getMemory() {\n return memory;\n }\n\n public double getIo() {\n return io;\n }\n\n public boolean isUnknown() {\n return this == UNKNOWN;\n }\n\n public Cost plus(Cost other) {\n if (isUnknown() || other.isUnknown()) {\n return UNKNOWN;\n }\n\n return new Cost(\n this.cpu + other.cpu,\n this.memory + other.memory,\n this.io + other.io);\n }\n\n public Cost multiplyBy(double factor) {\n if (isUnknown()) {\n return UNKNOWN;\n }\n\n return new Cost(\n this.cpu * factor,\n this.memory * factor,\n this.io * factor);\n }\n\n \/\/ TODO right now for simplicity, we choose to ignore CPU and memory costs. We may\n \/\/ add those into account as our cost model mature.\n @Override\n public int compareTo(Cost other) {\n if (isUnknown() && other.isUnknown()) {\n return 0;\n } else if (isUnknown() && !other.isUnknown()) {\n return 1;\n } else if (!isUnknown() && other.isUnknown()) {\n return -1;\n }\n\n double d = this.io - other.io;\n return d == 0 ? 0 : (d > 0 ? 1 : -1);\n }\n\n @Override\n public boolean equals(Object obj) {\n return this == obj\n || (obj instanceof Cost && this.compareTo((Cost) obj) == 0);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(cpu, memory, io);\n }\n\n @Override\n public String toString() {\n return \"{cpu: \" + cpu + \", memory: \" + memory + \", io: \" + io + \"}\";\n }\n}","smell_code":" @Override\n public int compareTo(Cost other) {\n if (isUnknown() && other.isUnknown()) {\n return 0;\n } else if (isUnknown() && !other.isUnknown()) {\n return 1;\n } else if (!isUnknown() && other.isUnknown()) {\n return -1;\n }\n\n double d = this.io - other.io;\n return d == 0 ? 0 : (d > 0 ? 1 : -1);\n }","smell":"feature envy","id":189} {"lang_cluster":"Java","source_code":"\/*\n\n Derby - Class org.apache.derbyTesting.functionTests.tests.compatibility.helpers.DummyBlob\n\n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to you under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n *\/\npackage org.apache.derbyTesting.functionTests.tests.compatibility.helpers;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.sql.Blob;\nimport java.sql.SQLException;\n\n\/**\n * A crude Blob implementation for datatype testing.\n *\/\npublic class DummyBlob\n implements Blob {\n private\tbyte[]\t_bytes;\n\n public\tDummyBlob( byte[] bytes )\n {\n _bytes = bytes;\n }\n\n public\tInputStream\tgetBinaryStream()\n {\n return new ByteArrayInputStream( _bytes );\n }\n\n public\tbyte[]\tgetBytes( long position, int length ) { return _bytes; }\n\n public\tlong\tlength() { return (long) _bytes.length; }\n\n public\tlong\tposition( Blob pattern, long start ) { return 0L; }\n public\tlong\tposition( byte[] pattern, long start ) { return 0L; }\n\n public\tboolean\tequals( Object other )\n {\n if ( other == null ) { return false; }\n if ( !( other instanceof Blob ) ) { return false; }\n\n Blob\tthat = (Blob) other;\n\n try {\n if ( this.length() != that.length() ) { return false; }\n\n InputStream\tthisStream = this.getBinaryStream();\n InputStream\tthatStream = that.getBinaryStream();\n\n while( true )\n {\n int\t\tnextByte = thisStream.read();\n\n if ( nextByte < 0 ) { break; }\n if ( nextByte != thatStream.read() ) { return false; }\n }\n }\n catch (Exception e)\n {\n System.err.println( e.getMessage() );\n e.printStackTrace(System.err);\n return false;\n }\n\n return true;\n }\n\n public int setBytes(long arg0, byte[] arg1) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public int setBytes(long arg0, byte[] arg1, int arg2, int arg3)\n throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public OutputStream setBinaryStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void truncate(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }\n\n public void free() throws SQLException {\n _bytes = null;\n }\n\n public InputStream getBinaryStream(long pos, long length)\n throws SQLException {\n return new ByteArrayInputStream(_bytes, (int)pos -1, (int)length);\n }\n}","smell_code":" public OutputStream setBinaryStream(long arg0) throws SQLException {\n throw new SQLException(\"not implemented for this test\");\n }","smell":"feature envy","id":190} {"lang_cluster":"Java","source_code":"\/**\n * Copyright (c) 2017, 2018 Kichwa Coders Ltd. and others.\n * \n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v. 2.0 which is available at\n * http:\/\/www.eclipse.org\/legal\/epl-2.0,\n * or the Eclipse Distribution License v. 1.0 which is available at\n * http:\/\/www.eclipse.org\/org\/documents\/edl-v10.php.\n * \n * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause\n *\/\npackage org.eclipse.lsp4j.debug;\n\nimport java.util.Arrays;\nimport org.eclipse.lsp4j.debug.Breakpoint;\nimport org.eclipse.lsp4j.jsonrpc.validation.NonNull;\nimport org.eclipse.xtext.xbase.lib.Pure;\nimport org.eclipse.xtext.xbase.lib.util.ToStringBuilder;\n\n\/**\n * Response to 'setFunctionBreakpoints' request.\n *

\n * Returned is information about each breakpoint created by this request.\n *\/\n@SuppressWarnings(\"all\")\npublic class SetFunctionBreakpointsResponse {\n \/**\n * Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array.\n *\/\n @NonNull\n private Breakpoint[] breakpoints;\n \n \/**\n * Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array.\n *\/\n @Pure\n @NonNull\n public Breakpoint[] getBreakpoints() {\n return this.breakpoints;\n }\n \n \/**\n * Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array.\n *\/\n public void setBreakpoints(@NonNull final Breakpoint[] breakpoints) {\n if (breakpoints == null) {\n throw new IllegalArgumentException(\"Property must not be null: breakpoints\");\n }\n this.breakpoints = breakpoints;\n }\n \n @Override\n @Pure\n public String toString() {\n ToStringBuilder b = new ToStringBuilder(this);\n b.add(\"breakpoints\", this.breakpoints);\n return b.toString();\n }\n \n @Override\n @Pure\n public boolean equals(final Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n SetFunctionBreakpointsResponse other = (SetFunctionBreakpointsResponse) obj;\n if (this.breakpoints == null) {\n if (other.breakpoints != null)\n return false;\n } else if (!Arrays.deepEquals(this.breakpoints, other.breakpoints))\n return false;\n return true;\n }\n \n @Override\n @Pure\n public int hashCode() {\n return 31 * 1 + ((this.breakpoints== null) ? 0 : Arrays.deepHashCode(this.breakpoints));\n }\n}","smell_code":" public void setBreakpoints(@NonNull final Breakpoint[] breakpoints) {\n if (breakpoints == null) {\n throw new IllegalArgumentException(\"Property must not be null: breakpoints\");\n }\n this.breakpoints = breakpoints;\n }","smell":"feature envy","id":191} {"lang_cluster":"Java","source_code":"\/\/ Copyright (C) 2005 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage com.google.caja.util;\n\nimport java.io.Serializable;\nimport java.util.AbstractMap;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n\n\/**\n * A set of attributes attached to a parse tree node that have been inferred by\n * the parser.\n *\n * @author mikesamuel@gmail.com\n *\/\npublic final class SyntheticAttributes\n extends AbstractMap, Object>\n implements Serializable {\n private static final long serialVersionUID = 1124793823020078634L;\n \/**\n * True iff this has its own copy without clobbering another maps attributes.\n * The copy constructor below does copy-on-write of the underlying map.\n *\/\n private boolean hasOwnCopy;\n private Map, Object> attributes;\n private boolean immutable = false;\n\n public SyntheticAttributes() {\n clear();\n }\n\n public SyntheticAttributes(SyntheticAttributes sa) {\n attributes = sa.attributes;\n immutable = sa.immutable;\n sa.hasOwnCopy = false;\n }\n\n public void makeImmutable() {\n if (immutable) { return; }\n requireOwnCopy();\n immutable = true;\n }\n\n public boolean isImmutable() {\n return immutable;\n }\n\n @Override\n public void clear() {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n attributes = Collections.emptyMap();\n hasOwnCopy = false;\n }\n\n @SuppressWarnings(\"unchecked\")\n public T get(SyntheticAttributeKey k) {\n return (T) attributes.get(k);\n }\n\n @Override\n public Object get(Object k) {\n return attributes.get(k);\n }\n\n \/**\n * associate the value v with the key k.\n * @param k non null.\n * @param v non null.\n * @return the old value associated with k or null if none.\n *\/\n @SuppressWarnings(\"unchecked\")\n public T set(SyntheticAttributeKey k, T v) {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n if (!(null == v || k.getType().isInstance(v))) {\n throw new ClassCastException(v + \" to \" + k.getType());\n }\n requireOwnCopy();\n return (T) attributes.put(k, v);\n }\n\n @Deprecated\n @Override\n public Object put(SyntheticAttributeKey k, Object v) {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n if (!(null == v || k.getType().isInstance(v))) {\n throw new ClassCastException(v + \" to \" + k.getType());\n }\n requireOwnCopy();\n return attributes.put(k, v);\n }\n\n \/**\n * @return true iff the value associated with the given key is\n * {@link Boolean#TRUE}.\n *\/\n public boolean is(SyntheticAttributeKey k) {\n return Boolean.TRUE.equals(attributes.get(k));\n }\n\n \/**\n * @see #remove(Object)\n *\/\n @SuppressWarnings(\"unchecked\")\n public T remove(SyntheticAttributeKey k) {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n return (T) remove((Object) k);\n }\n\n @Override\n public Object remove(Object k) {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n if (!hasOwnCopy) {\n if (attributes.isEmpty()) { return null; }\n requireOwnCopy();\n }\n return attributes.remove(k);\n }\n\n private void requireOwnCopy() {\n if (!hasOwnCopy) {\n attributes = new HashMap, Object>(attributes);\n hasOwnCopy = true;\n }\n }\n\n @Override\n public int size() { return attributes.size(); }\n\n @Override\n public boolean containsKey(Object k) { return attributes.containsKey(k); }\n\n @Override\n public boolean containsValue(Object v) { return attributes.containsValue(v); }\n\n \/**\n * @return an immutable entry set to force proper type checking of keys\n * and values. Mutability could be implemented, but it's not currently\n * used.\n *\/\n @Override\n public Set, Object>> entrySet() {\n return Collections.unmodifiableMap(attributes).entrySet();\n }\n}","smell_code":" @SuppressWarnings(\"unchecked\")\n public T remove(SyntheticAttributeKey k) {\n if (immutable) {\n throw new UnsupportedOperationException();\n }\n return (T) remove((Object) k);\n }","smell":"feature envy","id":192} {"lang_cluster":"Java","source_code":"\/*\n * Copyright (c) 2012-2018 Red Hat, Inc.\n * This program and the accompanying materials are made\n * available under the terms of the Eclipse Public License 2.0\n * which is available at https:\/\/www.eclipse.org\/legal\/epl-2.0\/\n *\n * SPDX-License-Identifier: EPL-2.0\n *\n * Contributors:\n * Red Hat, Inc. - initial API and implementation\n *\/\npackage org.eclipse.che.ide.ext.java.client.progressor;\n\nimport static java.lang.System.currentTimeMillis;\n\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.eclipse.che.ide.ext.java.client.inject.factories.ProgressWidgetFactory;\nimport org.eclipse.che.ide.util.Pair;\nimport org.eclipse.che.jdt.ls.extension.api.dto.ProgressReport;\n\n\/**\n * Presenter of the window which describes information about all running tasks.\n *\n * @author Valeriy Svydenko\n *\/\n@Singleton\npublic class ProgressMonitorPresenter {\n private static final long UPDATE_PERIOD = 1_000L; \/\/ don't update more often then 1 sec\n\n private final ProgressMonitorView view;\n private final ProgressWidgetFactory progressFactory;\n\n private Map> progresses = new HashMap<>();\n\n @Inject\n public ProgressMonitorPresenter(ProgressMonitorView view, ProgressWidgetFactory progressFactory) {\n this.view = view;\n this.progressFactory = progressFactory;\n }\n\n \/** Shows the widget. *\/\n public void show() {\n view.showDialog();\n }\n\n \/**\n * Updates progress for one task.\n *\n * @param progress updated progress\n *\/\n public void updateProgress(ProgressReport progress) {\n String taskId = progress.getId();\n if (!progresses.containsKey(taskId)) {\n return;\n }\n Pair updatedView = progresses.get(taskId);\n ProgressView progressView = updatedView.getFirst();\n if (progress.isComplete()) {\n view.remove(progressView);\n progresses.remove(taskId);\n return;\n }\n Long updated = updatedView.getSecond();\n if (currentTimeMillis() - updated < UPDATE_PERIOD) {\n return;\n }\n progressView.updateProgressBar(progress);\n }\n\n \/** Hides the widget. *\/\n public void hide() {\n view.close();\n }\n\n \/**\n * Adds new progress.\n *\n * @param progress information about progress\n *\/\n public void addProgress(ProgressReport progress) {\n String taskId = progress.getId();\n if (progresses.containsKey(taskId)) {\n updateProgress(progress);\n return;\n }\n ProgressView progressView = progressFactory.create();\n progressView.updateProgressBar(progress);\n progresses.put(taskId, Pair.of(progressView, currentTimeMillis()));\n view.add(progressView);\n }\n\n \/**\n * Removes progress.\n *\n * @param progress information about progress\n *\/\n public void removeProgress(ProgressReport progress) {\n String taskId = progress.getId();\n if (!progresses.containsKey(taskId)) {\n return;\n }\n view.remove(progresses.remove(taskId).getFirst());\n }\n}","smell_code":" public void hide() {\n view.close();\n }","smell":"feature envy","id":193} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/* $Id$ *\/\n\npackage org.apache.fop.afp.svg;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.batik.gvt.font.GVTFontFace;\n\nimport org.apache.fop.afp.AFPEventProducer;\nimport org.apache.fop.afp.fonts.DoubleByteFont;\nimport org.apache.fop.events.EventBroadcaster;\nimport org.apache.fop.fonts.Font;\nimport org.apache.fop.fonts.FontInfo;\nimport org.apache.fop.fonts.FontTriplet;\nimport org.apache.fop.fonts.Typeface;\nimport org.apache.fop.svg.font.FOPFontFamilyResolverImpl;\nimport org.apache.fop.svg.font.FOPGVTFontFamily;\nimport org.apache.fop.svg.font.FilteringFontFamilyResolver;\n\npublic class AFPFontFamilyResolver extends FilteringFontFamilyResolver {\n\n private final FontInfo fontInfo;\n\n private final AFPEventProducer eventProducer;\n\n\n public AFPFontFamilyResolver(FontInfo fontInfo, EventBroadcaster eventBroadCaster) {\n super(new FOPFontFamilyResolverImpl(fontInfo));\n this.fontInfo = fontInfo;\n this.eventProducer = AFPEventProducer.Provider.get(eventBroadCaster);\n }\n\n @Override\n public FOPGVTFontFamily resolve(String familyName) {\n FOPGVTFontFamily fopGVTFontFamily = super.resolve(familyName);\n \/\/ TODO why don't DB fonts work with GOCA?!?\n if (fopGVTFontFamily != null && fopGVTFontFamily.deriveFont(1, new HashMap())\n .getFont().getFontMetrics() instanceof DoubleByteFont) {\n notifyDBFontRejection(fopGVTFontFamily.getFamilyName());\n fopGVTFontFamily = null;\n }\n return fopGVTFontFamily;\n }\n\n @Override\n public FOPGVTFontFamily getFamilyThatCanDisplay(char c) {\n Map fonts = fontInfo.getFonts();\n for (Typeface font : fonts.values()) {\n \/\/ TODO why don't DB fonts work with GOCA?!?\n if (font.hasChar(c) && !(font instanceof DoubleByteFont)) {\n String fontFamily = font.getFamilyNames().iterator().next();\n if (font instanceof DoubleByteFont) {\n notifyDBFontRejection(font.getFontName());\n } else {\n return new FOPGVTFontFamily(fontInfo, fontFamily,\n new FontTriplet(fontFamily, Font.STYLE_NORMAL, Font.WEIGHT_NORMAL),\n new GVTFontFace(fontFamily));\n }\n\n }\n }\n return null;\n }\n\n private void notifyDBFontRejection(String fontFamily) {\n eventProducer.invalidDBFontInSVG(this, fontFamily);\n }\n\n}","smell_code":" @Override\n public FOPGVTFontFamily resolve(String familyName) {\n FOPGVTFontFamily fopGVTFontFamily = super.resolve(familyName);\n \/\/ TODO why don't DB fonts work with GOCA?!?\n if (fopGVTFontFamily != null && fopGVTFontFamily.deriveFont(1, new HashMap())\n .getFont().getFontMetrics() instanceof DoubleByteFont) {\n notifyDBFontRejection(fopGVTFontFamily.getFamilyName());\n fopGVTFontFamily = null;\n }\n return fopGVTFontFamily;\n }","smell":"feature envy","id":194} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage org.apache.eagle.security.auditlog;\n\nimport com.typesafe.config.Config;\nimport org.apache.eagle.security.service.ISecurityDataEnrichServiceClient;\nimport org.apache.eagle.security.service.IPZoneEntity;\nimport org.apache.eagle.security.enrich.AbstractDataEnrichLCM;\n\nimport java.util.Collection;\n\n\/**\n * Since 8\/16\/16.\n *\/\npublic class IPZoneDataEnrichLCM extends AbstractDataEnrichLCM {\n public IPZoneDataEnrichLCM(Config config){\n super(config);\n }\n @Override\n protected Collection loadFromService(ISecurityDataEnrichServiceClient client) {\n return client.listIPZones();\n }\n\n @Override\n public String getCacheKey(IPZoneEntity entity) {\n return entity.getIphost();\n }\n}","smell_code":" @Override\n protected Collection loadFromService(ISecurityDataEnrichServiceClient client) {\n return client.listIPZones();\n }","smell":"feature envy","id":195} {"lang_cluster":"Java","source_code":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage org.apache.knox.gateway.filter.rewrite.impl;\n\nimport org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;\nimport org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;\nimport org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;\nimport org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;\nimport org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;\nimport org.apache.knox.gateway.i18n.messages.MessagesFactory;\nimport org.apache.knox.gateway.util.urltemplate.Evaluator;\nimport org.apache.knox.gateway.util.urltemplate.Params;\nimport org.apache.knox.gateway.util.urltemplate.Resolver;\nimport org.apache.knox.gateway.util.urltemplate.Template;\n\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlRewriteContextImpl implements UrlRewriteContext {\n\n private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );\n\n private UrlRewriteEnvironment environment;\n private Resolver resolver;\n private Evaluator evaluator;\n private Map functions;\n private ContextParameters params;\n private UrlRewriter.Direction direction;\n private Template originalUrl;\n private Template currentUrl;\n\n public UrlRewriteContextImpl(\n UrlRewriteEnvironment environment,\n Resolver resolver,\n Map functions,\n UrlRewriter.Direction direction,\n Template url ) {\n this.environment = environment;\n this.resolver = resolver;\n this.functions = functions;\n this.params = new ContextParameters();\n this.evaluator = new ContextEvaluator();\n this.direction = direction;\n this.originalUrl = url;\n this.currentUrl = url;\n }\n\n @Override\n public UrlRewriter.Direction getDirection() {\n return direction;\n }\n\n @Override\n public Template getOriginalUrl() {\n return originalUrl;\n }\n\n @Override\n public Template getCurrentUrl() {\n return currentUrl;\n }\n\n @Override\n public void setCurrentUrl( Template url ) {\n currentUrl = url;\n }\n\n @Override\n public void addParameters( Params parameters ) {\n params.add( parameters );\n }\n\n @Override\n public Params getParameters() {\n return params;\n }\n\n @Override\n public Evaluator getEvaluator() {\n return evaluator;\n }\n\n private class ContextParameters implements Params {\n Map> map = new LinkedHashMap<>();\n\n @Override\n public Set getNames() {\n return map.keySet();\n }\n\n @Override\n public List resolve( String name ) {\n List values = map.get( name ); \/\/ Try to find the name in the context map.\n if( values == null ) {\n try {\n values = resolver.resolve( name );\n if( values == null ) {\n values = environment.resolve( name ); \/\/ Try to find the name in the environment.\n }\n } catch( Exception e ) {\n LOG.failedToFindValuesByParameter( name, e );\n \/\/ Ignore it and return null.\n }\n }\n return values;\n }\n\n public void add( Params params ) {\n for( String name : params.getNames() ) {\n map.put( name, params.resolve( name ) );\n }\n }\n\n }\n\n private class ContextEvaluator implements Evaluator {\n\n @Override\n public List evaluate( String function, List parameters ) {\n List results = null;\n UrlRewriteFunctionProcessor processor = functions.get( function );\n if( processor != null ) {\n try {\n results = processor.resolve( UrlRewriteContextImpl.this, parameters );\n } catch( Exception e ) {\n LOG.failedToInvokeRewriteFunction( function, e );\n results = null;\n }\n }\n return results;\n }\n }\n\n}","smell_code":" public UrlRewriteContextImpl(\n UrlRewriteEnvironment environment,\n Resolver resolver,\n Map functions,\n UrlRewriter.Direction direction,\n Template url ) {\n this.environment = environment;\n this.resolver = resolver;\n this.functions = functions;\n this.params = new ContextParameters();\n this.evaluator = new ContextEvaluator();\n this.direction = direction;\n this.originalUrl = url;\n this.currentUrl = url;\n }","smell":"feature envy","id":196} {"lang_cluster":"Java","source_code":"\/**\n * Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n *\n * http:\/\/aws.amazon.com\/apache2.0\n *\n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\npackage com.amazon.pay.response.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.xml.bind.annotation.XmlAccessType;\nimport javax.xml.bind.annotation.XmlAccessorType;\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlType;\n\n\/**\n * This can parse two different variations of <IdList> nodes.\n * In most cases, the individual members are instead <member>..<\/member> tags,\n * but some IPN messages put them inside <Id>..<\/Id> tags.\n * The class was modified to handle both cases and let the\n * SDK client retrieve either case by a single getMember() call.\n *\n * Valid example 1:\n * <IdList>\n * <member>S01-9228170-9681927-C035172<\/member>\n * <member>S01-9228170-9681927-C039558<\/member>\n * <\/IdList>\n *\n * Valid example 2:\n * <IdList>\n * <Id>S01-9228170-9681927-C035172<\/Id>\n * <Id>S01-9228170-9681927-C039558<\/Id>\n * <\/IdList>\n *\n * Invalid example (cannot mix Id and member tags in same group):\n * <IdList>\n * <member>S01-9228170-9681927-C035172<\/member>\n * <Id>S01-9228170-9681927-C039558<\/Id>\n * <\/IdList>\n *\/\n@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"IdList\", propOrder = {\n \"member\",\n \"id\"\n})\npublic class IdList {\n\n @XmlElement(name = \"member\")\n protected List member;\n @XmlElement(name = \"Id\")\n protected List id;\n\n \/**\n * Default constructor\n *\n *\/\n public IdList() {\n super();\n }\n\n public IdList(final List member) {\n this.member = member;\n }\n\n \/**\n * @return the members of the List\n *\/\n public List getMember() {\n if ((member == null) && (id == null)) {\n return new ArrayList();\n }\n return (member != null) ? member : id;\n }\n\n \/**\n * @return the ID of the members of the List\n *\/\n public List getId() {\n return getMember();\n }\n\n \/**\n * Returns the string representation of GetServiceStatusResult\n *\/\n @Override\n public String toString() {\n return \"IdList{\" + \"member=\" + getMember() + '}';\n }\n}","smell_code":" public IdList(final List member) {\n this.member = member;\n }","smell":"feature envy","id":197} {"lang_cluster":"Java","source_code":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\npackage org.apache.apex.malhar.contrib.parser;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\n\nimport org.json.simple.parser.ContentHandler;\n\nimport com.google.protobuf.TextFormat.ParseException;\n\n\/**\n * A concrete implementation of Json ContentHandler
\n * Matches JSON keys set from the {@link StreamingJsonParser }\n *\n * @since 3.5.0\n *\/\npublic class JsonKeyFinder implements ContentHandler\n{\n public JsonKeyFinder()\n {\n keyValMap = new HashMap<>();\n }\n\n public int getKeyCount()\n {\n return keyCount;\n }\n\n public void setKeyCount(int keyCount)\n {\n this.keyCount = keyCount;\n }\n\n private Object value;\n private HashMap keyValMap;\n private int keyCount = 0;\n\n public HashMap getKeyValMap()\n {\n return keyValMap;\n }\n\n public void setKeyValMap(HashMap keyValMap)\n {\n this.keyValMap = keyValMap;\n }\n\n private boolean found = false;\n private boolean end = false;\n private String key;\n\n private ArrayList matchKeyList;\n\n public void setMatchKeyList(ArrayList matchKeyList)\n {\n this.matchKeyList = matchKeyList;\n }\n\n public ArrayList getMatchKeyList()\n {\n return matchKeyList;\n }\n\n public Object getValue()\n {\n return value;\n }\n\n public boolean isEnd()\n {\n return end;\n }\n\n public void setFound(boolean found)\n {\n this.found = found;\n }\n\n public boolean isFound()\n {\n return found;\n }\n\n public void startJSON() throws ParseException, IOException\n {\n found = false;\n end = false;\n }\n\n public void endJSON() throws ParseException, IOException\n {\n end = true;\n }\n\n public boolean primitive(Object value) throws ParseException, IOException\n {\n if (getMatchKeyList().contains(key)) {\n found = true;\n this.value = value;\n keyValMap.put(key, value);\n key = null;\n keyCount++;\n return false;\n }\n return true;\n }\n\n public boolean startArray() throws ParseException, IOException\n {\n return true;\n }\n\n public boolean startObject() throws ParseException, IOException\n {\n return true;\n }\n\n public boolean startObjectEntry(String key) throws ParseException, IOException\n {\n this.key = key;\n return true;\n }\n\n public boolean endArray() throws ParseException, IOException\n {\n return false;\n }\n\n public boolean endObject() throws ParseException, IOException\n {\n return true;\n }\n\n public boolean endObjectEntry() throws ParseException, IOException\n {\n return true;\n }\n}","smell_code":" public void setMatchKeyList(ArrayList matchKeyList)\n {\n this.matchKeyList = matchKeyList;\n }","smell":"feature envy","id":198} {"lang_cluster":"Java","source_code":"\/*\n * Copyright 2006-2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations under the License.\n *\/\n\npackage org.springframework.security.oauth2.provider.expression;\n\nimport java.util.Arrays;\nimport java.util.LinkedHashSet;\nimport java.util.Set;\n\nimport org.springframework.security.access.AccessDeniedException;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;\n\n\/**\n * A convenience object for security expressions in OAuth2 protected resources, providing public methods that act on the\n * current authentication.\n * \n * @author Dave Syer\n * @author Rob Winch\n * @author Radek Ostrowski\n * \n *\/\npublic class OAuth2SecurityExpressionMethods {\n\n\tprivate final Authentication authentication;\n\n\tprivate Set missingScopes = new LinkedHashSet();\n\n\tpublic OAuth2SecurityExpressionMethods(Authentication authentication) {\n\t\tthis.authentication = authentication;\n\t}\n\n\t\/**\n\t * Check if any scope decisions have been denied in the current context and throw an exception if so. This method\n\t * automatically wraps any expressions when using {@link OAuth2MethodSecurityExpressionHandler} or\n\t * {@link OAuth2WebSecurityExpressionHandler}.\n\t * \n\t * OAuth2Example usage:\n\t * \n\t *

\n\t * access = "#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"\n\t * <\/pre>\n\t * \n\t * Will automatically be wrapped to ensure that explicit errors are propagated rather than a generic error when\n\t * returning false:\n\t * \n\t * 
\n\t * access = "#oauth2.throwOnError(#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"\n\t * <\/pre>\n\t * \n\t * N.B. normally this method will be automatically wrapped around all your access expressions. You could use it\n\t * explicitly to get more control, or if you have registered your own ExpressionParser<\/code> you might need\n\t * it.\n\t * \n\t * @param decision the existing access decision\n\t * @return true if the OAuth2 token has one of these scopes\n\t * @throws InsufficientScopeException if the scope is invalid and we the flag is set to throw the exception\n\t *\/\n\tpublic boolean throwOnError(boolean decision) {\n\t\tif (!decision && !missingScopes.isEmpty()) {\n\t\t\tThrowable failure = new InsufficientScopeException(\"Insufficient scope for this resource\", missingScopes);\n\t\t\tthrow new AccessDeniedException(failure.getMessage(), failure);\n\t\t}\n\t\treturn decision;\n\t}\n\n\t\/**\n\t * Check if the OAuth2 client (not the user) has the role specified. To check the user's roles see\n\t * {@link #clientHasRole(String)}.\n\t * \n\t * @param role the role to check\n\t * @return true if the OAuth2 client has this role\n\t *\/\n\tpublic boolean clientHasRole(String role) {\n\t\treturn clientHasAnyRole(role);\n\t}\n\n\t\/**\n\t * Check if the OAuth2 client (not the user) has one of the roles specified. To check the user's roles see\n\t * {@link #clientHasAnyRole(String...)}.\n\t * \n\t * @param roles the roles to check\n\t * @return true if the OAuth2 client has one of these roles\n\t *\/\n\tpublic boolean clientHasAnyRole(String... roles) {\n\t\treturn OAuth2ExpressionUtils.clientHasAnyRole(authentication, roles);\n\t}\n\n\t\/**\n\t * Check if the current OAuth2 authentication has the scope specified.\n\t * \n\t * @param scope the scope to check\n\t * @return true if the OAuth2 authentication has the required scope\n\t *\/\n\tpublic boolean hasScope(String scope) {\n\t\treturn hasAnyScope(scope);\n\t}\n\n\t\/**\n\t * Check if the current OAuth2 authentication has one of the scopes specified.\n\t * \n\t * @param scopes the scopes to check\n\t * @return true if the OAuth2 token has one of these scopes\n\t * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception\n\t *\/\n\tpublic boolean hasAnyScope(String... scopes) {\n\t\tboolean result = OAuth2ExpressionUtils.hasAnyScope(authentication, scopes);\n\t\tif (!result) {\n\t\t\tmissingScopes.addAll(Arrays.asList(scopes));\n\t\t}\n\t\treturn result;\n\t}\n\n\t\/**\n\t * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.\n\t * \n\t * 
\n\t * access = "#oauth2.hasScopeMatching('.*_admin:manage_scopes')))"\n\t * <\/pre>\n\t * \n\t * @param scopeRegex the scope regex to match\n\t * @return true if the OAuth2 authentication has the required scope\n\t *\/\n\tpublic boolean hasScopeMatching(String scopeRegex) {\n\t\treturn hasAnyScopeMatching(scopeRegex);\n\t}\n\n\t\/**\n\t * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.\n\t * \n\t * 
\n\t * access = "#oauth2.hasAnyScopeMatching('admin:manage_scopes','.*_admin:manage_scopes','.*_admin:read_scopes')))"\n\t * <\/pre>\n\t * \n\t * @param scopesRegex the scopes regex to match\n\t * @return true if the OAuth2 token has one of these scopes\n\t * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception\n\t *\/\n\tpublic boolean hasAnyScopeMatching(String... scopesRegex) {\n\n\t\tboolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex);\n\t\tif (!result) {\n\t\t\tmissingScopes.addAll(Arrays.asList(scopesRegex));\n\t\t}\n\t\treturn result;\n\t}\n\n\t\/**\n\t * Deny access to oauth requests, so used for example to only allow web UI users to access a resource.\n\t * \n\t * @return true if the current authentication is not an OAuth2 type\n\t *\/\n\tpublic boolean denyOAuthClient() {\n\t\treturn !OAuth2ExpressionUtils.isOAuth(authentication);\n\t}\n\n\t\/**\n\t * Permit access to oauth requests, so used for example to only allow machine clients to access a resource.\n\t * \n\t * @return true if the current authentication is not an OAuth2 type\n\t *\/\n\tpublic boolean isOAuth() {\n\t\treturn OAuth2ExpressionUtils.isOAuth(authentication);\n\t}\n\n\t\/**\n\t * Check if the current authentication is acting on behalf of an authenticated user.\n\t * \n\t * @return true if the current authentication represents a user\n\t *\/\n\tpublic boolean isUser() {\n\t\treturn OAuth2ExpressionUtils.isOAuthUserAuth(authentication);\n\t}\n\n\t\/**\n\t * Check if the current authentication is acting as an authenticated client application not on behalf of a user.\n\t * \n\t * @return true if the current authentication represents a client application\n\t *\/\n\tpublic boolean isClient() {\n\t\treturn OAuth2ExpressionUtils.isOAuthClientAuth(authentication);\n\t}\n}","smell_code":"\tpublic boolean hasAnyScope(String... scopes) {\n\t\tboolean result = OAuth2ExpressionUtils.hasAnyScope(authentication, scopes);\n\t\tif (!result) {\n\t\t\tmissingScopes.addAll(Arrays.asList(scopes));\n\t\t}\n\t\treturn result;\n\t}","smell":"feature envy","id":199}
{"lang_cluster":"Java","source_code":"\/*******************************************************************************\n * Copyright (c) 2004, 2005 Actuate Corporation.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n *  Actuate Corporation  - initial API and implementation\n *******************************************************************************\/\n\npackage org.eclipse.birt.report.data.adapter.group;\n\nimport java.util.Date;\n\nimport org.eclipse.birt.core.exception.BirtException;\n\nimport com.ibm.icu.util.TimeZone;\nimport com.ibm.icu.util.ULocale;\n\n\/**\n * This calculator is used to calculate a year group key basing group interval.\n *\/\nclass YearGroupCalculator extends DateGroupCalculator\n{\n\n\n\tpublic YearGroupCalculator( Object intervalStart, double intervalRange,\n\t\t\tULocale locale, TimeZone timeZone ) throws BirtException\n\t{\n\t\tsuper( intervalStart, intervalRange, locale, timeZone );\n\t}\n\n\t\/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.eclipse.birt.data.engine.impl.group.DateGroupCalculator#calculate(java.lang.Object)\n\t *\/\n\tpublic Object calculate( Object value )\n\t{\n\t\tif ( value == null )\n\t\t{\n\t\t\treturn new Double( -1 );\n\t\t}\n\n\t\tif ( intervalStart == null )\n\t\t{\n\t\t\treturn new Double( Math.floor( this.dateTimeUtil.diffYear( defaultStart,\n\t\t\t\t\t(Date) value )\n\t\t\t\t\t\/ getDateIntervalRange( ) ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( this.dateTimeUtil.diffYear( (Date) intervalStart, (Date) value ) < 0 )\n\t\t\t{\n\t\t\t\treturn new Double( -1 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn new Double( Math.floor( this.dateTimeUtil.diffYear( (Date) intervalStart,\n\t\t\t\t\t\t(Date) value )\n\t\t\t\t\t\t\/ getDateIntervalRange( ) ) );\n\t\t\t}\n\t\t}\n\t}\n}","smell_code":"\tpublic Object calculate( Object value )\n\t{\n\t\tif ( value == null )\n\t\t{\n\t\t\treturn new Double( -1 );\n\t\t}\n\n\t\tif ( intervalStart == null )\n\t\t{\n\t\t\treturn new Double( Math.floor( this.dateTimeUtil.diffYear( defaultStart,\n\t\t\t\t\t(Date) value )\n\t\t\t\t\t\/ getDateIntervalRange( ) ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( this.dateTimeUtil.diffYear( (Date) intervalStart, (Date) value ) < 0 )\n\t\t\t{\n\t\t\t\treturn new Double( -1 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn new Double( Math.floor( this.dateTimeUtil.diffYear( (Date) intervalStart,\n\t\t\t\t\t\t(Date) value )\n\t\t\t\t\t\t\/ getDateIntervalRange( ) ) );\n\t\t\t}\n\t\t}\n\t}","smell":"feature envy","id":200}