text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FlattenArray { class Program { static int[] FlattenArray(int[][] arr) { var counter = 0; int[] newArr = new int[arr.Length * arr.GetUpperBound(0)]; foreach(var item in arr) { newArr[counter] = item[0]; counter++; newArr[counter] = item[1]; counter++; } return newArr; } static void Main(string[] args) { var values = new[] { new[] { 1, 2 }, new[] { 2, 3 }, new[] { 4, 5 }, }; FlattenArray(values); } } }
using System; namespace Shapes { class Program { static void PrintNumberOfPoints(IPointy iface) { Console.WriteLine("Число вершин {0}", iface.NumberOfPoints()); } static IMeasurable GetTheLargest(params object[] figures) { IMeasurable result = null; foreach (object figure in figures) { if (figure is IMeasurable) { var iface = (IMeasurable)figure; if (result == null || iface.GetArea() > result.GetArea()) result = iface; } } return result; } static void Main() { var myPoint = new Point(1, 2); //Console.WriteLine(myPoint); //myPoint.PrintInfo(); var myCircle = new Circle() { Radius = 2, Center = myPoint }; //myCircle.PrintInfo(); var myTriangle = new Triangle() { Name = "ABC", A = new Point(0, 0), B = new Point(1, 0), C = new Point(0, 1) }; //myTriangle.PrintInfo(); //Console.WriteLine("Число вершин {0}", // myTriangle.NumberOfPoints()); //PrintNumberOfPoints(myTriangle); var myRectangle = new Rectangle() { A = new Point(1, 1), C = new Point(-1, -1), Name = "ABCD"}; //myRectangle.PrintInfo(); //Console.WriteLine("Число вершин {0}", // myRectangle.NumberOfPoints()); //PrintNumberOfPoints(myRectangle); var myLine = new Line() { A = new Point(), B = new Point(1, 1) }; IPrintable[] ifacePr = new IPrintable[] { (IPrintable)myCircle, myTriangle, myLine, myRectangle, myPoint }; foreach (var figure in ifacePr) { figure.PrintInfo(); if (figure is IPointy) PrintNumberOfPoints((IPointy)figure); if (figure is IMeasurable) Console.WriteLine("Площадь равна {0:F3} кв. ед.", ((IMeasurable)figure).GetArea()); if (figure is IPolygone) Console.WriteLine("Число диагоналей равно " + ((IPolygone)figure).NumberOfDiagonals); } Console.WriteLine("Фигура наибольшей площади имеет площадь {0:F3}", GetTheLargest(myPoint, myTriangle, myCircle, myLine).GetArea()); myCircle.Draw(); var ifaceScreen = (IScreenable)myCircle; var IfacePlotter = (IPlottarable)myCircle; ifaceScreen.Draw(); IfacePlotter.Draw(); foreach (Point vertex in myTriangle) vertex.PrintInfo(); myTriangle.A = new Point(-1, -1); myTriangle.PrintInfo(); foreach (Point vertex in myTriangle) vertex.PrintInfo(); myRectangle.PrintInfo(); foreach (Point vert in myRectangle) vert.PrintInfo(); //var iEnum = myRectangle.GetEnumerator(); //while (true) //{ // if (iEnum.MoveNext()) // { // var p = iEnum.Current as Point; // p.PrintInfo(); // } // else // iEnum.Reset(); // if (Console.KeyAvailable) // break; //} var myQuadrangle = new Quadrangle() { A = new Point(), B = new Point(5, 0), C = new Point(5, 5), D = new Point(-5, 0) }; myQuadrangle.PrintInfo(); foreach (Point vert in myQuadrangle) vert.PrintInfo(); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIGodGaugeManager : MonoBehaviour { public GodData GD; public RectTransform BackGround; public RectTransform Gauge; private float MaxWidth; // Use this for initialization private void Start() { MaxWidth = BackGround.rect.width; } // Update is called once per frame private void Update() { float currentGaugePercent = GD.LiftGauge / GD.MaxGauge; Gauge.sizeDelta = new Vector2(MaxWidth * currentGaugePercent, Gauge.sizeDelta.y); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MultiplechoiseSystem.DTO; namespace MultiplechoiseSystem.FORM { public partial class UCEditInfo : UserControl { public EventHandler BtnConfirmClick; public EventHandler BtnCloseClick; public UCEditInfo() { InitializeComponent(); } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void panel18_Paint(object sender, PaintEventArgs e) { } private void panel16_Paint(object sender, PaintEventArgs e) { } private void btnExit_Click(object sender, EventArgs e) { if (this.BtnCloseClick!=null) { this.BtnCloseClick(this, e); } } private void btnConfirm_Click(object sender, EventArgs e) { if (this.BtnConfirmClick != null) { this.BtnConfirmClick(this, e); } } private void UCEditInfo_Load(object sender, EventArgs e) { txtFistName.Text = UserDTO.Instance.FirstName; txtlastName.Text = UserDTO.Instance.LastName; if (UserDTO.Instance.sex == "M") { lbSex.Text = "Male"; } else lbSex.Text = "FeMale"; tbUsernam.Text = UserDTO.Instance.Username; tbPassword.Text = UserDTO.Instance.password; try { tbAddress.Text = UserDTO.Instance.Address; dateOfBirth.Value = UserDTO.Instance.DateOfBirth; } catch(Exception a) { } } } }
using System.Collections.Generic; using Framework.Core.Common; using Tests.Pages.Oberon.Contact; using NUnit.Framework; using Tests.Data.Oberon; using Tests.Pages.Oberon.Common; using Tests.Pages.Oberon.Contribution; using Tests.Pages.Oberon.Disbursement; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using Tests.Pages.Oberon.Pledge; namespace Tests.Pages.Oberon { public class RightPane : FormElements { public RightPane(Driver driver) : base(driver) { //ExpandOuterSection(FinanceSummarySection); //ExpandOuterSection(ActivitySummarySection); //ExpandOuterSection(ContributionAtAGlanceSection); } #region Page Objects private IWebElement ContactNavigationDiv { get { return _driver.FindElement(By.CssSelector("#subColumn")); } } private IWebElement FinanceSummarySection { get { return _driver.FindElement(By.CssSelector("#FinanceSummarySection")); } } private IWebElement FinanceSummary { get { return _driver.FindElement(By.CssSelector("#financeSummary")); } } private IWebElement ActivitySummarySection { get { return _driver.FindElement(By.CssSelector("#ActivitySummarySection")); } } private IWebElement ActivitySumary { get { return _driver.FindElement(By.CssSelector("#activitySummary")); } } private IWebElement ContributionAtAGlanceSection { get { return _driver.FindElement(By.CssSelector("#ContributionsAtAGlanceSection")); } } private IWebElement ContributionAtAGlance { get { return _driver.FindElement(By.CssSelector("#contributionsGlanceWidgetContainer")); } } private IWebElement Notes { get { return _driver.FindElement(By.CssSelector("#ContactNoteForm")); } } private IWebElement ContactNotes { get { return _driver.FindElement(By.CssSelector("#contactNotes")); } } #endregion #region Methods #region Contact Navigation /// <summary> /// Clicks contact search previous button /// </summary> public void ClickContactSerachBackButton() { ContactNavigationDiv.FindElement(By.CssSelector(".previous span")).Click(); } /// <summary> /// Clicks contact search next button /// </summary> public void ClickContactSerachNextButton() { ContactNavigationDiv.FindElement(By.CssSelector(".next span")).Click(); } /// <summary> /// Clicks create search link /// </summary> public void ClickCreateSerachLink() { ContactNavigationDiv.FindElement(By.CssSelector(".backToList.strong a")).Click(); } #endregion #region Finance Summary #region Contributions /// <summary> /// returns Contributions list element in Finance Summary IWebElement /// </summary> private IWebElement Contributions() { return FinanceSummary.FindElement(By.ClassName("contributions")); } /// <summary> /// retruns recent contribution table in finance summary /// </summary> /// <returns></returns> private IWebElement RecentContributionsTable() { return FinanceSummary.FindElement(By.ClassName("RecentContributionsTable")); } /// <summary> /// clicks view contributions in Finance Summary /// </summary> public void ClickViewContributions() { _driver.Click(Contributions().FindElement(By.CssSelector("span.view"))); var list = new ContributionList(_driver); list.WaitForSectionTitle(); } /// <summary> /// clicks view contribution list in Finance Summary /// </summary> public void ClickViewContributionList() { _driver.Click( Contributions().FindElement(By.XPath("//div[@id='contributionsActivityContainer']/div/span/a"))); } /// <summary> /// clicks add contributions button in Contributions Finance Summary /// </summary> public void ClickAddContributionButton() { //_driver.Click(AddContributionButton); _driver.Click(Contributions().FindElement(By.CssSelector(".action a"))); var contributionCreate = new ContributionCreate(_driver); contributionCreate.WaitForSectionTitle(); } /// <summary> /// returns most recent contributions IWebElement in recent contributions summary /// </summary> public IWebElement MostRecentContribution() { var recentContributions = new List<IWebElement>( RecentContributionsTable().FindElements(By.CssSelector(".MostRecentContributionsData"))); return recentContributions[0]; } /// <summary> /// returns most recent contributions in recent contributions summary /// </summary> public string GetMostRecentContributionAmount() { ExpandInnerSection(Contributions().FindElement(By.Id("contributionsActivityContainer"))); return MostRecentContribution().FindElement(By.CssSelector("td.alignRight.link")).Text.Trim(); } #endregion #region Pledges /// <summary> /// returns Pledges list element in Finance Summary IWebElement /// </summary> private IWebElement Pledges() { return FinanceSummary.FindElement(By.ClassName("pledges")); } private IWebElement PledgeLink() { return Pledges().FindElement(By.XPath("./child::div/div/span/a")); } public void ClickAddPledgeButton() { _driver.Click(Pledges().FindElement(By.CssSelector(".action a"))); var pledgeCreate = new PledgeCreate(_driver); pledgeCreate.WaitForSectionTitle(); } public void ClickPledgeCountLink() { _driver.Click(Pledges().FindElement(By.XPath("./child::div/div/span/a"))); var list = new PledgeList(_driver); list.WaitForSectionTitle(); } public int GetPledgeCount() { return int.Parse(Pledges().FindElement(By.XPath("./child::div/div/span/a")).Text); } #endregion #region Disbursements /// <summary> /// returns Disbursements list element in Finance Summary IWebElement /// </summary> private IWebElement Disbursements() { return FinanceSummary.FindElement(By.ClassName("disbursements")); } /// <summary> /// returns add disbursements button /// </summary> /// <returns></returns> private IWebElement AddDisbursementButton() { return Disbursements().FindElement(By.CssSelector(".action a")); } /// <summary> /// adds new disbursement by code, returns disbursement code /// </summary> public string AddNewDisbursement(string code) { return AddNewDisbursement(code, string.Empty); } /// <summary> /// adds new disbursementby code and public code, returns disbursement code /// </summary> /// public string AddNewDisbursement(string code, string publicCode) { CLickAddNewDisbursementButton(); var create = new DisbursementCreate(_driver); return create.AddDisembrusement(code); } /// <summary> /// adds new disbursement from disbursement object, returns new disbursement /// </summary> public string AddNewDisbursement(TestDisbursement disbursement) { CLickAddNewDisbursementButton(); var createDisbursment = new DisbursementCreate(_driver); return createDisbursment.CreateDisbursement(disbursement); } public void CLickAddNewDisbursementButton() { _driver.Click(AddDisbursementButton()); var create = new DisbursementCreate(_driver); WaitForSectionTitleToDisplay(create.SectionTitleLocator, create.SectionTitle, create.SectionTitleText); } #endregion #region Debts #endregion #endregion #region Activity Summary #region Call Logs /// <summary> /// returns Call Logs list element in Activity Summary IWebElement /// </summary> private IWebElement CallLogs() { return ActivitySumary.FindElement(By.ClassName("calllogs")); } /// <summary> /// returns call log count /// </summary> public string GetCallLogCount() { return CallLogs().FindElement(By.CssSelector("span.view")).Text; } /// <summary> /// clicks add a log button /// </summary> public void ClickAddALogButton() { _driver.Click(CallLogs().FindElement(By.CssSelector(".action a"))); } #endregion #region Events /// <summary> /// returns Events list element in Activity Summary IWebElement /// </summary> private IWebElement Events() { return FinanceSummary.FindElement(By.ClassName("events")); } /// <summary> /// clicks events add button /// </summary> public void ClickEventsAddButton() { Events().FindElement(By.ClassName("action")).Click(); } #endregion #region Relationships & Househould #endregion #region Email Messages #endregion #region Mailings (Postal) #endregion #region Research & Giving History #endregion #region MyVoters Link /// <summary> /// clicks my voters link in Activity Summary IWebElement /// </summary> public void ClickMyVotersLink() { _driver.Click(ActivitySumary.FindElement(By.CssSelector("li.myVoters span"))); var voterInfo = new ContactMyVotersInformation(_driver); _driver.WaitForElementToDisplayBy(voterInfo.CopyFromMyVotersButtonLocator); } #endregion #endregion #region Contribution At A Glance #endregion #region Notes /// <summary> /// types text into note text field /// </summary> /// <param name="text"></param> public void SetNoteText(string text) { Notes.FindElement(By.CssSelector("#NoteText")).SendKeys(text); } /// <summary> /// Clears date and sets date picker with date /// </summary> /// <param name="date"></param> public void SetNoteDate(string date) { var datePicker = Notes.FindElement(By.CssSelector("#NoteDate")); datePicker.Clear(); datePicker.SendKeys(date); } /// <summary> /// Clicks add note button /// </summary> public void ClickAddNoteButton() { Notes.FindElement(By.CssSelector(".actionButtons #saveNoteButton")).Click(); } /// <summary> /// clicks cancel link /// </summary> public new void ClickCancelLink() { Notes.FindElement(By.CssSelector(".actionButtons #cancelNoteLink")).Click(); } /// <summary> /// adds note with text and data /// </summary> /// <param name="text"></param> /// <param name="date"></param> public void SetNote(string text, string date) { SetNoteText(text); SetNoteDate(date); ClickAddNoteButton(); } public string GetNoteTimestamp(string noteText) { return FindNote(noteText).FindElement(By.CssSelector(".dateAndEdit span")).Text; } /// <summary> /// returns note element from text /// </summary> /// <param name="noteToFind"></param> /// <returns></returns> public IWebElement FindNote(string noteToFind) { var notes = new List<IWebElement>(ContactNotes.FindElements(By.TagName("li"))); foreach (var note in notes) { if (note.FindElement(By.ClassName("note")).Text.Contains(noteToFind)) return note; } return null; } /// <summary> /// edits note based on text of note /// </summary> /// <param name="noteToEdit"></param> /// <param name="newText"></param> /// <param name="newDate"></param> public void EditNote(string noteToEdit, string newText, string newDate) { var notes = new List<IWebElement>(ContactNotes.FindElements(By.TagName("li"))); var note = FindNote(noteToEdit); _driver.MoveToElement(note); note.FindElement(By.ClassName("edit")).Click(); SetNote(newText, newDate); } /// <summary> /// deletes note based on text of note /// </summary> /// <param name="noteToEdit"></param> public void DeleteNote(string noteToEdit) { var notes = new List<IWebElement>(ContactNotes.FindElements(By.TagName("li"))); var note = FindNote(noteToEdit); _driver.MoveToElement(note); note.FindElement(By.ClassName("delete")).Click(); var modal = new DeleteConfirmationModal(_driver); modal.ClickYes(); } #endregion #region Expanders /// <summary> /// expands section if header is collapsed /// </summary> /// <param name="section"></param> public void ExpandOuterSection(IWebElement section) { if (section.GetAttribute("class").Contains("title isExpandable")) section.Click(); } /// <summary> /// expands section if header is collapsed /// </summary> /// <param name="section"></param> public void ExpandInnerSection(IWebElement section) { if (section.GetAttribute("class").Contains("isExpandable")) section.Click(); } #endregion #endregion } }
using System.Reflection; using StardewModdingAPI; using StardewValley; using StardewValley.Locations; namespace BetterSkullCavernFalling { internal class SkullCavernFallMessageIntercepter { private static readonly MethodInfo MINESHAFT_AFTERFALL_METHOD = typeof(MineShaft).GetMethod("afterFall", BindingFlags.Instance | BindingFlags.NonPublic); private readonly int mineLevel; private readonly int levelsDownFallen; private void AfterFall() { // string message = Game1.content.LoadString("Strings\\StringsFromCSFiles:MineShaft.cs.9578", levelsDownFallen) + (levelsDownFallen > 7 ? Game1.content.LoadString("Strings\\StringsFromCSFiles:MineShaft.cs.9580") : ""); string message = Game1.content.LoadString(levelsDownFallen > 7 ? "Strings\\Locations:Mines_FallenFar" : "Strings\\Locations:Mines_Fallen", levelsDownFallen); Game1.addHUDMessage(new HUDMessage(message) { noIcon = true }); Game1.enterMine(mineLevel + levelsDownFallen); Game1.player.faceDirection(2); Game1.player.showFrame(5, false); Game1.globalFadeToClear(null, 0.01f); } private SkullCavernFallMessageIntercepter(MineShaft mineShaft, IReflectionHelper reflection) { this.mineLevel = mineShaft.mineLevel; this.levelsDownFallen = reflection.GetField<int>(mineShaft, "lastLevelsDownFallen").GetValue(); } internal static void Intercept(IReflectionHelper reflection) { if (Game1.afterFade != null && Game1.afterFade.Target is MineShaft mineShaft && Game1.afterFade.Method == MINESHAFT_AFTERFALL_METHOD) { Game1.afterFade = new SkullCavernFallMessageIntercepter(mineShaft, reflection).AfterFall; } } } }
namespace Assets.Scripts.Models.ResourceObjects { public class StoneResource : ResourceObject { public StoneResource() { LocalizationName = "stone_resource"; IconName = "stone_icon"; CanBuy = true; ShopPrice = 2; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace RPC.JsonRPC { [AttributeUsage(AttributeTargets.Interface)] public sealed class JsonRPCAttribute : RPCAttribute { public JsonRPCAttribute(string category, string version, string name) : base(category, version, name) { } public override IExecutor GetExecutor(Type interfaceType, string methodName, Func<Type> getImplementationType = null) { Type implType = null; if (getImplementationType != null) implType = getImplementationType(); return (IExecutor)Executor.ExecutorFor(interfaceType, implType, methodName); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Caserraria.Items; namespace Caserraria.Items.Weapons { public class PhantomDagger : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Phantom Dagger"); Tooltip.SetDefault("A magical returning dagger" + Environment.NewLine + "Phases through walls"); } public override void SetDefaults() { item.damage = 70; item.magic = true; item.mana = 8; item.noUseGraphic = true; item.width = 10; item.height = 24; item.useTime = 7; item.useAnimation = 7; item.useStyle = 1; item.noMelee = true; item.knockBack = 4; item.value = Item.sellPrice(gold: 8); item.rare = 8; item.UseSound = SoundID.Item1; item.autoReuse = true; item.shoot = mod.ProjectileType("PhantomDaggerProj"); item.shootSpeed = 20f; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.MagicDagger); recipe.AddIngredient(ItemID.Ectoplasm, 5); recipe.AddTile(TileID.MythrilAnvil); recipe.SetResult(this); recipe.AddRecipe(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using BlazorShared.Models.Appointment; using BlazorShared.Models.AppointmentType; using BlazorShared.Models.Room; using FrontDesk.Blazor.Services; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; namespace FrontDesk.Blazor.Shared.SchedulerComponent { public partial class Scheduler { [Inject] IJSRuntime JSRuntime { get; set; } [Inject] AppointmentService AppointmentService { get; set; } [Inject] SchedulerService SchedulerService { get; set; } [Parameter] public int Height { get; set; } = 750; [Parameter] public RenderFragment ChildContent { get; set; } [Parameter] public RenderFragment<Resource> RenderFragmentResources { get; set; } [Parameter] public List<string> Groups { get; set; } = new List<string>(); [Parameter] public DateTime StartDate { get; set; } = new DateTime(); [Parameter] public DateTime StartTime { get; set; } = new DateTime(); [Parameter] public DateTime EndTime { get; set; } = new DateTime(); [Parameter] public List<RoomDto> Rooms { get; set; } = new List<RoomDto>(); [Parameter] public List<AppointmentTypeDto> AppointmentTypes { get; set; } = new List<AppointmentTypeDto>(); [Parameter] public List<SchedulerResourceModel> SchedulerResources { get; set; } = new List<SchedulerResourceModel>(); [Parameter] public EventCallback<AppointmentDto> OnEditCallback { get; set; } private List<SchedulerResourceModel> Resources { get; set; } = new List<SchedulerResourceModel>(); private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { SchedulerService.RefreshRequested += Refresh; CallJSMethod(); var thisReference = DotNetObjectReference.Create(this); await JSRuntime.InvokeVoidAsync("addListenerToFireEdit", thisReference); } await base.OnAfterRenderAsync(firstRender); } public void AddResource(Resource resourceComponent) { Resources.Add(resourceComponent.SchedulerResource); Refresh(); } public void Refresh() { CallJSMethod(); } private void CallJSMethod() { var processRuntime = JSRuntime as IJSInProcessRuntime; processRuntime.InvokeVoid("scheduler", StartDate, StartTime, EndTime, SchedulerService.Appointments, Resources, Groups, Height); } [JSInvokable] public async Task KendoCall(string action, string jsonData) { if (action == "edit") { var result = JsonSerializer.Deserialize<AppointmentDto>(jsonData, JsonOptions); await OnEditCallback.InvokeAsync(result); } else if (action == "move") { var result = JsonSerializer.Deserialize<AppointmentDto>(jsonData, JsonOptions); await AppointmentService.EditAsync(UpdateAppointmentRequest.FromDto(result)); } else if (action == "delete") { var result = JsonSerializer.Deserialize<AppointmentDto>(jsonData, JsonOptions); await AppointmentService.DeleteAsync(result.AppointmentId); SchedulerService.Appointments.Remove(SchedulerService.Appointments.First(x => x.AppointmentId == result.AppointmentId)); CallJSMethod(); } } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace Data.Models.Mapping { public class subjectMap : EntityTypeConfiguration<subject> { public subjectMap() { // Primary Key this.HasKey(t => t.id_subject); // Properties this.Property(t => t.message) .HasMaxLength(255); this.Property(t => t.name_subject) .HasMaxLength(255); // Table & Column Mappings this.ToTable("subject", "vgta"); this.Property(t => t.id_subject).HasColumnName("id_subject"); this.Property(t => t.message).HasColumnName("message"); this.Property(t => t.name_subject).HasColumnName("name_subject"); this.Property(t => t.categoryForums).HasColumnName("categoryForums"); // Relationships this.HasOptional(t => t.categoryforum) .WithMany(t => t.subjects) .HasForeignKey(d => d.categoryForums); } } }
using System; using System.Collections.Generic; namespace Mio.TileMaster { public enum SongItemType { Normal = 0, Hot = 1, New = 2 } [Serializable] public class SongDataModel { //unique id for each song public int ID; //name of the song to be display to user public string name; //author or origin of the song public string author; //url to download level data public string songURL; //the unique id of this song item public string storeID; //version of this song data public int version; //price in primary currency of the game (currency bought from cash) public int pricePrimary; //how many star needed to unlock this song public int starsToUnlock; //maximum speed this level will reach public float maxBPM; //number of ticks for a black tiles public int tickPerTile; //faster or slower speed public float speedModifier; public List<float> speedPerStar; //type of the song (new, hot or normal one) public SongItemType type; } }
using System.Collections.Generic; using Microsoft.Xna.Framework; using SuperMario.Collision; using SuperMario.Entities.Items; using SuperMario.Entities.Mario; using SuperMario.Entities.Mario.MarioCondition; using static SuperMario.Entities.MovementDirectionsEnum; namespace SuperMario.Entities.Blocks { public abstract class Block { public static IList<Direction> GetRestrictedMovement(RectangleCollisions rectangleCollisions) { List<Direction> restrictedMovementDirection = new List<Direction>(); if (rectangleCollisions.Collisions.Contains(RectangleCollision.TopBottom)) restrictedMovementDirection.Add(Direction.Up); if (rectangleCollisions.Collisions.Contains(RectangleCollision.BottomTop)) restrictedMovementDirection.Add(Direction.Down); if (rectangleCollisions.Collisions.Contains(RectangleCollision.LeftRight)) restrictedMovementDirection.Add(Direction.Right); if (rectangleCollisions.Collisions.Contains(RectangleCollision.RightLeft)) restrictedMovementDirection.Add(Direction.Left); return restrictedMovementDirection; } public static Entity CreateItem(BlockItemType blockItemType, Vector2 screenLocation, MarioEntity mario) { screenLocation.Y -= 16; switch (blockItemType) { case BlockItemType.PowerUp: if (mario.CurrentMarioCondition is SmallMario || mario.CurrentMarioCondition is StarSmallMario) return new RedMushroom(screenLocation); return new Flower(screenLocation); case BlockItemType.Coin: var coin = new Coin(screenLocation); coin.Hit(); return coin; case BlockItemType.Star: return new Star(screenLocation); case BlockItemType.GreenMushroom: return new GreenMushroom(screenLocation); case BlockItemType.None: return null; } return null; } } public enum BlockItemType { PowerUp, GreenMushroom, Coin, Star, None } }
using System; using System.Windows; using AIMLbot.Utils; using System.Windows.Input; namespace AIMLbot.UI { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { readonly ChatBot _chatBot = new ChatBot(); public MainWindow() { InitializeComponent(); var loader = new AIMLLoader(); const string path = @"Human.aiml"; loader.LoadAIML(path); } private void Button_Click(object sender, RoutedEventArgs e) { var text = TextBox.Text; if (String.IsNullOrWhiteSpace(text)) { return; } var output = _chatBot.Chat(text, "1"); TextBlock.Text = output.Output; } private void TextBox_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { e.Handled = true; Button_Click(sender, e); } } } }
using System; using System.Threading.Tasks; namespace CC.Utilities { public class Timer { public bool IsPaused{ get; private set; } public bool IsRunning { get; set; } public int WaitTime { get; set; } public event EventHandler Elapsed; protected virtual void OnTimerElapsed() { if (Elapsed != null) { Elapsed(this, new EventArgs()); } } public Timer(int waitTime) { WaitTime = waitTime; } public async void Start() { int seconds = 0; IsRunning = true; while (IsRunning) { if (!IsPaused && seconds != 0 && seconds % WaitTime == 0) { OnTimerElapsed(); } await Task.Delay(1000); if (!IsPaused) { seconds++; } } } public void Pause(){ IsPaused = true; } public void Resume(){ IsPaused = false; } public void Stop() { IsRunning = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training { public abstract class Shape { public Shape() { Console.WriteLine("The shape is created..."); } public abstract void Draw(); public abstract double Area(); public abstract double Perimeter(); } public class Triangle : Shape { private readonly double ab; private readonly double bc; private readonly double ac; public Triangle(double ab, double bc, double ac) { this.ab = ab; this.bc = bc; this.ac = ac; Console.WriteLine("The triangle is created..."); } public override double Area() { double p = (ab + bc + ac) / 2; return Math.Sqrt(p * (p - ab) * (p - bc) * (p - ac)); } public override void Draw() { Console.WriteLine("Drawing triangle..."); } public override double Perimeter() { return ab + bc + ac; } } public class Rectangle : Shape { private readonly double width; private readonly double height; public Rectangle(double width, double height) { this.width = width; this.height = height; Console.WriteLine("The rectangle is created..."); } public override double Area() { return width * height; } public override void Draw() { Console.WriteLine("Drawing rectangle..."); } public override double Perimeter() { return (width + height) * 2; } } }
using System; namespace SharpNES.Utility { public enum LogLevel { Debug3, Debug2, Debug, Info, Warning, Error, Fatal } // ---------- Policies ---------- // public interface IFormatPolicy { string Format(string timestamp, LogLevel level, string tag, string message); } public interface IStreamPolicy { void Write(LogLevel level, string buffer); } public class Logger<Formater, StreamWriter> where Formater : IFormatPolicy, new() where StreamWriter : IStreamPolicy, new() { private IFormatPolicy _formater = new Formater(); private IStreamPolicy _streamWriter = new StreamWriter(); public LogLevel MinLogLevel { get; set; } public Logger(LogLevel minLevel = LogLevel.Info) { MinLogLevel = minLevel; } virtual public void Log(LogLevel level, string tag, string msg) { if (level > MinLogLevel) { _streamWriter.Write( level, _formater.Format( DateTime.Now.ToString("HH:mm:ss.fff"), level, tag, msg ) ); } } public void LogFatal(string tag, string msg) { Log(LogLevel.Fatal, tag, msg); } public void LogError(string tag, string msg) { Log(LogLevel.Error, tag, msg); } public void LogWarning(string tag, string msg) { Log(LogLevel.Warning, tag, msg); } public void LogInfo(string tag, string msg) { Log(LogLevel.Info, tag, msg); } public void LogDebug(string tag, string msg) { Log(LogLevel.Debug, tag, msg); } public void LogDebug2(string tag, string msg) { Log(LogLevel.Debug2, tag, msg); } public void LogDebug3(string tag, string msg) { Log(LogLevel.Debug3, tag, msg); } } public class DefaultLogger : Logger<DefaultFormater, ConsoleStream> { public DefaultLogger(LogLevel level = LogLevel.Info) : base(level) { } } // ---------- Basic policies ---------- // public class DefaultFormater : IFormatPolicy { string IFormatPolicy.Format(string timestamp, LogLevel level, string tag, string msg) { string buffer = "- "; buffer += timestamp; buffer += " ["; buffer += Enum.GetName(level.GetType(), level); buffer += "]"; buffer += " ("; buffer += tag; buffer += "): "; buffer += msg; return buffer; } } public class ConsoleStream : IStreamPolicy { private static readonly ConsoleColor[] _colorSet = { ConsoleColor.White, // Debug3 ConsoleColor.White, // Debug2 ConsoleColor.White, // Debug ConsoleColor.DarkGreen, // Info ConsoleColor.Yellow, // Warning ConsoleColor.Red, // Error ConsoleColor.Red, // Fatal }; void IStreamPolicy.Write(LogLevel level, string buffer) { Console.ForegroundColor = _colorSet[(int)level]; Console.WriteLine(buffer); Console.ForegroundColor = ConsoleColor.White; } } }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual; using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual; using Pe.Stracon.SGC.Infraestructura.Core.Context; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual { /// <summary> /// Implementación del Adaptador de Requerimiento Párrafo Variable /// </summary> public class RequerimientoParrafoVariableAdapter { /// <summary> /// Realiza la adaptación de campos para registrar o actualizar /// </summary> /// <param name="data">Datos a registrar o actualizar</param> /// <returns>Entidad Requerimiento Párrafo Variable con los datos a registrar</returns> public static RequerimientoParrafoVariableEntity RegistrarRequerimientoParrafoVariable(RequerimientoParrafoVariableRequest data) { var contratoParrafoVariableEntity = new RequerimientoParrafoVariableEntity(); NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); numberFormatInfo.NumberDecimalSeparator = "."; numberFormatInfo.NumberGroupSeparator = ","; if (data.CodigoRequerimientoParrafoVariable != null) { contratoParrafoVariableEntity.CodigoRequerimientoParrafoVariable = new Guid(data.CodigoRequerimientoParrafoVariable.ToString()); } else { Guid code; code = Guid.NewGuid(); contratoParrafoVariableEntity.CodigoRequerimientoParrafoVariable = code; } contratoParrafoVariableEntity.CodigoRequerimientoParrafo = new Guid(data.CodigoRequerimientoParrafo); contratoParrafoVariableEntity.CodigoVariable = new Guid(data.CodigoVariable); contratoParrafoVariableEntity.ValorTexto = data.ValorTexto; if (!string.IsNullOrWhiteSpace(data.ValorNumeroString)) { contratoParrafoVariableEntity.ValorNumero = Decimal.Parse(data.ValorNumeroString, numberFormatInfo); } if (!string.IsNullOrWhiteSpace(data.ValorFechaString)) { contratoParrafoVariableEntity.ValorFecha = DateTime.ParseExact(data.ValorFechaString, DatosConstantes.Formato.FormatoFecha, System.Globalization.CultureInfo.InvariantCulture); } contratoParrafoVariableEntity.ValorImagen = data.ValorImagen; contratoParrafoVariableEntity.ValorTabla = data.ValorTabla; contratoParrafoVariableEntity.ValorTablaEditable = data.ValorTablaEditable; contratoParrafoVariableEntity.ValorBien = data.ValorBien; contratoParrafoVariableEntity.ValorBienEditable = data.ValorBienEditable; contratoParrafoVariableEntity.ValorFirmante = data.ValorFirmante; contratoParrafoVariableEntity.ValorFirmanteEditable = data.ValorFirmanteEditable; contratoParrafoVariableEntity.ValorLista = !string.IsNullOrEmpty(data.ValorLista) ? (Guid?)new Guid(data.ValorLista) : null; contratoParrafoVariableEntity.FechaCreacion = DateTime.Now; return contratoParrafoVariableEntity; } } }
using System; namespace RetContorno { class Program { static void Main(string[] args) { int altura, largura, meio = 1; bool vlvalido; //vl = valor Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(" ----- CONTORNO ----- \n"); Console.ForegroundColor = ConsoleColor.White; Console.Write("Largura...:"); vlvalido = Int32.TryParse (Console.ReadLine(), out largura); Console.Write("Altura...:"); vlvalido = Int32.TryParse (Console.ReadLine(), out altura); if (!vlvalido || largura < 1 || largura > 10) { Console.Write("Programa finalizado: valor "); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("INVÁLIDO."); Console.ForegroundColor = ConsoleColor.White; Environment.Exit(-1); } else { int linhac = 1; Console.ForegroundColor = ConsoleColor.White; while (linhac <= largura) { Console.Write("* "); linhac++; } Console.WriteLine(); int p1 = altura - 2; // passo 1 while(meio <= p1) { int p2 = 1; // passo 2 Console.Write("* "); int result = largura - 2; while (p2 <= result) { Console.Write(" "); p2++; } Console.ForegroundColor = ConsoleColor.White; Console.Write("* "); Console.WriteLine(); meio++; } int linha2 = 1; Console.ForegroundColor = ConsoleColor.White; while (linha2 <= largura) { Console.Write("* "); linha2++; } Console.WriteLine("\nPressione enter para finalizar <3 "); Console.ReadKey(); } } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using StickFigure.Helpers; namespace StickFigure.Graphics { /// <summary> /// Code from https://social.msdn.microsoft.com/Forums/vstudio/en-US/0c4252c8-8274-449c-ad9b-e4f07a8f8cdd/how-could-i-create-an-animated-gif-file-from-several-other-jpg-files-in-c-express?forum=csharpgeneral /// But fixed to resemble normal C# /// </summary> public static class GifCreator { private static readonly byte[] GifAnimation = { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 }; private static byte[] Delay = { 20, 0 }; public static void CreateGif(string currentFolder) { string gifFolder = FileManager.GetGifFolder(currentFolder); Directory.CreateDirectory(gifFolder); string jpgFolder = FileManager.GetJpgFolder(currentFolder); string gifFile = Path.Combine(gifFolder, "sf.gif"); using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(new FileStream(gifFile, FileMode.Create))) { string[] jpgFiles = Directory.GetFiles(jpgFolder, "*.jpg").OrderBy(NumberPart).ToArray(); Image.FromFile(jpgFiles[0]).Save(ms, ImageFormat.Gif); byte[] bytes = ms.ToArray(); bytes[10] = (byte)(bytes[10] & 0X78); //No global color table. bw.Write(bytes, 0, 13); bw.Write(GifAnimation); WriteGifImg(bytes, bw); for (int idx = 1; idx < jpgFiles.Length; idx++) { ms.SetLength(0); Image.FromFile(jpgFiles[idx]).Save(ms, ImageFormat.Gif); bytes = ms.ToArray(); WriteGifImg(bytes, bw); } bw.Write(bytes[bytes.Length - 1]); } } private static int NumberPart(string fileName) { return Convert.ToInt32(Path.GetFileNameWithoutExtension(fileName).Replace("sf", "")); } private static void WriteGifImg(byte[] bytes, BinaryWriter bw) { bytes[785] = Delay[0]; bytes[786] = Delay[1]; bytes[798] = (byte)(bytes[798] | 0X87); bw.Write(bytes, 781, 18); bw.Write(bytes, 13, 768); bw.Write(bytes, 799, bytes.Length - 800); } } }
using System; namespace LogManager.Models { /// <summary> /// Logs 테이블과 일대일로 매핑되는 모델(뷰 모델, 엔터티) 클래스 /// </summary> public class LogViewModel { /// <summary> /// 일련번호 /// </summary> public int Id { get; set; } /// <summary> /// 비고 /// </summary> public string Note { get; set; } /// <summary> /// 응용 프로그램: 게시판 관리, 상품 관리 /// </summary> public string Application { get; set; } /// <summary> /// 사용자 정보(로그인 사용 아이디) /// </summary> public string Logger { get; set; } /// <summary> /// 로그 이벤트(사용자 정의 이벤트 ID) /// </summary> public string LogEvent { get; set; } /// <summary> /// 로그 메시지 /// </summary> public string Message { get; set; } /// <summary> /// 로그 메시지에 대한 템플릿 /// </summary> public string MessageTemplate { get; set; } /// <summary> /// 로그 레벨(정보, 에러, 경고) /// </summary> public string Level { get; set; } /// <summary> /// 로그 발생 시간(LogCreationDate) /// </summary> public DateTimeOffset TimeStamp { get; set; } /// <summary> /// 예외 메시지 /// </summary> public string Exception { get; set; } /// <summary> /// 기타 여러 속성들을 XML 저장 /// </summary> public string Properties { get; set; } /// <summary> /// 호출사이트 /// </summary> public string Callsite { get; set; } /// <summary> /// IP 주소 /// </summary> public string IpAddress { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Meshop.Framework.Model; using Meshop.Framework.Security; using Meshop.Framework.Services; namespace Meshop.Core.Areas.Admin.Controllers { [Admin] public abstract class AdminController : Controller { protected readonly IAdmin _adminService; protected readonly ICommon _commonService; protected DatabaseConnection2 db = new DatabaseConnection2(); protected AdminController(IAdmin adminsvc,ICommon commonsvc) { _adminService = adminsvc; _commonService = commonsvc; _commonService.TempData = TempData; } protected override void OnActionExecuting(ActionExecutingContext ctx) { base.OnActionExecuting(ctx); ViewBag.Settings = _commonService.Settings; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FootballManager { public class Utils { public static string UPLOAD = "~/Content/uploads"; public static string EncodeFile(string fileName) { return @"data:image/gif;base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName)); } } }
using System; using System.Collections.Generic; using StardewModdingAPI; namespace Entoarox.Framework { public static class IMonitorExtensions { /********* ** Fields *********/ private static readonly HashSet<string> Cache = new HashSet<string>(); /********* ** Public methods *********/ public static void Log(this IMonitor self, string message, LogLevel level = LogLevel.Debug, Exception error = null) { if (error != null) message += Environment.NewLine + error; self.Log(message, level); } public static void LogOnce(this IMonitor self, string message, LogLevel level = LogLevel.Debug, Exception error = null) { if (error != null) message += Environment.NewLine + error; if (IMonitorExtensions.Cache.Add($"{level}:{message}")) self.Log(message, level); } public static void ExitGameImmediately(this IMonitor self, string message, Exception error = null) { if (error != null) message += Environment.NewLine + error; self.ExitGameImmediately(message); } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `FloatPair`. Inherits from `AtomEventReferenceListener&lt;FloatPair, FloatPairEvent, FloatPairEventReference, FloatPairUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/FloatPair Event Reference Listener")] public sealed class FloatPairEventReferenceListener : AtomEventReferenceListener< FloatPair, FloatPairEvent, FloatPairEventReference, FloatPairUnityEvent> { } }
using System; using System.IO; using System.Text.RegularExpressions; namespace Robot.Cli { // PLACE X,Y,F // MOVE // LEFT // RIGHT // REPORT public class TextInterface { readonly TextReader _inputReader; readonly TextWriter _outputWriter; readonly TextWriter _errorWriter; public TextInterface(TextReader inputReader, TextWriter outputWriter, TextWriter errorWriter) { _inputReader = inputReader; _outputWriter = outputWriter; _errorWriter = errorWriter; } public void Run(Robot robot) { while (true) { var line = _inputReader.ReadLine(); if (line is null) { break; } ProcessCommand(line, robot); } } static readonly Regex PlaceRegex = new Regex(@"PLACE (\d+),(\d+),(NORTH|SOUTH|EAST|WEST)$", RegexOptions.IgnoreCase); void ProcessCommand(string rawLine, Robot robot) { var line = rawLine.Trim().ToUpper(); if (line == "MOVE") { robot.Move(); return; } if (line == "LEFT") { robot.Left(); return; } if (line == "RIGHT") { robot.Right(); return; } if (line == "REPORT") { if (robot.Report() is Position position) { _outputWriter.WriteLine(position); } return; } var match = PlaceRegex.Match(line); if (!match.Success) { _errorWriter.WriteLine("Unrecognised command: " + rawLine); return; } var xInput = match.Groups[1].ToString(); var yInput = match.Groups[2].ToString(); var directionInput = match.Groups[3].ToString(); if (!uint.TryParse(xInput, out var x)) { _errorWriter.WriteLine($"Invalid value for X: {xInput}"); return; } if (!uint.TryParse(yInput, out var y)) { _errorWriter.WriteLine($"Invalid value for X: {yInput}"); return; } if (!Enum.TryParse<Direction>(directionInput, ignoreCase:true, out var direction)) { _errorWriter.WriteLine($"Invalid direction: {directionInput}"); return; } robot.Place(new Position(new Coordinate(x, y), direction)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace masodik_feladat { class FileAdatok { string nev; DateTime modositasDatuma; long meret; public string Nev { get => nev; set => nev = value; } public DateTime ModositasDatuma { get => modositasDatuma; set => modositasDatuma = value; } public long Meret { get => meret; set => meret = value; } public FileAdatok(string nev, DateTime modositasDatuma, long meret) { Nev = nev; ModositasDatuma = modositasDatuma; Meret = meret; } public static void Kiiratas(string nev, DateTime modositasDatuma, long meret) { Console.WriteLine(nev + " - " + modositasDatuma + " - " + meret); } public static void CSVFormatumba(string mappanev, DateTime jelenlegiIdo, string nev, DateTime modositasDatuma, long meret) { StreamWriter mentes = new StreamWriter(jelenlegiIdo + "_" + mappanev + ".csv", true); mentes.WriteLine(nev + ';' + modositasDatuma + ';' + meret); mentes.Close(); } } }
/// This code is written by Tijndagamer and released under the MIT license. using System; class Calculator { static void Main() { Console.WriteLine("Welcome, if you need help type help"); do GetAnswer(); while (true); } static void add() { double a, b, c; string string_a, string_b; Console.Write("a ="); string_a = Console.ReadLine(); a = double.Parse(string_a); Console.Write("b ="); string_b = Console.ReadLine(); b = double.Parse(string_b); Console.WriteLine("Your answer is"); c = a + b; Console.WriteLine(c); } static void multiply() { double a, b, c; string string_a, string_b; Console.Write("a ="); string_a = Console.ReadLine(); a = double.Parse(string_a); Console.Write("b ="); string_b = Console.ReadLine(); b = double.Parse(string_b); Console.WriteLine("Your answer is"); c = a * b; Console.WriteLine(c); } static void subtract() { double a, b, c; string string_a, string_b; Console.Write("a ="); string_a = Console.ReadLine(); a = double.Parse(string_a); Console.Write("b ="); string_b = Console.ReadLine(); b = double.Parse(string_b); Console.WriteLine("Your answer is"); c = a - b; Console.WriteLine(c); } static void divide() { double a, b, c; string string_a, string_b; Console.Write("a ="); string_a = Console.ReadLine(); a = double.Parse(string_a); Console.Write("b ="); string_b = Console.ReadLine(); b = double.Parse(string_b); Console.WriteLine("Your answer is"); c = a / b; Console.WriteLine(c); } static void ExitFunction() { string exit_string; Console.WriteLine("Are you sure you want to exit? y/n"); exit_string = Console.ReadLine(); if (exit_string == "y") Environment.Exit(0); } static void HelpFunction() { string help_string; help_string = "These are the available commands: \n add \n multiply \n subtract \n divide \n exit \n help"; Console.WriteLine(help_string); } static void GetAnswer() { string answer; Console.Write(">"); answer = Console.ReadLine(); if (answer == "add") add(); if (answer == "multiply") multiply(); if (answer == "subtract") subtract(); if (answer == "divide") divide(); if (answer == "exit") ExitFunction(); if (answer == "help") HelpFunction(); } }
 using Xamarin.Forms; namespace RRExpress.Express.Views { public partial class PickupView : ContentView { public PickupView() { InitializeComponent(); } } }
using System; using System.Windows.Markup; namespace SqlServerRunnerNet.Infrastructure { public sealed class EnumValues : MarkupExtension { private readonly Type _enumType; public EnumValues(Type enumType) { _enumType = enumType; } public override object ProvideValue(IServiceProvider serviceProvider) { return Enum.GetValues(_enumType); } } }
using DocumentManagement.Common; using Model.DAO; using Model.EF; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DocumentManagement.Areas.Admin.Controllers { public class HomeController : BaseController { // GET: Admin/Home public ActionResult Index() { var documentDAO = new DocumentDAO(); ViewBag.DispatchIssued = documentDAO.TotalDispatchIssued(); ViewBag.DispatchWaitingIssued = documentDAO.TotalDispatchWaitingIssued(); ViewBag.DispatchPending = documentDAO.TotalDispatchPending(); ViewBag.DispatchCanceled = documentDAO.TotalDispatchCanceled(); return View(); } [ChildActionOnly] public ActionResult LeftMenu() { ViewBag.SessionViewBag = Session[CommonConstants.USER_SESSION]; return PartialView(); } [ChildActionOnly] public ActionResult TopMenu() { ViewBag.SessionViewBag = Session[CommonConstants.USER_SESSION]; return PartialView(); } public ActionResult GetData() { var results = new List<SimpleClass>(); var documentDAO = new DocumentDAO(); var documentTypeDAO = new DocumentTypeDAO(); List<DocumentType> listDocumentTypeExisting = documentTypeDAO.ListAll(); foreach (var item in listDocumentTypeExisting) { var check = documentDAO.CountDocumentType(item.ID.ToString()); if (check > 0) { results.Add(new SimpleClass { Key = item.Name.ToString(), Value = documentDAO.CountDocumentType(item.ID.ToString()) }); } } return Json(results, JsonRequestBehavior.AllowGet); } public class SimpleClass { public string Key { get; set; } public int Value { get; set; } } } }
using GufENuffLogInApi.DataAnnotations; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace GufENuffLogInApi.ViewModels { /// <summary> /// A View Model for changing passwords. /// </summary> public class ChangePasswordViewModel { /// <summary> /// The Email of the User Account /// </summary> [Required] public String Email { get; set; } /// <summary> /// The Current / Old Password of the User Account /// </summary> [Required] [Password] public String OldPassword { get; set; } /// <summary> /// The Desired / New Password of the User Account /// </summary> [Required] [Password] public String NewPassword { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class scene_switcher : MonoBehaviour { public void GoToPlayerSelectScene(){ SceneManager.LoadScene("player_select_scene"); } public void GoToMapScene(){ SceneManager.LoadScene("map_scene"); } public void GoToQuizScene(){ SceneManager.LoadScene("quiz_scene"); } public void GoToTitleScene(){ SceneManager.LoadScene("title_scene"); } public void GoToQuit() { Application.Quit(); } // Help Scenes public void GoToHelpScene(){ SceneManager.LoadScene("help_scene_summary"); } public void GoToSummaryScene(){ SceneManager.LoadScene("help_scene_summary"); } public void GoToCreditsScene(){ SceneManager.LoadScene("help_scene_credits"); } public void GoToCharactersScene(){ SceneManager.LoadScene("help_scene_characters_tsundere"); } public void GoToTsundereScene(){ SceneManager.LoadScene("help_scene_characters_tsundere"); } public void GoToLoveleeScene(){ SceneManager.LoadScene("help_scene_characters_lovelee"); } public void GoToReginaScene(){ SceneManager.LoadScene("help_scene_characters_regina"); } public void GoToTomScene(){ SceneManager.LoadScene("help_scene_characters_tom"); } public void GoToVanityScene(){ SceneManager.LoadScene("help_scene_characters_vanity"); } public void GoToWolfieScene(){ SceneManager.LoadScene("help_scene_characters_wolfie"); } //public void GoTo // Game Scenes public void GoToGameScene(){ SceneManager.LoadScene("game_scene"); } public void GoToBedroomScene(){ SceneManager.LoadScene("game_scene_bedroom"); } public void GoToCryptScene(){ SceneManager.LoadScene("game_scene_crypts"); } public void GoToGrandHall(){ SceneManager.LoadScene("game_scene_grand_hall"); } public void GoToGraveyard(){ SceneManager.LoadScene("game_scene_graveyard"); } public void GoToKitchen(){ SceneManager.LoadScene("game_scene_kitchen"); } public void GoToStudy(){ SceneManager.LoadScene("game_scene_study"); } }
using GalaSoft.MvvmLight.Command; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Windows.Input; using VesApp.Models; using VesApp.Services; using Xamarin.Forms; namespace VesApp.ViewModels { public class PublicationViewModel:BaseViewModel { #region Services private ApiService apiService; #endregion #region Attributes private ObservableCollection<Reflexion> reflexions; private ObservableCollection<Predication> predications; private ObservableCollection<Project> projects; private ObservableCollection<Event> events; private bool isRefreshing; #endregion #region Properties public ObservableCollection<Reflexion> Reflexions { get { return this.reflexions; } set { SetValue(ref this.reflexions, value); } } public ObservableCollection<Predication> Predications { get { return this.predications; } set { SetValue(ref this.predications, value); } } public ObservableCollection<Project> Projects { get { return this.projects; } set { SetValue(ref this.projects, value); } } public ObservableCollection<Event> Events { get { return this.events; } set { SetValue(ref this.events, value); } } public bool IsRefreshing { get { return this.isRefreshing; } set { SetValue(ref this.isRefreshing, value); } } #endregion #region Constructors public PublicationViewModel() { this.apiService = new ApiService(); this.LoadReflexions(); } #endregion #region Methods public async void LoadReflexions() { if (Reflexions == null) { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Reflexion>( "http://vesappapi.azurewebsites.net", "/api", "/Reflexions"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Reflexion>)response.Result; this.Reflexions = new ObservableCollection<Reflexion>(list); this.IsRefreshing = false; } } public async void LoadPredications() { if (Predications == null) { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Predication>( "http://vesappapi.azurewebsites.net", "/api", "/Predications"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Predication>)response.Result; this.Predications = new ObservableCollection<Predication>(list); this.IsRefreshing = false; } } public async void LoadProjects() { if (Projects == null) { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Project>( "http://vesappapi.azurewebsites.net", "/api", "/Projects"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Project>)response.Result; this.Projects = new ObservableCollection<Project>(list); this.IsRefreshing = false; } } public async void LoadEvents() { if (Events == null) { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Event>( "http://vesappapi.azurewebsites.net", "/api", "/Events"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Event>)response.Result; this.Events = new ObservableCollection<Event>(list); this.IsRefreshing = false; } } public async void LoadRefreshReflexions() { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Reflexion>( "http://vesappapi.azurewebsites.net", "/api", "/Reflexions"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error",response.Message,"Aceptar"); return; } var list = (List<Reflexion>)response.Result; this.Reflexions = new ObservableCollection<Reflexion>(list); this.IsRefreshing = false; } public async void LoadRefreshPredications() { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Predication>( "http://vesappapi.azurewebsites.net", "/api", "/Predications"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Predication>)response.Result; this.Predications = new ObservableCollection<Predication>(list); this.IsRefreshing = false; } public async void LoadRefreshProjects() { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Project>( "http://vesappapi.azurewebsites.net", "/api", "/Projects"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Project>)response.Result; this.Projects = new ObservableCollection<Project>(list); this.IsRefreshing = false; } public async void LoadRefreshEvents() { this.IsRefreshing = true; var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", connection.Message, "Aceptar"); return; } var response = await this.apiService.GetList<Event>( "http://vesappapi.azurewebsites.net", "/api", "/Events"); if (!response.IsSuccess) { this.IsRefreshing = false; await App.Current.MainPage.DisplayAlert("Error", response.Message, "Aceptar"); return; } var list = (List<Event>)response.Result; this.Events = new ObservableCollection<Event>(list); this.IsRefreshing = false; } #endregion #region Commands public ICommand RefreshReflexionsCommand { get { return new RelayCommand(LoadRefreshReflexions); } } public ICommand RefreshPredicationsCommand { get { return new RelayCommand(LoadRefreshPredications); } } public ICommand RefreshProjectsCommand { get { return new RelayCommand(LoadRefreshProjects); } } public ICommand RefreshEventsCommand { get { return new RelayCommand(LoadRefreshEvents); } } #endregion } }
using System.Collections.Generic; namespace TransactionRegistry.Core { using System.Collections.Concurrent; using TransactionRegistry.Core.Models; public class Data { public ConcurrentDictionary<string, ServiceState> Key; public SortedSet<ServiceState> List; } }
using System; using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class PivotGridController: DemoController { public ActionResult Templates() { return DemoView("Templates", NorthwindDataProvider.GetProductReports()); } public ActionResult TemplatesPartial() { return PartialView("TemplatesPartial", NorthwindDataProvider.GetProductReports()); } } }
using MediatR; using AspNetCoreGettingStarted.Data; using AspNetCoreGettingStarted.Features.Core; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using Microsoft.EntityFrameworkCore; using System.Threading; namespace AspNetCoreGettingStarted.Features.Dashboards { public class GetDashboardsQuery { public class Request : BaseRequest, IRequest<Response> { } public class Response { public ICollection<DashboardApiModel> Dashboards { get; set; } = new HashSet<DashboardApiModel>(); } public class Handler : IRequestHandler<Request, Response> { public Handler(IAspNetCoreGettingStartedContext context, ICache cache) { _context = context; _cache = cache; } public async Task<Response> Handle(Request request, CancellationToken cancellationToken) { var dashboards = await _context.Dashboards .Include(x => x.Tenant) .Where(x => x.Tenant.TenantId == request.TenantId ) .ToListAsync(); return new Response() { Dashboards = dashboards.Select(x => DashboardApiModel.FromDashboard(x)).ToList() }; } private readonly IAspNetCoreGettingStartedContext _context; private readonly ICache _cache; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InstituteOfFineArts.Models { public class CompetitionPost { public int ID { get; set; } [Required] public int CompetitionID { get; set; } public Competition Competition { get; set; } [Required] public int PostID { get; set; } public Post Post { get; set; } [Required] [Display(Name = "Post Point")] public int PostPoint { get; set; } [Required] [Display(Name = "Author")] public string UserID { get; set; } [Required] [Display(Name = "Submit Date")] public DateTime SubmitDate { get; set; } public string StaffSubmit { get; set; } public string StudentSubmit { get; set; } public bool Available { get; set; } public DateTime DeletedAt { get; set; } } }
using UnityEngine; using System.Collections; public class CameraFollowScript : MonoBehaviour { [SerializeField] private float distanceAway; [SerializeField] private float distanceUp; [SerializeField] private float smooth; [SerializeField] private Transform follow; private Vector3 targetPosition; // Use this for initialization void Start () { follow = GameObject.FindWithTag ("Brute").transform; } // Update is called once per frame void Update () { } void LateUpdate() { targetPosition = follow.position + Vector3.up * distanceUp - follow.forward * distanceAway; transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * smooth); transform.LookAt (follow); } }
using LibraryCoder.UtilitiesMisc; using System; using Windows.UI.Xaml.Controls; /* * This sample runs various code snipplets initializing, using, and validating enumerations. * * * This bit of code was thowing me for a loop since could not convert a enum into a system base Enum without compiler error!!!! * * Big revelation was to cast the enum using "newEnum = oldEnum as Enum". * * Seems simple but would not convert any other way!!! Days spent searching for this small discovery. * * Note: Keyword 'as' always returns null on fault versus an exception, therefor always check if not null * immediately after using the 'as' keyword before proceeding. * * newEnum = oldEnum as Enum; // Compiler would not convert this without using 'as' keyword!!! * if (getEnum != null) * { * ........ * } * * Also note that comparing one enum to another with the '==' operator may not show a match. * * Use Equals operator to compare two enums. * * if (item.conversion.Equals(currentType.saveEnumInput)) * { * ........ * } * */ namespace SampleUWP.ConsoleCodeSamples { internal partial class Samples { enum ArrivalStatus { Unknown = -3, Late = -1, OnTime = 0, Early = 1 }; enum Color { Red = 1, Blue = 2, Green = 3 } [Flags] enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 }; // DescriptionAttribute is not available for UWP apps. So con not use with Enums! Two alternatives shown here: // http://stackoverflow.com/questions/18912697/system-componentmodel-descriptionattribute-in-portable-class-library // // Various methods to use the attributes here: http://stackoverflow.com/questions/4367723/get-enum-from-description-attribute //public enum InstallationType {[Display(Description = "Forward of Bulk Head")] FORWARD, [Display(Description = "Rear of Bulk Head")] REAR, [Display(Description = "Roof Mounted")] ROOF} //enum Animal //{ // [Display(Description = "")] // NotSet = 0, // [Display(Description = "Giant Panda")] // GiantPanda = 1, // [Display(Description = "Lesser Spotted Anteater")] // LesserSpottedAnteater = 2 //} /***** Use .Net code above versus building enumeration description handling from scratch since this works with UWP apps. *****/ // For more information: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute(v=vs.110).aspx // Sample code not used or tested but SAVE for future use. VS not thowing any errors. // // Build your own DescriptionAttribute..... // //[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] //public class EnumDescriptionAttribute : Attribute //{ // private readonly string description; // public string Description { get { return description; } } // public EnumDescriptionAttribute(string description) // { // this.description = description; // } //} // Sample code not used or tested but SAVE for future use. VS not thowing any errors. // //enum Foo {[EnumDescription("abc")] A, [EnumDescription("def")] B } // Sample code not used or tested but SAVE for future use. VS not thowing any errors. // //enum UserColours //{ // [EnumDescription("Burnt Orange")] // BurntOrange = 1, // [EnumDescription("Bright Pink")] // BrightPink = 2, // [EnumDescription("Dark Green")] // DarkGreen = 3, // [EnumDescription("Sky Blue")] // SkyBlue = 4 //} // Sample code not used or tested but SAVE for future use. VS not thowing any errors. // //public static string GetEnumDescriptionFromEnumValue(Enum value) //{ // EnumDescriptionAttribute attribute = value.GetType() // .GetField(value.ToString()) // .GetCustomAttributes(typeof(EnumDescriptionAttribute), false) // .SingleOrDefault() as EnumDescriptionAttribute; // return attribute == null ? value.ToString() : attribute.Description; //} ///* // * Sample code not used or tested but SAVE for future use. // * // * This is not working... // * //public static T GetEnumValueFromDescription<T>(string description) //{ // var type = typeof(T); // if (!type.IsEnum) // throw new ArgumentException(); // FieldInfo[] fields = type.GetFields(); // var field = fields // .SelectMany(f => f.GetCustomAttributes( // typeof(DisplayAttribute), false), ( // f, a) => new { Field = f, Att = a }) // .Where(a => ((DisplayAttribute)a.Att) // .Description == description).SingleOrDefault(); // return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); //} //*/ ///* // * Sample code not used or tested but SAVE for future use. // * // * //public static string GetDescriptionFromEnumValueOriginal(Enum value) //{ // DescriptionAttribute attribute = value.GetType() // .GetField(value.ToString()) // .GetCustomAttributes(typeof(DescriptionAttribute), false) // .SingleOrDefault() as DescriptionAttribute; // return attribute == null ? value.ToString() : attribute.Description; //} //public static T GetEnumValueFromDescriptionOriginal<T>(string description) //{ // var type = typeof(T); // if (!type.IsEnum) // throw new ArgumentException(); // FieldInfo[] fields = type.GetFields(); // var field = fields // .SelectMany(f => f.GetCustomAttributes( // typeof(DescriptionAttribute), false), ( // f, a) => new { Field = f, Att = a }) // .Where(a => ((DescriptionAttribute)a.Att) // .Description == description).SingleOrDefault(); // return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); //} //*/ internal static void Sample09_Enum_Code_Sampler(TextBlock outputBlock) { outputBlock.Text = "\nSample09_Enum_Code_Sampler:\n"; outputBlock.Text += "\nThis sample runs various code snipplets initializing, using, and validating enumerations.\n"; outputBlock.Text += "\nExample01: Check if integer is valid member of an enum: \nCode from: https://msdn.microsoft.com/en-us/library/system.enum.aspx \n"; int[] values = { -3, -1, 0, 1, 5, int.MaxValue }; ArrivalStatus status; foreach (int value in values) { if (Enum.IsDefined(typeof(ArrivalStatus), value)) // Check if int is members of enum. status = (ArrivalStatus)value; // Cast int to enum. else status = ArrivalStatus.Unknown; // Not member of enum so cast to 'Unknown'. outputBlock.Text += string.Format("\nConverted {0:N0} to {1}", value, status); } // Displays the following output: // Converted -3 to Unknown // Converted -1 to Late // Converted 0 to OnTime // Converted 1 to Early // Converted 5 to Unknown // Converted 2,147,483,647 to Unknown status = ArrivalStatus.Early; var aNumber = (int)Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus))); outputBlock.Text += string.Format("\nConverted {0} to {1}\n", status, aNumber); // Displays the following output: // Converted Early to 1 outputBlock.Text += "\nExample02: Parse, TryParse, Enum.IsDefined methods: \nCode from: https://msdn.microsoft.com/en-us/library/system.enum.aspx \n"; // Note that the parsing methods will successfully convert string representations of numbers that are not members // of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. // To prevent this, the IsDefined method can be called to ensure that the result of the parsing method is a valid // enumeration value. string numberString = "-1"; string name = "Early"; ArrivalStatus status1; try { status1 = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), numberString); if (!(Enum.IsDefined(typeof(ArrivalStatus), status1))) // Validate if converted value is member of enum. status1 = ArrivalStatus.Unknown; outputBlock.Text += string.Format("\nConverted '{0}' to {1}", numberString, status1); } catch (FormatException) // Parse throws exception if it could not make conversion. { outputBlock.Text += string.Format("\nUnable to convert '{0}' to an ArrivalStatus value.", numberString); } // equivalent TryParse sample. if (Enum.TryParse<ArrivalStatus>(name, out ArrivalStatus status2)) // Generic with T = enum. { if (!(Enum.IsDefined(typeof(ArrivalStatus), status2))) // Validate if converted value is member of enum. status2 = ArrivalStatus.Unknown; outputBlock.Text += string.Format("\nConverted '{0}' to {1}", name, status2); } else { outputBlock.Text += string.Format("\nUnable to convert '{0}' to an ArrivalStatus value.", numberString); } // Displays the following output: // Converted '-1' to Late // Converted 'Early' to Early // outputBlock.Text += "\n\nExample03: Format enumeration values: \nCode from: https://msdn.microsoft.com/en-us/library/c3s1ez6e.aspx \n"; // Format enumeration values: string[] formats = { "G", "F", "D", "X" }; status = ArrivalStatus.Late; foreach (var fmt in formats) outputBlock.Text += string.Format("\n" + status.ToString(fmt)); // Displays the following output: // Late // Late // -1 // FFFFFFFF Color myColor = Color.Green; outputBlock.Text += string.Format("\nThe value of myColor is {0}.", myColor.ToString("G")); outputBlock.Text += string.Format("\nThe value of myColor is {0}.", myColor.ToString("F")); outputBlock.Text += string.Format("\nThe value of myColor is {0}.", myColor.ToString("D")); outputBlock.Text += string.Format("\nThe value of myColor is 0x{0}.\n", myColor.ToString("X")); // Displays the following output to the console: // The value of myColor is Green. // The value of myColor is Green. // The value of myColor is 3. // The value of myColor is 0x00000003. outputBlock.Text += "\nExample04: Iterating enumeration members: \nCode from: https://msdn.microsoft.com/en-us/library/system.enum.aspx \n"; // Iterating enumeration members: You can enumerate members in either of two ways. // GetNames Method: string[] names = Enum.GetNames(typeof(ArrivalStatus)); // Get an arrary of name values from a enum. Array.Sort(names); outputBlock.Text += string.Format("\nGetNames Method: Sorted members of {0}:", typeof(ArrivalStatus).Name); foreach (string item in names) // Iterate the array of names. { status = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), item); // Convert the name back into enum. outputBlock.Text += string.Format("\n {0} ({0:D})", status); } // Displays the following output: // Members of ArrivalStatus: // Early (1) // Late (-1) // OnTime (0) // Unknown (-3 // // GetValues Method var enumValues = Enum.GetValues(typeof(ArrivalStatus)); // Can't really replace 'var' with a type since it is 'Array'. outputBlock.Text += string.Format("\n\nGetValues Method: Unsorted members of {0}:", typeof(ArrivalStatus).Name); foreach (var item in enumValues) { status = (ArrivalStatus)Enum.ToObject(typeof(ArrivalStatus), item); outputBlock.Text += string.Format("\n {0} ({0:D})", status); } // The example displays the following output: // Members of ArrivalStatus: // OnTime (0) // Early (1) // Unknown (-3) // Late (-1) /* * * * Big deal here!!!!!!! * * */ outputBlock.Text += "\nExample05: Iterating enumeration members directly!:"; // Apparently can iterate enumerations directly contrary to what is said above. Which is more efficeint depends on what compiler is doing. // // Basically, all that was done here was to eliminate the 'var' variable 'enumValues' and move code directly to the 'foreach' loop. // outputBlock.Text += string.Format("\n\nDirect iterating method: Members of {0}:", typeof(ArrivalStatus).Name); foreach (ArrivalStatus item in Enum.GetValues(typeof(ArrivalStatus))) { outputBlock.Text += string.Format("\n {0} ({0:D})", item); } outputBlock.Text += "\n\nExample06: Nice TyParse sample: \nCode from: https://msdn.microsoft.com/en-us/library/dd991317.aspx \n"; string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; // Note last string item... foreach (string colorString in colorStrings) { if (Enum.TryParse(colorString, true, out Colors colorValue)) if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(",")) outputBlock.Text += string.Format("\nConverted '{0}' to {1}.", colorString, colorValue.ToString()); else outputBlock.Text += string.Format("\n{0} is not an underlying value of the Colors enumeration.", colorString); else outputBlock.Text += string.Format("\n{0} is not a member of the Colors enumeration.", colorString); } // The example displays the following output: // Converted '0' to None. // Converted '2' to Green. // 8 is not an underlying value of the Colors enumeration. // Converted 'blue' to Blue. // Converted 'Blue' to Blue. // Yellow is not a member of the Colors enumeration. // Converted 'Red, Green' to Red, Green. outputBlock.Text += "\n\nExample07: Enum Descrption attribute sample using DisplayAtrribute: "; //outputBlock.Text += "\n" + LibUM.EnumShowValues<Animal>(); //outputBlock.Text += "\n" + LibUM.EnumShowValues<InstallationType>(true); //outputBlock.Text += "\n" + LibUM.EnumShowValues<ConversionType>(); //outputBlock.Text += "\n" + LibUM.EnumShowValues<Angle>(true); outputBlock.Text += "\n\nExample08: Off subject of Enum's but need to test LibUM.ReverseString() \nmethod using strings with control characters.\n"; // Test LibUM.ReverseString() methods. Seems to be picking up '\n' characters correctly. //outputBlock.Text += "\n" + LibUM.ReverseString(LibUM.EnumShowValues<Angle>(true)); string string1 = "\nUnicode in C#: Hamburger=\uE700, Home=\uE80F, Back=\uE72B, Forward=\uE72A, Page=\uE7C3"; string string2 = "\nUnicode in XAML: \nHamburger = &#xE700, \nHome=&#xE80F, \nBack=&#xE72B, \nForward=&#xE72A, \nPage=&#xE7C3"; outputBlock.Text += string1; outputBlock.Text += "\n\nReversed string above:\n" + LibUM.ReverseString(string1); outputBlock.Text += string2; outputBlock.Text += "\n\nReversed string above:\n " + LibUM.ReverseString(string2); outputBlock.Text += "\n\n"; // Finish up with a couple of LF's. } } }
using BetterRNG.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; namespace BetterRNG { /// <summary>The main entry point.</summary> public class ModEntry : Mod { /********* ** Properties *********/ /// <summary>The mod configuration.</summary> private ModConfig Config; private float[] RandomFloats; private WeightedGeneric<int>[] Weather; /********* ** Accessors *********/ internal static MersenneTwister Twister { get; private set; } /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { // read config this.Config = helper.ReadConfig<ModConfig>(); // init randomness Game1.random = ModEntry.Twister = new MersenneTwister(); this.RandomFloats = new float[256]; this.RandomFloats.FillFloats(); // fill buffer with junk so everything is good and random this.Weather = new[] { WeightedGeneric<int>.Create(this.Config.SunnyChance, Game1.weather_sunny), WeightedGeneric<int>.Create(this.Config.CloudySnowyChance, Game1.weather_debris), WeightedGeneric<int>.Create(this.Config.RainyChance, Game1.weather_rain), WeightedGeneric<int>.Create(this.Config.StormyChance, Game1.weather_lightning), WeightedGeneric<int>.Create(this.Config.HarshSnowyChance, Game1.weather_snow) }; this.DetermineRng(); /* //Debugging for my randoms while (true) { List<int> got = new List<int>(); int v = 0; int gen = 1024; float genf = gen; for (int i = 0; i < gen; i++) { v = Weighted.ChooseRange(OneToTen, 1, 5).TValue; got.Add(v); if (gen <= 1024) Console.Write(v + ", "); } Console.Write("\n"); Console.WriteLine("Generated {0} Randoms", got.Count); Console.WriteLine("1: {0} | 2: {1} | 3: {2} | 4: {3} | 5: {4} | 6: {5} | 7: {6} | 8: {7} | 9: {8} | 10: {9} | ?: {10}", got.Count(x => x == 1), got.Count(x => x == 2), got.Count(x => x == 3), got.Count(x => x == 4), got.Count(x => x == 5), got.Count(x => x == 6), got.Count(x => x == 7), got.Count(x => x == 8), got.Count(x => x == 9), got.Count(x => x == 10), got.Count(x => x > 10)); Console.WriteLine("{0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} | {8} | {9}", got.Count(x => x == 1) / genf * 100 + "%", got.Count(x => x == 2) / genf * 100 + "%", got.Count(x => x == 3) / genf * 100 + "%", got.Count(x => x == 4) / genf * 100 + "%", got.Count(x => x == 5) / genf * 100 + "%", got.Count(x => x == 6) / genf * 100 + "%", got.Count(x => x == 7) / genf * 100 + "%", got.Count(x => x == 8) / genf * 100 + "%", got.Count(x => x == 9) / genf * 100 + "%", got.Count(x => x == 10) / genf * 100 + "%"); //Console.WriteLine(OneToTen.ChooseRange(0, 10).TValue); Console.ReadKey(); } */ // hook events helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded; helper.Events.Input.ButtonPressed += this.OnButtonPressed; this.Monitor.Log("Initialized (press F5 to reload config)"); } /********* ** Private methods *********/ /// <summary>Raised after the player loads a save slot and the world is initialised.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnSaveLoaded(object sender, SaveLoadedEventArgs e) { this.DetermineRng(); } /// <summary>Raised after the player presses a button on the keyboard, controller, or mouse.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { if (e.Button == SButton.F5) { this.Config = this.Helper.ReadConfig<ModConfig>(); this.Monitor.Log("Config reloaded", LogLevel.Info); } } private void DetermineRng() { //0 = SUNNY, 1 = RAIN, 2 = CLOUDY/SNOWY, 3 = THUNDER STORM, 4 = FESTIVAL/EVENT/SUNNY, 5 = SNOW //Generate a good set of new random numbers to choose from for daily luck every morning. this.RandomFloats.FillFloats(); if (this.Config.EnableDailyLuckOverride) Game1.dailyLuck = RandomFloats.Random() / 10; if (this.Config.EnableWeatherOverride) { int targetWeather = this.Weather.Choose().TValue; if (targetWeather == Game1.weather_snow && Game1.currentSeason != "winter") targetWeather = Game1.weather_lightning; if (targetWeather == Game1.weather_rain && Game1.currentSeason == "winter") targetWeather = Game1.weather_debris; if (targetWeather == Game1.weather_lightning && Game1.currentSeason == "winter") targetWeather = Game1.weather_snow; if (targetWeather == Game1.weather_festival) targetWeather = Game1.weather_sunny; Game1.weatherForTomorrow = targetWeather; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Car : Obstacles { [SerializeField] private bool m_canMove = false; private float m_speed = 10; public override void HitPlayer(Vector3 pos) { base.HitPlayer(pos); } public override void OnSpawn() { } public override void OnUnSpawn() { StopAllCoroutines(); } public void HitTrigger() { if (m_canMove) StartCoroutine(MoveCar()); } IEnumerator MoveCar() { while (true) { if (!Game.M_Instance.M_GM.M_IsPause && Game.M_Instance.M_GM.M_IsPlay) { transform.Translate(-transform.forward * m_speed * Time.deltaTime); } yield return null; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using WebQz.Models; namespace WebQz.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly Service.IQuestionsService _questionService; private static Game game = new(); public HomeController(ILogger<HomeController> logger, Service.IQuestionsService questionService) { _logger = logger; _questionService = questionService; } public IActionResult Index(string title, string start, int maxSteps) { game.question = "Готовы начать игру?"; _questionService.StartStopGame(game, title, start); if (start == "Старт" || title != null) { if (start == "Старт" || title.Contains("Answer")) { try { if (_questionService.GameProcess(game, title, maxSteps) != false) NextQuestion(); } catch (Exception) { game._score = 0; NextQuestion(); game.maxSteps = maxSteps - 1; } } } return View(game); } public void NextQuestion() { try { game.question = _questionService.GetQuestions().ElementAt(game._minStep).TextQ; _questionService.SetRandomTitle(_questionService.GetRandomTitle().OrderBy(i => new Random().Next()).ToList()); ViewData[_questionService.GetRandomTitle()[0]] = _questionService.GetQuestions().ElementAt(game._minStep).Answer1; ViewData[_questionService.GetRandomTitle()[1]] = _questionService.GetQuestions().ElementAt(game._minStep).Answer2; ViewData[_questionService.GetRandomTitle()[2]] = _questionService.GetQuestions().ElementAt(game._minStep).Answer3; ViewData[_questionService.GetRandomTitle()[3]] = _questionService.GetQuestions().ElementAt(game._minStep).Answer4; List<string> questionsValue = new() { _questionService.GetQuestions().ElementAt(game._minStep).Answer1, _questionService.GetQuestions().ElementAt(game._minStep).Answer2, _questionService.GetQuestions().ElementAt(game._minStep).Answer3, _questionService.GetQuestions().ElementAt(game._minStep).Answer4 }; _questionService.SetQuestionValue(questionsValue); game._rightAnswer = _questionService.GetQuestions().ElementAt(game._minStep).RightAnswer; } catch (Exception) { } } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
// <copyright file="FourthTask.cs" company="MyCompany.com"> // Contains the solutions to tasks of the 'Basic Coding in C#' module. // </copyright> // <author>Daryn Akhmetov</author> namespace Basic_coding_in_CSharp { using System.Linq; /// <summary> /// Contains implementation of the given by the task algorithm. /// </summary> public class FourthTask { /// <summary> /// Concatenates two strings, excluding duplicate characters. /// </summary> /// <param name="latinAlphabetString1">The first string that include only characters from 'a' to 'z'</param> /// <param name="latinAlphabetString2">The second string that include only characters from 'a' to 'z'</param> /// <returns>A concatenated string, excluding duplicate characters.</returns> public static string ConcatenateExcludingDuplicateCharacters(string latinAlphabetString1, string latinAlphabetString2) { return latinAlphabetString2.Where(character => !latinAlphabetString1.Contains(character)) .Aggregate(latinAlphabetString1, (current, character) => current + character); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SecurityPlusCore { public class BaseSettings<T> { protected string settingsPath; public BaseSettings(string settingsPath) { if (null == settingsPath) { throw new ArgumentNullException(nameof(settingsPath)); } if (string.IsNullOrWhiteSpace(settingsPath)) { throw new ArgumentException("Settings path cannot be empty", nameof(settingsPath)); } this.settingsPath = settingsPath; } public virtual T LoadSettings() { return XmlHelper.Deserialize<T>(File.ReadAllText(this.settingsPath)); } public virtual void SaveSettings(T settings) { if(null == settings) { throw new ArgumentNullException(nameof(settings)); } File.WriteAllText(this.settingsPath, XmlHelper.Serialize(settings)); } } }
/** * Copyright 2019 Oskar Sigvardsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace GK { public class ConvexHullTest : MonoBehaviour { public GameObject RockPrefab; IEnumerator Start() { var calc = new ConvexHullCalculator(); var verts = new List<Vector3>(); var tris = new List<int>(); var normals = new List<Vector3>(); var points = new List<Vector3>(); while(true) { points.Clear(); for (int i = 0; i < 200; i++) { points.Add(Random.insideUnitSphere); } //calc.GenerateHull(points, true, ref verts, ref tris, ref normals); var rock = Instantiate(RockPrefab); rock.transform.SetParent(transform, false); rock.transform.localPosition = Vector3.zero; rock.transform.localRotation = Quaternion.identity; rock.transform.localScale = Vector3.one; var mesh = new Mesh(); mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); mesh.SetNormals(normals); rock.GetComponent<MeshFilter>().sharedMesh = mesh; rock.GetComponent<MeshCollider>().sharedMesh = mesh; yield return new WaitForSeconds(0.5f); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace Hakaima { public class Bonus { public enum Type { None, Bonus0, Bonus1, Bonus2, Bonus3, Bonus4, Bonus5, Bonus6, } public const float SIZE = Data.SIZE_CHIP; public const int LAYER = Data.LAYER_5; public Type type { get; private set; } public float positionX { get; private set; } public float positionY { get; private set; } public int layer { get; private set; } public bool visible { get; private set; } public Color color { get; private set; } public int pointX { get; private set; } public int pointY { get; private set; } public float size { get; private set; } public bool blind { get; private set; } public float blindTime { get; private set; } public void Init (Type type, int pointX, int pointY) { this.type = type; this.pointX = pointX; this.pointY = pointY; this.size = SIZE; this.positionX = this.size * this.pointX; this.positionY = this.size * this.pointY; this.layer = LAYER; this.visible = true; this.color = Color.white; } public void Move (float deltaTime, int frameRate) { if (blind) { Color color = Color.white; color.a = ((int)(this.blindTime * 2) % 2 == 0) ? 1 : 0; this.color = color; this.blindTime += deltaTime * 2f; } else { Color color = Color.white; color.a = 1; this.color = color; } } public void SetBlind (bool blind) { this.blind = blind; this.blindTime = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Caapora { public interface IAutoMovable { void moveRight(); void moveLeft(); void moveUp(); void moveDown(); } }
using System.ComponentModel.DataAnnotations; using System.Threading; using System.Threading.Tasks; using Justa.Job.Backend.Api.Application.MediatR.Requests; using Justa.Job.Backend.Api.Identity.Models; using MediatR; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace Justa.Job.Backend.Api.Application.MediatR.Handlers { public class QueryUserByUserNameHandler : ActionResultRequestHandler<QueryUserByUserName> { private readonly UserManager<ApplicationUser> _userManager; public QueryUserByUserNameHandler(UserManager<ApplicationUser> userManager) { _userManager = userManager; } public override async Task<IActionResult> Handle(QueryUserByUserName request, CancellationToken cancellationToken) { var applicationUser = await _userManager.FindByNameAsync(request.UserName); if (applicationUser is null) { return NotFound(); } var user = new { applicationUser.Id, applicationUser.UserName, applicationUser.NormalizedUserName, applicationUser.Email, applicationUser.NormalizedEmail, applicationUser.EmailConfirmed, applicationUser.PhoneNumber }; return Ok(user); } } }
using ISE.Framework.Common.CommonBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ISE.SM.Common.DTO { public partial class PermissionToUserConstraintDto:BaseDto { public PermissionToUserConstraintDto() { this.PrimaryKeyName = "PuConstraintId"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectMaker : MonoBehaviour { [SerializeField] private Transform objectParent; [SerializeField] private SparkEffect sparkPrefab; [SerializeField] private DropItem dropItemPrefab; private ObjectPool<SparkEffect> sparkPool; private ObjectPool<DropItem> dropItemPool; private void Awake() { MakePool(); } private void MakePool() { sparkPool = new ObjectPool<SparkEffect>(sparkPrefab, 5, objectParent); dropItemPool = new ObjectPool<DropItem>(dropItemPrefab, 3, objectParent); } public SparkEffect GetSparkEffect() { if (sparkPool == null) return null; return sparkPool.GetItem(); } public void SpawnDropItem(DropItemType dropItemType,Transform targetPlatform,RGBType rgbType= RGBType.End) { if (dropItemPool == null) return; DropItem item = dropItemPool.GetItem(); if (item != null) { item.Initialize(targetPlatform, dropItemType, rgbType); } #if UNITY_EDITOR Debug.Log("DropItem생성"); #endif } }
using Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Repository { public class EmployeeCommandRepository { public void SaveEmployee(Employees emp) { DbClass.ExecuteNonQuery("InsertEmployeeData", System.Data.CommandType.StoredProcedure, new SqlParameter("@EmployeeName", emp.EmployeeName), new SqlParameter("@Deparmtent", emp.Department), new SqlParameter("@EmployeeTypeId", emp.EmployeeTypeId), new SqlParameter("@HourlyPay", emp.HourlyPay), new SqlParameter("@Bonusinc", emp.Bonusinc) ); } public void UpdateEmployee(Employees emp) { DbClass.ExecuteNonQuery("InsertEmployeeData", System.Data.CommandType.StoredProcedure, new SqlParameter("@EmployeeId", emp.EmployeeId), new SqlParameter("@EmployeeName", emp.EmployeeName), new SqlParameter("@Deparmtent", emp.Department), new SqlParameter("@EmployeeTypeId", emp.EmployeeTypeId), new SqlParameter("@HourlyPay", emp.HourlyPay), new SqlParameter("@Bonusinc", emp.Bonusinc) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.SSO { /// <summary> /// 角色信息 /// </summary> public class RoleInfo { public int RoleID { get; set; } public string RoleCode { get; set; } public int RoleLeaf { get; set; } public string RoleName { get; set; } public override string ToString() { return RoleName; } public RoleInfo Clone() { return MemberwiseClone() as RoleInfo; } } }
using Cs_Gerencial.Aplicacao.Interfaces; using Cs_Gerencial.Dominio.Entities; using Cs_Notas.Aplicacao.Interfaces; using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Cs_Notas.Windows { /// <summary> /// Interaction logic for SerieSeloAtual.xaml /// </summary> public partial class SerieSeloAtual : Window { private readonly IAppServicoSelos _AppServicoSelos = BootStrap.Container.GetInstance<IAppServicoSelos>(); private readonly IAppServicoSeries _AppServicoSeries = BootStrap.Container.GetInstance<IAppServicoSeries>(); private readonly IAppServicoConfiguracoes _AppServicoConfiguracoes = BootStrap.Container.GetInstance<IAppServicoConfiguracoes>(); private readonly Cs_Notas.Aplicacao.Interfaces.IAppServicoLogSistema _AppServicoLogSistema = BootStrap.Container.GetInstance<Cs_Notas.Aplicacao.Interfaces.IAppServicoLogSistema>(); Series serieAtual; List<Series> listSeriesDisponiveis = new List<Series>(); List<Series> listSeriesIndisponiveis = new List<Series>(); List<Selos> listSelos = new List<Selos>(); List<Series> listSeries = new List<Series>(); Cs_Notas.Dominio.Entities.Usuario _usuario; List<Selos> listSelosDisponiveisSerieSelecionada = new List<Selos>(); int serieAtualId; Cs_Notas.Dominio.Entities.LogSistema logSistema; public SerieSeloAtual(Cs_Notas.Dominio.Entities.Usuario usuario ) { _usuario = usuario; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { try { serieAtualId = _AppServicoConfiguracoes.GetById(1).SerieAtual; CarregaDataGridSeriesDisponiveis(); serieAtual = listSeriesDisponiveis.Where(p => p.SerieId == serieAtualId).FirstOrDefault(); dataGridSeriesDisponiveis.SelectedItem = serieAtual; dataGridSeriesDisponiveis.ScrollIntoView(serieAtual); SalvarLogSistema("Entrou na Tela de Alterar Série do Selo"); } catch (Exception) { } } private void CarregaDataGridSeriesDisponiveis() { listSelos = _AppServicoSelos.ConsultarPorStatusLivre().ToList(); listSeries = _AppServicoSeries.GetAll().ToList(); List<int> listIdsSeriesDisponiveis = listSelos.Select(p => p.IdSerie).Distinct().ToList(); Series serie; for (int i = 0; i < listIdsSeriesDisponiveis.Count; i++) { serie = listSeries.Where(p => p.SerieId == listIdsSeriesDisponiveis[i]).FirstOrDefault(); listSeriesDisponiveis.Add(serie); } serie = null; dataGridSeriesDisponiveis.ItemsSource = listSeriesDisponiveis; dataGridSeriesDisponiveis.SelectedValuePath = "SerieId"; dataGridSeriesDisponiveis.Items.Refresh(); } private void dataGridSeriesDisponiveis_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { serieAtual = (Series)dataGridSeriesDisponiveis.SelectedItem; if (serieAtual != null) { listSelosDisponiveisSerieSelecionada = _AppServicoSelos.ConsultarPorIdSerie(serieAtual.SerieId).ToList(); CarregarSerieDisponivelSelecionadaTextBox(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnSalvar_Click(object sender, RoutedEventArgs e) { try { Configuracoes config = _AppServicoConfiguracoes.GetById(1); config.SerieAtual = ((Series)dataGridSeriesDisponiveis.SelectedItem).SerieId; _AppServicoConfiguracoes.Update(config); AlterarLogSistema(logSistema, "Alterou Série do Selo para " + config.SerieAtual); } catch (Exception) { } finally {this.Close(); } } private void SalvarLogSistema(string descricao) { logSistema = new Cs_Notas.Dominio.Entities.LogSistema(); logSistema.Data = DateTime.Now.Date; logSistema.Descricao = descricao; logSistema.Hora = DateTime.Now.ToLongTimeString(); logSistema.Tela = "Série Selo Atual"; logSistema.IdUsuario = _usuario.UsuarioId; logSistema.Usuario = _usuario.Nome; logSistema.Maquina = Environment.MachineName.ToString(); logSistema.InicioTela = string.Format("Serie {0}; Selo Inicio {1}; Selo Fim {2}; Quant. {3}; Utilizados {4}; Livres {5};", txtSerieLetra.Text, txtSerieInicial.Text, txtSerieFinal.Text, txtSerieQtd.Text, txtSerieUtilizado.Text, txtSerieLivre.Text); _AppServicoLogSistema.Add(logSistema); } private void AlterarLogSistema(Cs_Notas.Dominio.Entities.LogSistema log, string descricao) { logSistema = _AppServicoLogSistema.GetById(log.LogId); logSistema.Descricao = descricao; logSistema.HoraClose = DateTime.Now.ToLongTimeString(); logSistema.FimTela = string.Format("Serie {0}; Selo Inicio {1}; Selo Fim {2}; Quant. {3}; Utilizados {4}; Livres {5};", txtSerieLetra.Text, txtSerieInicial.Text, txtSerieFinal.Text, txtSerieQtd.Text, txtSerieUtilizado.Text, txtSerieLivre.Text); _AppServicoLogSistema.Update(logSistema); } private void CarregarSerieDisponivelSelecionadaTextBox() { txtSerieLetra.Text = serieAtual.Letra; txtSerieInicial.Text = string.Format("{0:00000}", serieAtual.Inicial); txtSerieFinal.Text = string.Format("{0:00000}", serieAtual.Final); txtSerieQtd.Text = serieAtual.Quantidade.ToString(); txtSerieUtilizado.Text = listSelosDisponiveisSerieSelecionada.Where(p => p.IdSerie == serieAtual.SerieId && p.Status != "LIVRE").Count().ToString(); txtSerieLivre.Text = listSelosDisponiveisSerieSelecionada.Where(p => p.IdSerie == serieAtual.SerieId && p.Status == "LIVRE").Count().ToString(); } private void Window_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { this.Close(); } } } }
using System.Threading; // ReSharper disable once CheckNamespace namespace System { /// <summary> /// Extensions for the <see cref="double"/> class. /// </summary> public static class DoubleExtensions { /// <summary> /// The double epsilon. /// </summary> public const double DoubleEpsilon = 2.2204460492503131E-15; /// <summary> /// Compare two values. Return <c>true</c> if they are equals. /// </summary> /// <param name="a">The first value.</param> /// <param name="b">The second value.</param> /// <returns> /// <c>true</c> if the two values are equals, <c>false</c> otherwise. /// </returns> public static bool IsEqual(this double a, double b) { return Math.Abs(a - b) < double.Epsilon; } /// <summary> /// Compare two values. Return <c>true</c> if they are equals. /// </summary> /// <param name="a">The first value.</param> /// <param name="b">The second value.</param> /// <returns> /// <c>true</c> if the two values are equals, <c>false</c> otherwise. /// </returns> public static bool IsEqual(this double? a, double? b) { if (a == null || b == null) { return a == null && b == null; } return IsEqual((double)a, (double)b); } /// <summary> /// Determines whether the specified b is equal. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <param name="decimalPrecision">The decimal precision.</param> /// <returns> /// <c>true</c> if the specified b is equal; otherwise, <c>false</c>. /// </returns> public static bool IsEqual(this double a, double b, int decimalPrecision) { return ((decimal)a).IsEqual((decimal)b, decimalPrecision); } /// <summary> /// Determines whether the specified a is equal. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <param name="decimalPrecision">The decimal precision.</param> public static bool IsEqual(this double? a, double? b, int decimalPrecision) { if (a == null || b == null) { return a == null && b == null; } return ((decimal)a).IsEqual((decimal)b, decimalPrecision); } /// <summary> /// Ares the close. /// </summary> /// <param name="value1">The value1.</param> /// <param name="value2">The value2.</param> public static bool AreClose(this double value1, double value2) { if (value1.IsEqual(value2)) { return true; } var num1 = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * DoubleEpsilon / 10; var num2 = value1 - value2; return -num1 < num2 && num1 > num2; } /// <summary> /// Greater the than or close. /// </summary> /// <param name="value1">The value1.</param> /// <param name="value2">The value2.</param> public static bool GreaterThanOrClose(this double value1, double value2) { return (value1 > value2) || AreClose(value1, value2); } /// <summary> /// Determines whether the specified value is zero. /// </summary> /// <param name="value">The value.</param> public static bool IsZero(this double value) { return Math.Abs(value) < DoubleEpsilon; } /// <summary> /// Currencies the rounding as integer. /// </summary> /// <param name="value">The value.</param> public static int CurrencyRoundingAsInteger(this double value) { return (int)CurrencyRounding(value, 0); } /// <summary> /// Currencies the rounding. /// </summary> /// <param name="value">The value.</param> public static double CurrencyRounding(this double value) { return CurrencyRounding(value, Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyDecimalDigits); } /// <summary> /// Currencies the rounding. /// </summary> /// <param name="value">The value.</param> /// <param name="digits">The digits.</param> public static double CurrencyRounding(this double value, int digits) { if (digits < 0) { digits = 0; } return Math.Round(value, digits, MidpointRounding.AwayFromZero); } /// <summary> /// Rounds the off2. /// </summary> /// <param name="value">The value.</param> public static double RoundOff2(this double value) { return RoundOff(value, 2); } /// <summary> /// Rounds the off10. /// </summary> /// <param name="value">The value.</param> public static double RoundOff10(this double value) { return RoundOff(value, 10); } /// <summary> /// Rounds the off. /// </summary> /// <param name="value">The value.</param> /// <param name="numberOfDecimals">The number of decimals.</param> public static double RoundOff(this double value, int numberOfDecimals) { return Math.Round(value, numberOfDecimals); } /// <summary> /// Rounds the off percent. /// </summary> /// <param name="percent">The percent.</param> public static double RoundOffPercent(this double percent) { return RoundOff(percent, 2); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using WebStore.DAL.Context; using WebStore.DomainNew.Dto; using WebStore.DomainNew.Entities; using WebStore.DomainNew.Filters; using WebStore.DomainNew.Helpers; using WebStore.Interfaces; namespace WebStore.Services.Sql { public class SqlProductService : IProductService { private readonly WebStoreContext _webStoreContext; public SqlProductService( WebStoreContext webStoreContext) { _webStoreContext = webStoreContext; } public IEnumerable<Category> GetCategories() { return _webStoreContext .Categories.ToList(); } public IEnumerable<Brand> GetBrands() { return _webStoreContext .Brands.ToList(); } public IEnumerable<ProductDto> GetProducts(ProductsFilter filter) { var query = _webStoreContext .Products .Include(p => p.Brand) .Include(p => p.Category) .AsQueryable(); if (filter.BrandId.HasValue) { query = query.Where(c => c.BrandId.HasValue && c.BrandId.Value.Equals( filter.BrandId.Value)); } if (filter.CategoryId.HasValue) { query = query.Where(c => c.CategoryId .Equals(filter.CategoryId.Value)); } return query.Select(p => p.ToDto()).ToList(); } public ProductDto GetProductById(int id) { var product = _webStoreContext .Products .Include(p => p.Brand) .Include(p => p.Category) .SingleOrDefault(p => p.Id == id); if (product != null) return product.ToDto(); return null; } public Category GetCategoryById(int id) { var category = _webStoreContext.Categories .SingleOrDefault(c => c.Id == id); return category; } public Brand GetBrandById(int id) { var brand = _webStoreContext.Brands .SingleOrDefault(b => b.Id == id); return brand; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityAtoms.Editor { public static class AtomsSearchableAssetCreationMenu { class StringTree<T> { public Dictionary<string, StringTree<T>> SubTrees { get; } = new Dictionary<string, StringTree<T>>(); public T Value { get; private set; } public void Insert(string path, T value, int idx = 0) { Internal_Insert(path.Split('/'), idx, value); } private void Internal_Insert(string[] path, int idx, T value) { if (idx >= path.Length) { Value = value; return; } if (!SubTrees.ContainsKey(path[idx])) SubTrees.Add(path[idx], new StringTree<T>()); SubTrees[path[idx]].Internal_Insert(path, idx + 1, value); } } [MenuItem(itemName: "Assets/Create/Atoms Search &1", isValidateFunction: false, priority: -1)] // Adds to the project window's create menu public static void AtomsSearchMenu() { StringTree<Type> typeTree = new StringTree<Type>(); foreach (var type in TypeCache.GetTypesWithAttribute<CreateAssetMenuAttribute>() .Where(t => t.GetCustomAttribute<AtomsSearchable>(true) != null)) { var name = type.GetCustomAttribute<CreateAssetMenuAttribute>().menuName; var i = name.LastIndexOf('/'); name = (i == -1) ? name : name.Substring(0, i + 1) + type.Name; typeTree.Insert(name, type, 1); } var projectBrowserType = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.ProjectBrowser"); var projectBrowser = EditorWindow.GetWindow(projectBrowserType); Vector2 xy = new Vector2(projectBrowser.position.x + 10, projectBrowser.position.y + 60); var dropdown = new SearchTypeDropdown(new AdvancedDropdownState(), typeTree, (s) => { EditorApplication.ExecuteMenuItem("Assets/Create/" + s.GetCustomAttribute<CreateAssetMenuAttribute>().menuName); }) { MinimumSize = new Vector2(projectBrowser.position.width - 20, projectBrowser.position.height - 80) }; var rect = new Rect(xy.x, xy.y, projectBrowser.position.width - 20, projectBrowser.position.height); dropdown.Show(new Rect()); // don't use this to position the var window = typeof(SearchTypeDropdown).GetField("m_WindowInstance", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(dropdown) as EditorWindow; window.position = rect; } private class SearchTypeDropdown : AdvancedDropdown { private readonly StringTree<Type> _list; private readonly Action<Type> _func; private readonly List<Type> _lookup = new List<Type>(); public Vector2 MinimumSize { get => minimumSize; set => minimumSize = value; } public SearchTypeDropdown(AdvancedDropdownState state, StringTree<Type> list, Action<Type> func) : base(state) { _list = list; _func = func; } protected override void ItemSelected(AdvancedDropdownItem item) { base.ItemSelected(item); _func?.Invoke(_lookup[item.id]); } private void Render(StringTree<Type> tree, string key, AdvancedDropdownItem parentGroup) { if (tree.Value != null) { _lookup.Add(tree.Value); parentGroup.AddChild(new AdvancedDropdownItem(key) { id = _lookup.Count - 1 }); } else { var self = new AdvancedDropdownItem(key); foreach (var subtree in tree.SubTrees) { Render(subtree.Value, subtree.Key, self); } parentGroup.AddChild(self); } } protected override AdvancedDropdownItem BuildRoot() { var root = new AdvancedDropdownItem("Unity Atoms"); foreach (var subtree in _list.SubTrees) { Render(subtree.Value, subtree.Key, root); } return root; } } } }
using System; using System.Threading; using System.Threading.Tasks; using IdentityServer3.Core.Logging; using IdentityServer3.Shaolinq.DataModel.Interfaces; using Shaolinq; namespace IdentityServer3.Shaolinq { public class TokenCleanup { private static readonly ILog Logger = LogProvider.GetCurrentClassLogger(); private readonly IIdentityServerOperationalDataAccessModel dataModel; private readonly TimeSpan interval; private CancellationTokenSource cancellationTokenSource; public TokenCleanup(IIdentityServerOperationalDataAccessModel dataModel, int intervalSecs = 60) { this.dataModel = dataModel; this.interval = TimeSpan.FromSeconds(intervalSecs); } public void Start() { if (cancellationTokenSource != null) { throw new InvalidOperationException("Already started. Call Stop first."); } cancellationTokenSource = new CancellationTokenSource(); Task.Factory.StartNew(() => Start(cancellationTokenSource.Token)); } public void Stop() { if (cancellationTokenSource == null) { throw new InvalidOperationException("Not started."); } cancellationTokenSource.Cancel(); cancellationTokenSource = null; } public async Task Start(CancellationToken cancellationToken) { Logger.InfoFormat("Starting TokenCleanup with interval {0}", interval); while (true) { try { await Task.Delay(interval, cancellationToken); } catch (Exception ex) { Logger.InfoException("Exception during Task.Delay, stopping", ex); break; } if (cancellationToken.IsCancellationRequested) { Logger.Info("Cancellation requested"); break; } try { await ClearExpiredTokensAsync(dataModel); } catch (Exception ex) { Logger.ErrorException("Error clearing tokens", ex); } } } public static async Task ClearExpiredTokensAsync(IIdentityServerOperationalDataAccessModel dataModel) { using (var scope = DataAccessScope.CreateReadCommitted()) { await dataModel.Tokens.DeleteAsync(x => x.ExpiryDateTime < DateTime.UtcNow.AddDays(-1)); await scope.CompleteAsync(); } } } }
using Alabo.Domains.Entities; using Alabo.Domains.Services; using Alabo.Framework.Basic.Grades.Domain.Configs; using Alabo.Framework.Basic.Grades.Dtos; using System; using System.Collections.Generic; namespace Alabo.Framework.Basic.Grades.Domain.Services { public interface IGradeService : IService { UserGradeConfig DefaultUserGrade { get; } IList<UserGradeConfig> GetUserGradeList(); UserGradeConfig GetGrade(Guid gradeId); /// <summary> /// 获取所有的用户类类型等级 /// </summary> /// <param name="key"></param> List<BaseGradeConfig> GetGradeListByKey(string key); /// <summary> /// 根据等级Id获取用户等级 /// </summary> /// <param name="guid"></param> List<BaseGradeConfig> GetGradeListByGuid(Guid guid); /// <summary> /// 根据用户类型Id和等级Id获取用户类型等级 /// </summary> /// <param name="userTypeId">用户类型Id></param> /// <param name="gradeId">等级Id</param> BaseGradeConfig GetGradeByUserTypeIdAndGradeId(Guid userTypeId, Guid gradeId); /// <summary> /// 修改会员等级 /// </summary> /// <param name="userGradeInput"></param> ServiceResult UpdateUserGrade(UserGradeInput userGradeInput); } }
/* * Class representing the Moved state in player's state machine (player has moved, but can upgrade or take role) * Limits Player's action to Upgrade() and TakeRole() * Copyright (c) Yulo Leake 2016 */ using Deadwood.Model.Rooms; using Deadwood.Model.Exceptions; namespace Deadwood.Model.PlayerStates { class MovedState : IPlayerState { // Legal moves // Give role to player, move the state to terminal public IPlayerState TakeRole(Player p, string rolename) { // Get role from current room Role role = null; try { role = p.room.GetRole(rolename); } catch (IllegalUserActionException) { throw; } role.AssignPlayer(p); return new TerminalState(); } // Upgrade player, keep the state public IPlayerState Upgrade(Player p, CurrencyType type, int rank) { p.room.Upgrade(p, type, rank); return this; } // Illegal actions, throw an error public IPlayerState Act(Player p) { throw new IllegalUserActionException("\"How can you have any act if you don't have yer role?\"\n(You cannot act without playing a role)"); } public IPlayerState Move(Player p, string destination) { throw new IllegalUserActionException("\"You seem exhausted, wait a bit, will ya?\"\n(You can only move once in a turn)"); } public IPlayerState Rehearse(Player p) { throw new IllegalUserActionException("\"If you don't have yer role, you can't have any rehearsing!\"\n(You cannot rehearse without playing a role)"); } } }
using EPI.Sorting; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Sorting { [TestClass] public class CountingSortUnitTest { [TestMethod] public void ReorderElementsWithSameKey() { CountingSort.Element[] array = new CountingSort.Element[] { new CountingSort.Element() { key = 7, name = "D" }, new CountingSort.Element() { key = 7, name = "B" }, new CountingSort.Element() { key = 20, name = "A" }, new CountingSort.Element() { key = 3, name = "C" }, new CountingSort.Element() { key = 1, name = "B" }, new CountingSort.Element() { key = 7, name = "E" }, new CountingSort.Element() { key = 20, name = "D" } }; CountingSort.ReOrderArrayByElementKeys(array); array.ShouldBeEquivalentTo( new CountingSort.Element[] { new CountingSort.Element() { key = 7, name = "D" }, new CountingSort.Element() { key = 7, name = "B" }, new CountingSort.Element() { key = 7, name = "E" }, new CountingSort.Element() { key = 20, name = "A" }, new CountingSort.Element() { key = 20, name = "D" }, new CountingSort.Element() { key = 3, name = "C" }, new CountingSort.Element() { key = 1, name = "B" } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MayaBot.Knowledge { [Serializable] public class Subject { public Subject() { SubjectNames = new List<string>(); InformationPoints = new List<string>(); } public Subject(string initialSubjectName, params string[] infoPoints) { SubjectNames = new List<string>{initialSubjectName}; InformationPoints = new List<string>(); InformationPoints.AddRange(infoPoints); } public List<string> SubjectNames { get; set; } public List<string> InformationPoints { get; set; } public override string ToString() { return $"{SubjectNames[0]}, {InformationPoints[0]}"; } } }
using Chess.v4.Models.Enums; namespace Chess.v4.Engine.Models { public class DirectionInfo { public bool IsOrthogonal { get; set; } = false; public bool IsDiagonal { get; set; } = false; public Direction Direction { get; set; } = Direction.Invalid; public DiagonalDirection DiagonalDirection { get; set; } = DiagonalDirection.Invalid; } }
using FrameOS.Systems.CommandSystem; using System; using System.Collections.Generic; using System.Text; using FrameOS.FileSystem; using Cosmos.HAL; namespace FrameOS.Commands { class TouchCommand : ICommand { public string description { get => "Make a file."; } public string command => "touch"; public void Run(CommandArg[] commandArgs) { if(commandArgs.Length != 1) { Terminal.WriteLine("Invalid Paramaters"); return; } Filesystem.CreateFile(commandArgs[0].String); } } }
using Justa.Job.Backend.Api.Application.Services.Jwt.Models; using Justa.Job.Backend.Api.Identity.Models; namespace Justa.Job.Backend.Api.Application.Services.Jwt.Interfaces { public interface IJwtService { JsonWebToken CreateJsonWebToken(ApplicationUser user); } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Serilog; using Witsml; using Witsml.Data; using Witsml.Extensions; using Witsml.ServiceReference; using WitsmlExplorer.Api.Jobs; using WitsmlExplorer.Api.Models; using WitsmlExplorer.Api.Query; using WitsmlExplorer.Api.Services; namespace WitsmlExplorer.Api.Workers { public class CreateWellWorker : IWorker<CreateWellJob> { private readonly IWitsmlClient witsmlClient; public CreateWellWorker(IWitsmlClientProvider witsmlClientProvider) { witsmlClient = witsmlClientProvider.GetClient(); } public async Task<(WorkerResult, RefreshAction)> Execute(CreateWellJob job) { var well = job.Well; Verify(well); var wellToCreate = WellQueries.CreateWitsmlWell(well); var result = await witsmlClient.AddToStoreAsync(wellToCreate); if (result.IsSuccessful) { Log.Information("{JobType} - Job successful", GetType().Name); await WaitUntilWellHasBeenCreated(well); var workerResult = new WorkerResult(witsmlClient.GetServerHostname(), true, $"Well created ({well.Name} [{well.Uid}])"); var refreshAction = new RefreshWell(witsmlClient.GetServerHostname(), well.Uid, RefreshType.Add); return (workerResult, refreshAction); } var description = new EntityDescription { WellName = well.Name }; Log.Error("Job failed. An error occurred when creating well: {Well}", job.Well.PrintProperties()); return (new WorkerResult(witsmlClient.GetServerHostname(), false, "Failed to create well", result.Reason, description), null); } private async Task WaitUntilWellHasBeenCreated(Well well) { var isWellCreated = false; var query = WellQueries.GetWitsmlWellByUid(well.Uid); var maxRetries = 30; while (!isWellCreated) { if (--maxRetries == 0) { throw new InvalidOperationException($"Not able to read newly created well with name {well.Name} (id={well.Uid})"); } Thread.Sleep(1000); var wellResult = await witsmlClient.GetFromStoreAsync(query, new OptionsIn(ReturnElements.IdOnly)); isWellCreated = wellResult.Wells.Any(); } } private static void Verify(Well well) { if (string.IsNullOrEmpty(well.Uid)) throw new InvalidOperationException($"{nameof(well.Uid)} cannot be empty"); if (string.IsNullOrEmpty(well.Name)) throw new InvalidOperationException($"{nameof(well.Name)} cannot be empty"); if (string.IsNullOrEmpty(well.TimeZone)) throw new InvalidOperationException($"{nameof(well.TimeZone)} cannot be empty"); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using OBS_Net.Entities.Tables; using System; using System.Collections.Generic; using System.Text; namespace OBS_Net.DAL.ORM.EFCore { public class ObsContext:DbContext { public ObsContext(DbContextOptions<ObsContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<LessonForStudent>() .HasOne(sa => sa.Student) .WithMany(sa => sa.MyLessons) .HasForeignKey(sa => sa.StudentId); modelBuilder.Entity<Lesson>() .HasOne(sa => sa.Teacher) .WithMany(sa => sa.MeLessons) .HasForeignKey(sa => sa.TeacherId); } public DbSet<Lesson> Lessons { get; set; } public DbSet<LessonForStudent> LessonForStudents { get; set; } public DbSet<Student> Students { get; set; } public DbSet<Teacher> Teachers { get; set; } } }
using UnityEngine; [RequireComponent(typeof(Health))] [RequireComponent(typeof(CharacterSheet))] [RequireComponent(typeof(Animator))] public class DemonBrain : MonoBehaviour { private static int faceLeftAnimParam { get; } = Animator.StringToHash("FaceLeft"); private static int walkingAnimParam { get; } = Animator.StringToHash("Walking"); private static int deadAnimParam { get; } = Animator.StringToHash("Dead"); [SerializeField] protected CharacterSheet _characterSheet; [SerializeField] protected Animator _animator; [SerializeField] protected SidePositionChecker _wallChecker; [SerializeField] protected SidePositionChecker _platformEndChecker; [SerializeField] protected float _pauseTime = 2; [SerializeField] protected AudioClip _clipOnDead; private bool directionRight { get; set; } = true; private float pauseStartTime { get; set; } = -100; private void Reset() { if (!_characterSheet) _characterSheet = GetComponent<CharacterSheet>(); if (!_animator) _animator = GetComponent<Animator>(); } private void Awake() { GetComponent<Health>().onDead.AddListener(HandleDeath); } private void HandleDeath() { _animator.SetTrigger(deadAnimParam); GetComponent<Rigidbody2D>().gravityScale = 0; foreach (var thisColliders in GetComponentsInChildren<Collider2D>()) thisColliders.enabled = false; AudioManager.Sfx.Play(_clipOnDead); } private void Update() { if (pauseStartTime + _pauseTime > Time.time) return; if (HasToStop()) { pauseStartTime = Time.time; _animator.SetBool(walkingAnimParam, false); directionRight = !directionRight; return; } _animator.SetBool(walkingAnimParam, true); _animator.SetBool(faceLeftAnimParam, !directionRight); transform.position += new Vector3((directionRight ? 1 : -1) * _characterSheet.speed * Time.deltaTime, 0, 0); } private bool HasToStop() { if (directionRight && (!_platformEndChecker.isRightValid || _wallChecker.isRightValid)) return true; if (!directionRight && (!_platformEndChecker.isLeftValid || _wallChecker.isLeftValid)) return true; return false; } }
// <copyright file="Global.asax.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Site { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Web.UI; using Infrastructure; using Pages; /// <summary> /// Global /// </summary> public class Global : System.Web.HttpApplication { /// <summary> /// Check is exception being ignored or not. /// </summary> /// <param name="exception">exception</param> /// <returns>returns bool</returns> public bool IsExceptionIgnored(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } var nestedExceptions = exception.GetExceptionChain(); return nestedExceptions.Any(ex => ex is ViewStateException || ex.Message.Contains("Timeout") || ex.Message.StartsWith("Invalid viewstate") || ex.Message.Contains("potentially dangerous") || ex.Message.Contains("The remote host closed the connection") || ex.Message.Contains("System.Web.UI.ViewStateException: Invalid viewstate") || ex.Message.Contains("System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError") || ex.Message.Contains("0x80070032") || ex.Message.Contains("/images/") || ////(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) || ex is ThreadAbortException); } /// <summary> /// Application Start Event /// </summary> /// <param name="sender">sender value</param> /// <param name="e">e value</param> protected void Application_Start(object sender, EventArgs e) { ////In Server TLS 1.0 is disabled to to run this application, need to write below line. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } /// <summary> /// Application Post Authorize Request /// </summary> protected void Application_PostAuthorizeRequest() { HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required); } /// <summary> /// application request state /// </summary> /// <param name="sender">object sender</param> /// <param name="e">event argument e</param> protected void Application_AcquireRequestState(object sender, EventArgs e) { string language = string.Empty; if (this.Request.UserLanguages != null && this.Session["UserPortalLanguageId"] == null) { language = this.Request.UserLanguages[0]; if (language.ToLower().Contains("ar")) { SmartLibrary.Infrastructure.ProjectSession.UserPortalLanguageId = SmartLibrary.Infrastructure.SystemEnumList.Language.Arabic.GetHashCode(); } else { SmartLibrary.Infrastructure.ProjectSession.UserPortalLanguageId = SmartLibrary.Infrastructure.SystemEnumList.Language.English.GetHashCode(); } } language = SmartLibrary.Site.Classes.General.GetCultureName(SmartLibrary.Infrastructure.ProjectSession.UserPortalLanguageId); Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language); } /// <summary> /// Application Begin Request /// </summary> /// <param name="sender">sender value</param> /// <param name="e">e value</param> protected void Application_BeginRequest(object sender, EventArgs e) { if (this.Request.HttpMethod != "POST") { ////Convert URL to lowercase string lowercaseURL = this.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath; if (Regex.IsMatch(lowercaseURL, @"[A-Z]")) { System.Web.HttpContext.Current.Response.RedirectPermanent(lowercaseURL.ToLower() + HttpContext.Current.Request.Url.Query); } } } /// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Application_Error(object sender, EventArgs e) { Exception exception = this.Server.GetLastError(); this.Response.Clear(); if (this.IsExceptionIgnored(exception) || exception.Message.ToString().Contains("was not found or does not implement IController.")) { return; } string controller = SmartLibrary.Site.Pages.Controllers.Error; string action = string.Empty; if (exception.InnerException?.Message == "The remote server returned an error: (404) Not Found.") { action = Actions.UnAuthorizePage; this.Session.Abandon(); this.Session.Clear(); } else if (exception.InnerException?.Message == "The remote server returned an error: (401) Unauthorized.") { action = Actions.UnAuthorizePage; this.Session.Abandon(); this.Session.Clear(); } else { action = Actions.ErrorPage; var httpException = exception as HttpException; if (httpException?.GetHttpCode() == 404) { action = Actions.PageNotFound; } } bool throwError = System.Configuration.ConfigurationManager.AppSettings["ThrowError"].ToBoolean(); if ((!throwError || action == Actions.UnAuthorizePage) && !string.IsNullOrEmpty(action)) { var routeData = new RouteData(); routeData.Values.Add("controller", controller); routeData.Values.Add("action", action); routeData.Values.Add("exception", exception); this.Server.ClearError(); this.Response.TrySkipIisCustomErrors = true; this.Response.Headers.Add("Content-Type", "text/html"); if (controller != SmartLibrary.Site.Pages.Controllers.Home) { IController errorController = new SmartLibrary.Site.Controllers.ErrorController(); errorController.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData)); } else { IController loginController = new SmartLibrary.Site.Controllers.ErrorController(); loginController.Execute(new RequestContext(new HttpContextWrapper(this.Context), routeData)); } } LogWritter.WriteErrorFile(exception, ProjectSession.Email); } } }
// Utility.cs // using System; using System.Collections; using System.Html; using System.Runtime.CompilerServices; using jQueryApi; namespace SportsLinkScript.Shared.Facebook { [IgnoreNamespace] [Imported] [ScriptName("Object")] public class AuthResponse { public SessionResponse Session; public string Status; } }
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class ReadStory : MonoBehaviour { public MeshRenderer textToShow; void OnTriggerStay2D(Collider2D collision) { if (Input.GetKey("e") && collision.gameObject.tag == "Player") { textToShow.enabled = true; } } }
namespace Cs_Gerencial.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class PessoasAdd : DbMigration { public override void Up() { CreateTable( "dbo.Pessoas", c => new { PessoasId = c.Int(nullable: false, identity: true), Nome = c.String(maxLength: 100, unicode: false), TipoPessoa = c.String(nullable: false, maxLength: 1, unicode: false), DataCadastro = c.DateTime(nullable: false, storeType: "date"), CpfCgc = c.String(maxLength: 18, unicode: false), Rg = c.String(maxLength: 25, unicode: false), OrgaoRG = c.String(maxLength: 70, unicode: false), DataEmissaoRG = c.DateTime(nullable: false, storeType: "date"), Nacionalidade = c.String(maxLength: 30, unicode: false), Endereco = c.String(maxLength: 100, unicode: false), Bairro = c.String(maxLength: 100, unicode: false), Cidade = c.String(maxLength: 100, unicode: false), Uf = c.String(maxLength: 2, unicode: false), Cep = c.String(maxLength: 10, unicode: false), EsctadoCivil = c.Int(nullable: false), Conjuge = c.String(maxLength: 100, unicode: false), RegimeBens = c.String(maxLength: 30, unicode: false), DataCasamento = c.DateTime(nullable: false, storeType: "date"), DataObito = c.DateTime(nullable: false, storeType: "date"), LivroObito = c.String(maxLength: 18, unicode: false), FolhaObito = c.String(maxLength: 10, unicode: false), SeloObito = c.String(maxLength: 9, unicode: false), DataNascimento = c.DateTime(nullable: false, storeType: "date"), NomePai = c.String(maxLength: 100, unicode: false), NomeMae = c.String(maxLength: 100, unicode: false), Profissao = c.String(maxLength: 100, unicode: false), Justificativa = c.String(maxLength: 800, unicode: false), Digital = c.String(maxLength: 800, unicode: false), TipoEndereco = c.String(maxLength: 1, unicode: false), Sexo = c.String(maxLength: 1, unicode: false), Sobrenome = c.String(maxLength: 100, unicode: false), IfpDetran = c.String(maxLength: 1, unicode: false), Observacao = c.String(maxLength: 100, unicode: false), Naturalidade = c.String(maxLength: 100, unicode: false), Atualizado = c.String(maxLength: 1, unicode: false), Digitador = c.String(maxLength: 10, unicode: false), QtdFilhosMaiores = c.Int(), UfNascimento = c.String(maxLength: 2, unicode: false), PaisReside = c.String(maxLength: 30, unicode: false), UfPaisReside = c.String(maxLength: 2, unicode: false), CodigoMunicipioReside = c.Int(), UfOab = c.String(maxLength: 2, unicode: false), CodigoPais = c.Int(), CodigoPaisOnu = c.Int(), }) .PrimaryKey(t => t.PessoasId); } public override void Down() { DropTable("dbo.Pessoas"); } } }
using UnityEngine; [CreateAssetMenu(fileName = "Cell Rail", menuName = "MS49/Cell/Cell Rail", order = 1)] public class CellDataRail : CellData { public EnumRailMoveType moveType; public enum EnumRailMoveType { STRAIGHT = 0, CROSSING = 1, CURVE = 2, STOPPER = 3, MERGER = 4, } }
using UnityEngine.Events; public class SpawnBallEvent : UnityEvent { }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201305061423)] public class AddRoleFunctionCols : Migration { public override void Down() { Delete.Column("RoleNameFr").FromTable("PRF_Role"); Delete.Column("Description").FromTable("PRF_Role"); Delete.Column("FunctionNameFr").FromTable("PRF_Function"); Delete.Column("Description").FromTable("PRF_Function"); } public override void Up() { Alter.Table("PRF_Role").AddColumn("RoleNameFr").AsString().Nullable(); Alter.Table("PRF_Role").AddColumn("Description").AsString(int.MaxValue).Nullable(); Alter.Table("PRF_Function").AddColumn("FunctionNameFr").AsString().Nullable(); Alter.Table("PRF_Function").AddColumn("Description").AsString().Nullable(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EighthQueens { partial class Map { private const int cellsNumber = 8; private char[,] field = new char[cellsNumber, cellsNumber]; private void Write<T>(T n, ConsoleColor color) { Console.ForegroundColor = color; Console.Write($"{n}"); Console.ForegroundColor = ConsoleColor.White; } public void FieldSetUp() { //Full the field with spaces. for (int i = 0; i < cellsNumber; i++) { for (int j = 0; j < cellsNumber; j++) { field[i, j] = ' '; } } } public void PlaceQueen(int x, int y) { /* Q - sign for queen # - positions where queen can move*/ for (int i = 0; i < cellsNumber; i++) { for (int j = 0; j < cellsNumber; j++) { if (x == i && j == y) { field[i, j] = 'Q'; int k = x + 1; while (k < cellsNumber) { field[k, j] = '#'; k++; }//down k = 0; while (k < x) { field[k, j] = '#'; k++; }//up k = y + 1; while (k < cellsNumber) { field[i, k] = '#'; k++; }//rigth k = 0; while (k < y) { field[i, k] = '#'; k++; }//left k = 1; while (i - k >= 0 && j - k >= 0) { field[i - k, j - k] = '#'; k++; }//upLeft diagonal k = 1; while (i + k < cellsNumber && j + k < cellsNumber) { field[i + k, j + k] = '#'; k++; }//downLeft diagonal k = 1; while (i - k >= 0 && j + k < cellsNumber) { field[i - k, j + k] = '#'; k++; }//upRigth diagonal k = 1; while (i + k < cellsNumber && j - k >= 0) { field[i + k, j - k] = '#'; k++; }//downRigth diagonal } } } } public void DrawField() { Console.Write(" "); for (int i = 0; i < cellsNumber; i++) { Write(i, ConsoleColor.Green); } Console.WriteLine(); for (int i = 0; i < cellsNumber; i++) { for (int j = 0; j < cellsNumber; j++) { if (j == 0) { Write(i, ConsoleColor.Green); } if (field[i, j] == '#') { Write(field[i, j], ConsoleColor.White); } else if (field[i, j] == 'Q') { Write(field[i, j], ConsoleColor.Red); } else { Console.Write($"{field[i, j]}"); } } Console.WriteLine(); } } static void Main(string[] args) { Map map = new Map(); int y = 0; int x = 0; while (true) { Console.WriteLine("Enter Y coordinate of the first queen : "); while (!int.TryParse(Console.ReadLine(), out y)) { Console.WriteLine("Please Enter a valid numerical value!"); } Console.WriteLine("Enter X coordinate of the first queen : "); while (!int.TryParse(Console.ReadLine(), out x)) { Console.WriteLine("Please Enter a valid numerical value!"); } map.FieldSetUp(); map.PlaceQueen(x, y); map.CheckSells(x, y); map.DrawField(); } } } }
using System; using System.Collections; using System.Linq; using HiLoSocket.Compressor; using NUnit.Framework; namespace HiLoSocketTests.Compressor { [TestFixture] [Category( "CompressorFactoryTests" )] public class CompressorFactoryTests { [TestCaseSource( typeof( CompressTypeSource ) )] public void CreateCompressor_CompressType_ShouldNotThrowException( CompressType compressType ) { Shouldly.Should.NotThrow( ( ) => CompressorFactory.CreateCompressor( compressType ) ); } private class CompressTypeSource : IEnumerable { public IEnumerator GetEnumerator( ) { return Enum.GetValues( typeof( CompressType ) ).Cast<CompressType>( ).GetEnumerator( ); } } } }
using Common.Data; using Common.Exceptions; using System; using System.Collections.Generic; using System.Data; namespace Entity { public partial class ImagesAssignments { public bool CheckExists(string connectionString, int id) { bool result = false; string sql = "select count(*) from images_assignments where id = " + id.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0; } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public DataTable GetImageManagementData(string connectionString, int id) { DataTable result = null; string sql = "select i.*, s.Image_Management_Name from Images_Assignments i left outer join " + "System_Stations s on i.Channel = s.Value where i.ID = " + id.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelect(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<ImagesAssignments> GetItemsByDateChannel(string connectionString, DateTime date, string channels) { string sql = "select * from images_assignments where sched_date = '" + date.ToString() + "' and channel in" + "('" + channels + "') and is_group = 0"; return GetList(connectionString, sql); } public List<ImagesAssignments> GetItemsByProject(string connectionString, int projectId) { string sql = "select * from images_assignments where project_id = " + projectId.ToString(); return GetList(connectionString, sql); } public bool UpdateDueDate(string connectionString, int id, int projectId, DateTime date) { bool result = false; string sql = "Update Images_assignments set due_date = '" + date.ToString() + "'"; if (id > 0) sql += ", project_id = " + projectId.ToString() + " where id = " + id.ToString(); else sql += " where project_id = " + projectId.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public bool UpdateProjectId(string connectionString, int id, int projectId) { bool result = false; string sql = "update images_assignments set project_id = " + projectId.ToString() + " " + "where id = " + id.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public bool UpdateRecord(string connectionString, ImagesAssignments data) { bool result = false; Mapper<ImagesAssignments> mapper = new Mapper<ImagesAssignments>(); string sql = ""; try { sql = mapper.MapSingleInsert(data); using (Database database = new Database(connectionString)) { result = database.ExecuteNonQuery(sql); } } catch (Exception e) { throw new EntityException(sql, e); } finally { mapper = null; } return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AntibacSledge : MonoBehaviour { public GameObject attack; private GameObject meleeATK; public float meleeATKCooldown; public bool sledgeCraft; public GameObject pS; public PlaySound playSound; private void Start() { pS = GameObject.FindGameObjectWithTag("PlayerSFX"); playSound = pS.GetComponent<PlaySound>(); } // Update is called once per frame public void Update() { meleeATKCooldown = meleeATKCooldown - Time.deltaTime; if (Input.GetKeyDown(KeyCode.Space) && meleeATKCooldown <= 0f && sledgeCraft == true) { meleeATK = Instantiate(attack, transform.position, transform.rotation); meleeATKCooldown = 0.18f; Destroy(meleeATK, 0.18f); playSound.AntibacSledgeSwing(); } if (meleeATKCooldown >= 0) meleeATK.transform.Rotate(new Vector3(transform.rotation.x, transform.rotation.y, transform.rotation.z + 600 * Time.deltaTime)); } }
namespace MockDelegates { public delegate T Add<T>(T a, T b); }
namespace PriceChangeAlert { using System; public class StartUp { public static void Main() { int n = int.Parse(Console.ReadLine()); double threshold = double.Parse(Console.ReadLine()); double last = double.Parse(Console.ReadLine()); for (int i = 0; i < n - 1; i++) { double price = double.Parse(Console.ReadLine()); double diff = Proc(last, price); bool isSignificantDifference = isDiff(diff, threshold); string message = Get(price, last, diff, isSignificantDifference); Console.WriteLine(message); last = price; } } static string Get(double price, double last, double change, bool etherTrueOrFalse) { string result = ""; if (change == 0) { result = string.Format("NO CHANGE: {0}", price); } else if (!etherTrueOrFalse) { result = string.Format("MINOR CHANGE: {0} to {1} ({2:F2}%)", last, price, change * 100); } else if (etherTrueOrFalse && (change > 0)) { result = string.Format("PRICE UP: {0} to {1} ({2:F2}%)", last, price, change * 100); } else if (etherTrueOrFalse && (change < 0)) result = string.Format("PRICE DOWN: {0} to {1} ({2:F2}%)", last, price, change * 100); return result; } static bool isDiff(double threshold, double isDiff) { if (Math.Abs(threshold) >= isDiff) { return true; } return false; } static double Proc(double last, double price) { double res = (price - last) / last; return res; } } }
using System; namespace Nono.Engine.Extensions { public static class CuesExtensions { public static int Sum(this ReadOnlySpan<int> span) { int sum = 0; for (int i = 0; i < span.Length; i++) { sum += span[i]; } return sum; } public static int Max(this ReadOnlySpan<int> span) { int max = span[0]; for (int i = 1; i < span.Length; i++) { var element = span[i]; max = element > max ? element : max; } return max; } } }
using SGCFT.Dominio.Entidades; using System.Collections.Generic; using System.Linq; namespace SGCFT.Apresentacao.Models { public class QuestionarioViewModel { public QuestionarioViewModel(Pergunta pergunta) { this.IdPergunta = pergunta.Id; this.Pergunta = pergunta.Texto; this.Alternativas = pergunta.Alternativas.Select(x => new AlternativaViewModel(x.Id,x.Texto)).ToList(); } public int IdPergunta { get; set; } public string Pergunta { get; set; } public List<AlternativaViewModel> Alternativas { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrendyolApiTest.Entities { public class Books { public List<Book> BookList { get; set; } } }
#region copyright // ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** #endregion using Inventory.Models; using Inventory.Services; using Inventory.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Inventory.Views { public sealed partial class DishesView : Page { public DishesView() { ViewModel = ServiceLocator.Current.GetService<DishesViewModel>(); NavigationService = ServiceLocator.Current.GetService<INavigationService>(); InitializeComponent(); } public DishesViewModel ViewModel { get; } public INavigationService NavigationService { get; } protected override async void OnNavigatedTo(NavigationEventArgs e) { DishListArgs productArgs = (DishListArgs)e.Parameter; ViewModel.Subscribe(); await ViewModel.LoadAsync(productArgs); } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { ViewModel.Unload(); ViewModel.Unsubscribe(); } private async void OpenInNewView(object sender, RoutedEventArgs e) { await NavigationService.CreateNewViewAsync<DishesViewModel>(ViewModel.DishList.CreateArgs()); } private async void OpenDetailsInNewView(object sender, RoutedEventArgs e) { ViewModel.DishDetails.CancelEdit(); await NavigationService.CreateNewViewAsync<DishDetailsViewModel>(ViewModel.DishDetails.CreateArgs()); } public int GetRowSpan(bool isMultipleSelection) { return isMultipleSelection ? 2 : 1; } private void BtnToogleFilterPanel_Click(object sender, RoutedEventArgs e) { if (ViewModel.ToogleFilterBarCommand.CanExecute(this)) { ViewModel.ToogleFilterBarCommand.Execute(this); UpdateToogleFilterButtonIcon(); } } private void UpdateToogleFilterButtonIcon() { Symbol toogleSymbol = ViewModel.IsFilterPanelOpen ? Symbol.Back : Symbol.Forward; btnToogleFilterPanel.Icon = new SymbolIcon(toogleSymbol); } /// <summary> /// Выбор узла (включается отбор по узлу и ниже) /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void TreeCategory_ItemInvoked(TreeView sender, TreeViewItemInvokedEventArgs args) { if (args.InvokedItem is MenuFolderTreeModel) { var node = args.InvokedItem as MenuFolderTreeModel; if (node is MenuFolderTreeModel item) { ViewModel.CategoryFilterChanged(item); } } } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace VoxelSpace { public class SelectionWireframe { V[] _verts; public BasicEffect Effect { get; private set; } public SelectionWireframe(BasicEffect effect) { Effect = effect; float n = -0.01f; float p = 1.01f; Vector3 nnn = new Vector3(n, n, n); Vector3 nnp = new Vector3(n, n, p); Vector3 npn = new Vector3(n, p, n); Vector3 npp = new Vector3(n, p, p); Vector3 pnn = new Vector3(p, n, n); Vector3 pnp = new Vector3(p, n, p); Vector3 ppn = new Vector3(p, p, n); Vector3 ppp = new Vector3(p, p, p); _verts = new V[] { new V(nnn), new V(nnp), new V(nnn), new V(npn), new V(nnn), new V(pnn), new V(nnp), new V(npp), new V(nnp), new V(pnp), new V(npn), new V(npp), new V(npn), new V(ppn), new V(npp), new V(ppp), new V(pnn), new V(pnp), new V(pnn), new V(ppn), new V(pnp), new V(ppp), new V(ppn), new V(ppp) }; } public void Draw(Vector3 position, GraphicsDevice graphics) { Effect.World = Matrix.CreateTranslation(position); foreach (var pass in Effect.CurrentTechnique.Passes) { pass.Apply(); graphics.DrawUserPrimitives(PrimitiveType.LineList, _verts, 0, 12); } } struct V : IVertexType { public VertexDeclaration VertexDeclaration => new VertexDeclaration(new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0)); public Vector3 Position; public V(Vector3 position) { this.Position = position; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.Configuration; namespace Zesty.Core.Common { public static class Cache { private static object Lock = new object(); private static int LifetimeInMinutes = 5; private static readonly List<CacheItem> items = new List<CacheItem>(); private static readonly NLog.Logger logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); static Cache() { IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json"); IConfigurationRoot config = builder.Build(); string minute = config["Zesty:CacheLifetimeInMinutes"]; if (!string.IsNullOrWhiteSpace(minute)) { try { LifetimeInMinutes = int.Parse(minute); } catch { } } logger.Info($"LifetimeInMinutes: {LifetimeInMinutes}"); } public static void Store<T>(CacheKey key, T value, StorePolicy storePolicy) { logger.Debug($"Request to store with key {key.Key}@{key.Domain}"); T present = Get<T>(key); if (present == null) { lock (Lock) { CacheItem cacheItem = items.Where(x => x.Key.Domain == key.Domain && x.Key.Key == key.Key).FirstOrDefault(); if (cacheItem == null) { cacheItem = new CacheItem() { Inserted = DateTime.Now, Key = key, Value = value }; items.Add(cacheItem); logger.Debug($"Stored with key {key.Key}@{key.Domain}"); } } } else { if (storePolicy == StorePolicy.SkipIfExists) { logger.Debug($"Store skipped with key {key.Key}@{key.Domain}"); return; } Remove(key); lock (Lock) { CacheItem cacheItem = items.Where(x => x.Key.Domain == key.Domain && x.Key.Key == key.Key).FirstOrDefault(); if (cacheItem == null) { cacheItem = new CacheItem() { Inserted = DateTime.Now, Key = key, Value = value }; items.Add(cacheItem); logger.Debug($"Stored with key {key.Key}@{key.Domain}"); } } } } private static void Remove(CacheKey key) { logger.Debug($"Remove with key {key.Key}@{key.Domain}"); CacheItem present = items.Where(x => x.Key.Domain == key.Domain && x.Key.Key == key.Key).FirstOrDefault(); if (present != null) { lock (Lock) { present = items.Where(x => x.Key.Domain == key.Domain && x.Key.Key == key.Key).FirstOrDefault(); if (present != null) { items.Remove(present); logger.Debug($"Removed key {key.Key}@{key.Domain}"); } } } } public static T Get<T>(CacheKey key) { logger.Debug($"Get with key {key.Key}@{key.Domain}"); CacheItem present = items.Where(x => x.Key.Domain == key.Domain && x.Key.Key == key.Key).FirstOrDefault(); if (present == null) { logger.Debug($"Key not found {key.Key}@{key.Domain}"); return default; } DateTime expired = present.Inserted.AddMinutes(LifetimeInMinutes); logger.Debug($"Object with key {key.Key}@{key.Domain} expire at {expired}"); if (expired < DateTime.Now) { logger.Debug($"Object expired with key {key.Key}@{key.Domain}"); lock (Lock) { if (items.Contains(present)) { items.Remove(present); logger.Debug($"Object expired removed with key {key.Key}@{key.Domain}"); } } return default; } logger.Debug($"Object found with key {key.Key}@{key.Domain}"); return (T)present.Value; } } public enum StorePolicy { SkipIfExists, ReplaceIfExists } public class CacheKey { public string Domain { get; set; } public string Key { get; set; } } public class CacheItem { public CacheKey Key { get; set; } public DateTime Inserted { get; set; } public object Value { get; set; } } public static class CacheDomains { public static readonly string Settings = "Settings"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Library.Model { public class LeaderboardLine { private int _score; private float _timeElapsed; private int _stepsTaken; public LeaderboardLine() { } public LeaderboardLine(int id, int raceId, int userId, int score, float timeElapsed, int stepsTaken, DateTime leaderBoardDateTime, List<PathStep> paths, User user) { Id = id; RaceId = raceId; UserId = userId; Score = score; TimeElapsed = timeElapsed; StepsTaken = stepsTaken; LeaderboardDateTime = leaderBoardDateTime; Path = paths; User = user; } public int Id { get; set; } public int RaceId { get; set; } public int UserId { get; set; } public int Score { get { return _score; } set { if(value < 0) { throw new ArgumentOutOfRangeException("Score shouldn't be negative"); } else { _score = value; } } } public float TimeElapsed { get { return _timeElapsed; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("TimeElapsed should not be negative or 0"); } else { _timeElapsed = value; } } } public int StepsTaken { get { return _stepsTaken; } set { if(value <= 0) { throw new ArgumentOutOfRangeException("StepsTaken should not be negative or 0"); } else { _stepsTaken = value; } } } public DateTime LeaderboardDateTime { get; set; } public List<PathStep> Path { get; set; } public User User { get; set; } } }
using System; using Autofac; using Tests.Pages.ActionID; using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Oberon; using Tests.Pages.Oberon; using Tests.Pages.Oberon.Common; using Tests.Pages.Oberon.GivingRecipient; using OpenQA.Selenium; namespace Tests.Projects.Oberon.GivingHistory { public class VerifyAddGivingRecipient : BaseTest { private Driver Driver { get { return Scope.Resolve<Driver>(); }} private ActionIdLogIn ActionLogIn { get { return Scope.Resolve<ActionIdLogIn>(); } } /// <summary> /// COA 1. Verify that selecting the option to manage recipients takes me to a list of my existing recipients (similar to manage users list) /// COA 2. Verify that the Name, Description, State, District, Office and Party properties of /// the Recipient can be added and that Name is required /// </summary> [Test] ////[Ignore] //todo issues with flexigrid [Category("oberon"), Category("oberon_smoketest"), Category("oberon_giving history"), Category("oberon_PRODUCTION")] public void VerifyAddGivingRecipientTest() { ActionLogIn.LogInTenant(); // click the Admin link for managing recipients var util = Scope.Resolve<Nav>(); util.ClickManageGivingHistoryRecipients(); // verify we're on the manage recipients page var listPage = Scope.Resolve<GivingRecipientList>(); Assert.IsTrue( listPage.GetSectionTitle().Contains("List Of Recipients")); // click the add link listPage.ClickAdd(); // verify that the name field is reqired var createPage = Scope.Resolve<GivingRecipientCreate>(); createPage.SaveRecipient(); Assert.IsTrue(createPage.NameValidatorExists()); // add recipient var recipient = GivingHistoryRecipient.GetRandomRecipient(); createPage.EnterFormData(recipient); createPage.SaveRecipient(); Driver.WaitForElementToDisplayBy(createPage.EditLinkLocator); // verify we're on the details page and add date and ID to recip var detailPage = Scope.Resolve<GivingRecipientDetails>(); recipient.Id = detailPage.RecipientId(); recipient.CreatedOn = DateTime.Now; // verify the information was saved Assert.IsTrue(detailPage.VerifyRecipientInfo(recipient)); // go back to List page detailPage.ClickBackToListPage(); // get list of recipients //listPage = new GivingRecipientList(Driver); var recipList = listPage.AllRecipients; // get the index number of the recipient int indexNum = -1; foreach (GivingHistoryRecipient recip in recipList) { if (recip.Id == recipient.Id) { indexNum = recipList.IndexOf(recip); break; } } IWebElement createdOnDiv = Driver.FindElement(By.XPath("//th[@abbr='CreatedOn']/div")); Driver.Click(createdOnDiv); if (Driver.GetAttribute(createdOnDiv, "class").Contains("sAscending")) Driver.Click(createdOnDiv); // check for values in grid Assert.AreEqual(recipient.CreatedOn.ToShortDateString(), recipList[indexNum].CreatedOn.ToShortDateString()); Assert.AreEqual(recipient.Name, recipList[indexNum].Name); Assert.AreEqual(recipient.Office, recipList[indexNum].Office); Assert.AreEqual(recipient.District, recipList[indexNum].District); Assert.AreEqual(recipient.State, recipList[indexNum].State); Assert.AreEqual(recipient.PoliticalPartyName, recipList[indexNum].PoliticalPartyName); // clean up test data //todo this needs additional waiting, tripping up in the get ID part //listPage.DeleteRecipient(recipient.Id); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SodaMachineProject { public class FileWriter { public static void WriteToInventoryFile(string fileName, List<Inventory> inventory) { using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { foreach (Inventory soda in inventory) { sw.WriteLine(soda); } } } } public static void OverrideInventoryFile(string fileName, List<string> inventory) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { foreach (string soda in inventory) { sw.WriteLine(soda); } } } } public static void OverrideCoinsFile(string fileName, List<int> inventory) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { foreach (int soda in inventory) { sw.WriteLine(soda); } } } } public static void WriteToFile(string fileName, double total) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(total); } } } } }
using UnityEngine; using IsoTools.Internal; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif namespace IsoTools { [ExecuteInEditMode, DisallowMultipleComponent] public class IsoObject : MonoBehaviour { // ------------------------------------------------------------------------ // // Mode // // ------------------------------------------------------------------------ public enum Mode { Mode2d, Mode3d } [SerializeField] Mode _mode = Mode.Mode2d; public Mode mode { get { return _mode; } set { _mode = value; FixTransform(); } } // ------------------------------------------------------------------------ // // Size // // ------------------------------------------------------------------------ [SerializeField] Vector3 _size = Vector3.one; public Vector3 size { get { return _size; } set { _size = IsoUtils.Vec3Max(value, Vector3.zero); FixTransform(); } } public float sizeX { get { return size.x; } set { size = IsoUtils.Vec3ChangeX(size, value); } } public float sizeY { get { return size.y; } set { size = IsoUtils.Vec3ChangeY(size, value); } } public float sizeZ { get { return size.z; } set { size = IsoUtils.Vec3ChangeZ(size, value); } } public Vector2 sizeXY { get { return new Vector2(sizeX, sizeY); } } public Vector2 sizeYZ { get { return new Vector2(sizeY, sizeZ); } } public Vector2 sizeXZ { get { return new Vector2(sizeX, sizeZ); } } // ------------------------------------------------------------------------ // // Position // // ------------------------------------------------------------------------ [SerializeField] Vector3 _position = Vector3.zero; public Vector3 position { get { return _position; } set { _position = value; FixTransform(); } } public float positionX { get { return position.x; } set { position = IsoUtils.Vec3ChangeX(position, value); } } public float positionY { get { return position.y; } set { position = IsoUtils.Vec3ChangeY(position, value); } } public float positionZ { get { return position.z; } set { position = IsoUtils.Vec3ChangeZ(position, value); } } public Vector2 positionXY { get { return new Vector2(positionX, positionY); } } public Vector2 positionYZ { get { return new Vector2(positionY, positionZ); } } public Vector2 positionXZ { get { return new Vector2(positionX, positionZ); } } // ------------------------------------------------------------------------ // // TilePosition // // ------------------------------------------------------------------------ public Vector3 tilePosition { get { return IsoUtils.Vec3Round(position); } set { position = value; } } public float tilePositionX { get { return tilePosition.x; } set { tilePosition = IsoUtils.Vec3ChangeX(tilePosition, value); } } public float tilePositionY { get { return tilePosition.y; } set { tilePosition = IsoUtils.Vec3ChangeY(tilePosition, value); } } public float tilePositionZ { get { return tilePosition.z; } set { tilePosition = IsoUtils.Vec3ChangeZ(tilePosition, value); } } public Vector2 tilePositionXY { get { return new Vector2(tilePositionX, tilePositionY); } } public Vector2 tilePositionYZ { get { return new Vector2(tilePositionY, tilePositionZ); } } public Vector2 tilePositionXZ { get { return new Vector2(tilePositionX, tilePositionZ); } } // ------------------------------------------------------------------------ // // Internal // // ------------------------------------------------------------------------ public class InternalState { public bool Dirty = false; public bool Visited = false; public Rect ScreenRect = new Rect(); public Bounds Bounds3d = new Bounds(); public float Offset3d = 0.0f; public Vector2 MinSector = Vector2.zero; public Vector2 MaxSector = Vector2.zero; public HashSet<IsoObject> SelfDepends = new HashSet<IsoObject>(); public HashSet<IsoObject> TheirDepends = new HashSet<IsoObject>(); } public InternalState Internal = new InternalState(); // ------------------------------------------------------------------------ // // For editor // // ------------------------------------------------------------------------ #if UNITY_EDITOR Vector3 _lastSize = Vector3.zero; Vector3 _lastPosition = Vector3.zero; Vector2 _lastTransPos = Vector2.zero; [SerializeField] bool _isAlignment = true; [SerializeField] bool _isShowBounds = false; public bool isAlignment { get { return _isAlignment; } set { _isAlignment = value; } } public bool isShowBounds { get { return _isShowBounds; } set { _isShowBounds = value; } } #endif // ------------------------------------------------------------------------ // // Functions // // ------------------------------------------------------------------------ IsoWorld _isoWorld = null; public IsoWorld isoWorld { get { if ( !_isoWorld && gameObject.activeInHierarchy ) { _isoWorld = GameObject.FindObjectOfType<IsoWorld>(); } return _isoWorld; } } public void FixTransform() { #if UNITY_EDITOR if ( !Application.isPlaying && isAlignment ) { _position = tilePosition; } #endif if ( isoWorld ) { transform.position = IsoUtils.Vec3ChangeZ( isoWorld.IsoToScreen(position), transform.position.z); FixScreenRect(); } FixLastProperties(); MartDirtyIsoWorld(); } public void FixIsoPosition() { if ( isoWorld ) { position = isoWorld.ScreenToIso( transform.position, positionZ); } } void FixScreenRect() { if ( isoWorld ) { var l = isoWorld.IsoToScreen(position + IsoUtils.Vec3FromY(size.y)).x; var r = isoWorld.IsoToScreen(position + IsoUtils.Vec3FromX(size.x)).x; var b = isoWorld.IsoToScreen(position).y; var t = isoWorld.IsoToScreen(position + size).y; Internal.ScreenRect = new Rect(l, b, r - l, t - b); } } void FixLastProperties() { #if UNITY_EDITOR _lastSize = size; _lastPosition = position; _lastTransPos = transform.position; #endif } void MartDirtyIsoWorld() { if ( isoWorld ) { isoWorld.MarkDirty(this); } #if UNITY_EDITOR EditorUtility.SetDirty(this); #endif } // ------------------------------------------------------------------------ // // Messages // // ------------------------------------------------------------------------ void Awake() { Internal.SelfDepends = new HashSet<IsoObject>(new IsoObject[47]); Internal.SelfDepends.Clear(); Internal.TheirDepends = new HashSet<IsoObject>(new IsoObject[47]); Internal.TheirDepends.Clear(); FixLastProperties(); FixIsoPosition(); } void OnEnable() { if ( isoWorld ) { isoWorld.AddIsoObject(this); } MartDirtyIsoWorld(); } void OnDisable() { if ( isoWorld ) { isoWorld.RemoveIsoObject(this); } } #if UNITY_EDITOR void Reset() { size = Vector3.one; position = Vector3.zero; } void OnValidate() { size = _size; position = _position; } void OnDrawGizmos() { if ( isShowBounds && isoWorld ) { IsoUtils.DrawCube(isoWorld, position + size * 0.5f, size, Color.red, Vector3.zero); } } void Update() { if ( !IsoUtils.Vec3Approximately(_lastSize, _size) ) { size = _size; } if ( !IsoUtils.Vec3Approximately(_lastPosition, _position) ) { position = _position; } if ( !IsoUtils.Vec2Approximately(_lastTransPos, transform.position) ) { FixIsoPosition(); } } #endif } } // namespace IsoTools
using Alabo.Data.People.Internals.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Data.People.Internals.Domain.Repositories { public class InternalRepository : RepositoryMongo<Internal, ObjectId>, IInternalRepository { public InternalRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameController : MonoBehaviour { public static GameController instance; public static int highScore = 0; public Text scoreText, highScoreText, scorePauseText, highScorePauseText, gameOverText, tapToStartText; public GameObject levelText, PauseUI, GameDetailsUI; public float scrollSpeed; private int score = 0, currentLevel; private float dispalyHeight, displayWidth; // Start is called before the first frame update void Awake() { if(instance == null) { instance = this; } else if(instance != this){ Destroy(gameObject); } dispalyHeight = 0.85f * Screen.height; displayWidth = 0.85f * Screen.width; currentLevel = Levels.currentLevel; scrollSpeed = Levels.levelData[currentLevel - 1].scrollSpeed; highScore = currentLevel == Levels.maxLevels ? highScore : Levels.levelData[currentLevel - 1].maxScore; scoreText.text = "Score : " + score.ToString(); if(currentLevel == Levels.maxLevels) { highScoreText.text = "High Score : " + highScore.ToString(); } else { highScoreText.text = "Max Score : " + highScore.ToString(); } } // Update is called once per frame void Update() { if(Bird.gameStatus == Bird.GameStatus.DEAD || Bird.gameStatus == Bird.GameStatus.UPGRADING || Bird.gameStatus == Bird.GameStatus.PAUSED) { OnMenuButtonClick(); if(Input.GetMouseButtonDown(0)) { if(Input.mousePosition.y < dispalyHeight && Input.mousePosition.x < displayWidth) { if(Bird.gameStatus != Bird.GameStatus.PAUSED) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } else { GameDetailsUI.SetActive(true); PauseUI.SetActive(false); Bird.gameStatus = Bird.GameStatus.PLAYING; } Time.timeScale = 1f; } } } } public void BirdScored() { if(Bird.gameStatus == Bird.GameStatus.DEAD || Bird.gameStatus == Bird.GameStatus.UPGRADING) { return; } score++; if(currentLevel == Levels.maxLevels) { if(highScore < score) { highScore = score; highScoreText.text = "High Score : " + highScore.ToString(); } } else { if(score >= highScore) { Levels.UpgradeLevel(); Bird.gameStatus = Bird.GameStatus.UPGRADING; } } scoreText.text = "Score : " + score.ToString(); } private void OnMenuButtonClick() { GameDetailsUI.SetActive(false); scorePauseText.text = "SCORE: " + score.ToString(); if(currentLevel == Levels.maxLevels) { highScorePauseText.text = "HIGH SCORE: " + highScore.ToString(); } else { highScorePauseText.text = "MAX SCORE: " + highScore.ToString(); } if(Bird.gameStatus == Bird.GameStatus.DEAD) { gameOverText.text = "OOPS! BIRD DIED"; tapToStartText.text = "FLAP TO RESTART"; } else if(Bird.gameStatus == Bird.GameStatus.PAUSED) { gameOverText.text = "GAME PAUSED"; tapToStartText.text = "TAP TO CONTINUE"; } else { gameOverText.color = new Color32(0, 204, 0, 255); gameOverText.text = "LEVEL COMPLETED"; tapToStartText.text = "TAP TO CONTINUE"; } PauseUI.SetActive(true); Time.timeScale = 0f; } public void BirdDied() { levelText.SetActive(false); Bird.gameStatus = Bird.GameStatus.DEAD; Levels.UpgradeLevel(); } }
namespace Funding.Data { using Funding.Data.Builder; using Funding.Data.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class FundingDbContext : IdentityDbContext<User> { public FundingDbContext(DbContextOptions<FundingDbContext> options) : base(options) { } public DbSet<Message> Messages { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<ProjectsTags> ProjectTags { get; set; } public DbSet<Backers> Backers { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<SearchHistory> Searches { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.UserBuilder(); builder.ProjectBuilder(); builder.MappingTablesBuilder(); base.OnModelCreating(builder); } } }
using System; namespace TableProjectRepetition { class MainClass { /* * The Project name: * TableProjectRepetition * * This file is created only to repeat impressions of the last few lessons. Main TOPICS: * 1. Arrays * 2. Strings * 3. Strings as an arrays * 4. Two dimention arrays (also known as tables - this gave us name of the project) */ public static void Main(string[] args) { Console.WriteLine("Hi! This is TableProjectRepetition, the work file for some features to be re-regard."); Console.WriteLine("\n\n\n"); Console.WriteLine("1. Split and Parse in strings (arrays): "); Console.WriteLine("\n"); Console.WriteLine("Let us assume row[] is 1-dimentional string with value as follows: \n 1,2,3,4,5,6,7,8,9"); Console.WriteLine("The task is to replace it with 1;2;3;4;5;6;7;8;9 i.e. to move commas to semi-colons \n"); // init the array: Define it with string, using commas as a separator Console.WriteLine("\n\n First of all, lets init the variable: \n string parse = 1,2,3,4,5,6,7,8,9 \n\n"); // use Split to divide the string above to array of symbols 1 2 3 4 5 6 7 8 9 Console.WriteLine("divide the string above to array of symbols 1 2 3 4 5 6 7 8 9"); Console.WriteLine(" Use \n string[] parse = \"1,2,3,4,5,6,7,8,9\".Split(','); \n to do that: \n\n"); string[] parse = "1,2,3,4,5,6,7,8,9".Split(','); // use Lenght - Console.WriteLine("The defined string is " + parse.Length + " - characters long. \n This is also called Power of the array/string... \n\n" ); // replace commas w. semi-colons: string list1 = String.Join(";", parse); Console.WriteLine("And here is the string (preformatted): " + list1 + "\n\n\n\n" ); } } }
using CustomerService.Utils.Helpers; using System.Web.Http; using Teste_CRUD_CiaTecnica.Application; using Teste_CRUD_CiaTecnica.Application.Interfaces; using Teste_CRUD_CiaTecnica.Domain.Interfaces.Repositories; using Teste_CRUD_CiaTecnica.Domain.Interfaces.Services; using Teste_CRUD_CiaTecnica.Domain.Services; using Teste_CRUD_CiaTecnica.Infra.Data.Repositories; using Unity; using Unity.Lifetime; namespace Teste_CRUD_CiaTecnica.Presentation.MVC { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // DI var container = new UnityContainer(); container.RegisterType(typeof(IRepositoryBase<>), typeof(RepositoryBase<>), new HierarchicalLifetimeManager()); container.RegisterType<IPessoaRepository, PessoaRepository>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaFisicaRepository, PessoaFisicaRepository>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaJuridicaRepository, PessoaJuridicaRepository>(new HierarchicalLifetimeManager()); container.RegisterType(typeof(IServiceBase<>), typeof(ServiceBase<>), new HierarchicalLifetimeManager()); container.RegisterType<IPessoaService, PessoaService>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaFisicaService, PessoaFisicaService>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaJuridicaService, PessoaJuridicaService>(new HierarchicalLifetimeManager()); container.RegisterType(typeof(IAppServiceBase<>), typeof(AppServiceBase<>), new HierarchicalLifetimeManager()); container.RegisterType<IPessoaAppService, PessoaAppService>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaFisicaAppService, PessoaFisicaAppService>(new HierarchicalLifetimeManager()); container.RegisterType<IPessoaJuridicaAppService, PessoaJuridicaAppService>(new HierarchicalLifetimeManager()); config.DependencyResolver = new UnityResolver(container); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
using HastaOtomasyonLib; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Windows.Forms; namespace HastaneOtomasyonu { public partial class HastaGüncellemeForm : BaseForm { public HastaGüncellemeForm() { InitializeComponent(); } public List<Hasta> Hastalar { get; set; } Hasta seciliHasta = new Hasta(); private void btnKaydet_Click(object sender, EventArgs e) { try { Hasta yeniHasta = new Hasta() { Ad = txtAd.Text, Soyad = txtSoyad.Text, DogumTarihi = dtpDogumTarihi.Value, Cinsiyet = (Cinsiyetler)(Enum.Parse(typeof(Cinsiyetler), cmbCinsiyet.SelectedItem.ToString())), Telefon = txtTelefon.Text }; Hastalar.Add(yeniHasta); FormuTemizle(); ListeyiDoldur(); MessageBox.Show("Hasta Kaydı başarıyla eklendi.","Hasta Kaydetme",MessageBoxButtons.OK,MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ListeyiDoldur() { lstListe.Items.Clear(); foreach (Hasta item in Hastalar) { lstListe.Items.Add(item); } } private void btnGuncelle_Click(object sender, EventArgs e) { if (seciliHasta == null) { MessageBox.Show("Güncellemek için hasta seçmelisiniz!"); return; } DialogResult cevap = MessageBox.Show($"{seciliHasta.Ad} adlı hastayı güncellemek üzeresiniz! Devam etmek istiyor musunuz?", "Kişi Güncelleme", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (cevap == DialogResult.Yes) { try { seciliHasta = Hastalar.Where(item => item.TCKN == seciliHasta.TCKN).FirstOrDefault(); seciliHasta.Ad = txtAd.Text; seciliHasta.Soyad = txtSoyad.Text; seciliHasta.DogumTarihi = dtpDogumTarihi.Value; seciliHasta.Cinsiyet = (Cinsiyetler)Enum.Parse(typeof(Cinsiyetler), cmbCinsiyet.SelectedItem.ToString()); seciliHasta.Telefon = txtTelefon.Text; FormuTemizle(); ListeyiDoldur(); seciliHasta = null; MessageBox.Show("Güncelleme başarıyla gerçekleşti","Güncelleme başarılı", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void lstListe_SelectedIndexChanged(object sender, EventArgs e) { if (lstListe.SelectedIndex == -1) return; seciliHasta = lstListe.SelectedItem as Hasta; txtAd.Text = seciliHasta.Ad; dtpDogumTarihi.Value = seciliHasta.DogumTarihi; txtSoyad.Text = seciliHasta.Soyad; cmbCinsiyet.SelectedIndex = (int)seciliHasta.Cinsiyet; txtTelefon.Text = seciliHasta.Telefon; } private void btnSil_Click(object sender, EventArgs e) { if (seciliHasta == null) { MessageBox.Show("Silmek için hasta seçmediniz!"); return; } seciliHasta = (Hasta)lstListe.SelectedItem; DialogResult cevap = MessageBox.Show($"{ seciliHasta.Ad} adlı hastayı silmek istiyor musunuz?", "Öğrenci Silme", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (cevap == DialogResult.Yes) { Hastalar.Remove(seciliHasta); ListeyiDoldur(); seciliHasta = null; MessageBox.Show("Öğrenci başarıyla silindi"); } } private void txtArama_TextChanged(object sender, EventArgs e) { List<Hasta> aramaSonucu = Methods.Ara(Hastalar, txtArama.Text); ListeyiDoldur(aramaSonucu); } private void ListeyiDoldur(List<Hasta> aramaSonucu) { lstListe.Items.Clear(); foreach (Hasta item in aramaSonucu) { lstListe.Items.Add(item); } } private void HastaKayıtForm_Load(object sender, EventArgs e) { cmbCinsiyet.Items.AddRange(Enum.GetNames(typeof(Cinsiyetler))); ListeyiDoldur(); } } }
namespace CheckIt.ObjectsFinder { using System.Collections.Generic; using System.Linq; using CheckIt.Syntax; internal class ReferencesObjectsFinder : IObjectsFinder { private readonly IEnumerable<IReference> checkReferences; public ReferencesObjectsFinder(IEnumerable<IReference> checkReferences) { this.checkReferences = checkReferences; } public IObjectsFinder Class(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder Reference(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder Assembly(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder File(string pattern, bool invert) { throw new System.NotImplementedException(); } public IObjectsFinder Interfaces(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder Method(string pattern) { throw new System.NotImplementedException(); } public List<T> ToList<T>() { return this.checkReferences.Cast<T>().ToList(); } public IObjectsFinder Project(string pattern, bool invert) { throw new System.NotImplementedException(); } } }
namespace CheckIt.ObjectsFinder { using System.Collections.Generic; using System.Linq; using CheckIt.Syntax; internal class AssembliesObjectsFinder : IObjectsFinder { private readonly IEnumerable<IAssembly> checkAssemblies; public AssembliesObjectsFinder(IEnumerable<IAssembly> checkAssemblies) { this.checkAssemblies = checkAssemblies; } public IObjectsFinder Interfaces(string pattern) { return new InterfacesObjectsFinder(this.checkAssemblies.SelectMany(a => a.Interface(pattern))); } public IObjectsFinder Method(string pattern) { return new MethodsObjectsFinder(this.checkAssemblies.SelectMany(a => a.Method(pattern))); } public List<T> ToList<T>() { return this.checkAssemblies.Cast<T>().ToList(); } public IObjectsFinder Project(string pattern, bool invert) { throw new System.NotImplementedException(); } public IObjectsFinder Class(string pattern) { return new ClassesObjectsFinder(new CheckClasses(this.checkAssemblies.SelectMany(f => f.Class(pattern)))); } public IObjectsFinder Reference(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder Assembly(string pattern) { throw new System.NotImplementedException(); } public IObjectsFinder File(string pattern, bool invert) { throw new System.NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.MES { public class MesScanControlPointSearchModel : SearchModelBase { public string ControlPoint { get; set; } public string TraceCode { get; set; } } }