content
stringlengths
23
1.05M
// Copyright (c) Alessio Parma <alessio.parma@gmail.com>. All rights reserved. // // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System; using ShaiRandom.Generators; namespace ShaiRandom.Distributions { /// <summary> /// Abstract class which implements some features shared across all distributions. /// </summary> /// <remarks>The thread safety of this class depends on the one of the underlying generator.</remarks> [Serializable] public abstract class AbstractDistribution { /// <summary> /// Builds a distribution using given generator. /// </summary> /// <param name="generator">The generator that will be used by the distribution.</param> /// <exception cref="ArgumentNullException">Given generator is null.</exception> protected AbstractDistribution(IEnhancedRandom generator) { Generator = generator ?? throw new ArgumentNullException(nameof(generator), ErrorMessages.NullGenerator); } #region IDistribution members /// <summary> /// Gets the <see cref="IEnhancedRandom"/> object that is used as underlying random number generator. /// </summary> public IEnhancedRandom Generator { get; } #endregion IDistribution members } }
using Humanizer; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Threading.Tasks; namespace FluentlyHttpClient.Sample.Api.Controllers { public class UploadInput { [Required] public string Hero { get; set; } [Required] public IFormFile File { get; set; } } [Route("api/[controller]")] [ApiController] public class SampleController : ControllerBase { //private readonly FluentHttpClientDbContext _dbContext; public SampleController( //FluentHttpClientDbContext dbContext ) { //_dbContext = dbContext; } // GET api/values [HttpGet] public async Task<IEnumerable<string>> Get() { //await _dbContext.Initialize(); return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost("upload")] public IActionResult Upload([FromForm] UploadInput input) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var file = input.File; if (file.Length > 0) { using (var fileStream = new FileStream(file.FileName, FileMode.Create)) { file.CopyTo(fileStream); } } return Ok(new { input.Hero, file.FileName, file.ContentType, Size = file.Length.Bytes().Kilobytes }); } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
#if INCLUDE_PHYSICS using System.Collections.Generic; using UnityEngine; namespace Unity.RuntimeSceneSerialization.Internal { static class ColliderPropertyBagDefinition { [RuntimeInitializeOnLoadMethod] #if UNITY_EDITOR [UnityEditor.InitializeOnLoadMethod] #endif static void Initialize() { ReflectedPropertyBagUtils.SetIncludedProperties(typeof(Collider), new HashSet<string> { nameof(Collider.sharedMaterial) }); ReflectedPropertyBagUtils.SetIgnoredProperties(typeof(Collider), new HashSet<string> { nameof(Collider.contactOffset), nameof(Collider.material) }); ReflectedPropertyBagUtils.SetIncludedProperties(typeof(BoxCollider), new HashSet<string> { nameof(BoxCollider.center) }); ReflectedPropertyBagUtils.SetIncludedProperties(typeof(CapsuleCollider), new HashSet<string> { nameof(CapsuleCollider.center) }); ReflectedPropertyBagUtils.SetIncludedProperties(typeof(SphereCollider), new HashSet<string> { nameof(SphereCollider.center) }); } // Reference property getters and setters needed for serialization that may get stripped on AOT public static void Unused(CapsuleCollider collider) { collider.material = collider.material; collider.isTrigger = collider.isTrigger; collider.radius = collider.radius; collider.height = collider.height; collider.direction = collider.direction; collider.center = collider.center; } public static void Unused(BoxCollider collider) { collider.material = collider.material; collider.isTrigger = collider.isTrigger; collider.size = collider.size; collider.center = collider.center; } public static void Unused(MeshCollider collider) { collider.material = collider.material; collider.isTrigger = collider.isTrigger; collider.convex = collider.convex; collider.cookingOptions = collider.cookingOptions; collider.sharedMesh = collider.sharedMesh; } public static void Unused(SphereCollider collider) { collider.material = collider.material; collider.isTrigger = collider.isTrigger; collider.radius = collider.radius; collider.center = collider.center; } } } #endif
using UnityEngine; public class Fire : MonoBehaviour { public CircleCollider2D fireCollider; public GameObject explosion; public Vector2 offset; public Vector2 offset2; public Animator animator; // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)) { fireCollider.offset = offset2; fireCollider.radius = 2.5f; animator.SetBool("MousePressed", true); } if(Input.GetMouseButtonUp(0)) { fireCollider.offset = offset; fireCollider.radius = 5f; animator.SetBool("MousePressed", false); } } void OnTriggerEnter2D(Collider2D other) { if(other.gameObject.tag == "Enemy") { GameManager.currentEnemyCount = GameManager.currentEnemyCount - 1; Destroy(other.gameObject); GameObject expl = Instantiate(explosion, other.transform.position, Quaternion.identity) as GameObject; Destroy(expl, 1); } } }
// Copyright (c) MASA Stack All rights reserved. // Licensed under the Apache License. See LICENSE.txt in the project root for license information. namespace Masa.Auth.ApiGateways.Caller.Services.Permissions; public class PermissionService : ServiceBase { protected override string BaseUrl { get; set; } internal PermissionService(ICallerProvider callerProvider) : base(callerProvider) { BaseUrl = "api/permission"; } public async Task UpsertMenuPermissionAsync(MenuPermissionDetailDto dto) { await PostAsync($"CreateMenuPermission", dto); } public async Task UpsertApiPermissionAsync(ApiPermissionDetailDto dto) { await PostAsync($"CreateApiPermission", dto); } public async Task<List<SelectItemDto<PermissionTypes>>> GetTypesAsync() { return await GetAsync<List<SelectItemDto<PermissionTypes>>>($"GetTypes"); } public async Task<List<AppPermissionDto>> GetApplicationPermissionsAsync(string systemId) { return await GetAsync<List<AppPermissionDto>>($"GetApplicationPermissions?systemId={systemId}"); } public async Task<List<PermissionDto>> GetChildMenuPermissionsAsync(Guid permissionId) { return await GetAsync<List<PermissionDto>>($"GetChildMenuPermissions?permissionId={permissionId}"); } public async Task<MenuPermissionDetailDto> GetMenuPermissionDetailAsync(Guid id) { return await GetAsync<MenuPermissionDetailDto>($"GetMenuPermission?id={id}"); } public async Task<ApiPermissionDetailDto> GetApiPermissionDetailAsync(Guid id) { return await GetAsync<ApiPermissionDetailDto>($"GetApiPermission?id={id}"); } public async Task<List<SelectItemDto<Guid>>> GetApiPermissionSelectAsync(string name) { return await GetAsync<List<SelectItemDto<Guid>>>($"GetApiPermissionSelect?name={name}"); } public async Task RemoveAsync(Guid permissionId) { await DeleteAsync($"Delete?id={permissionId}"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using EcsRx.Collections.Entity; using EcsRx.Entities; using EcsRx.Events.Collections; using EcsRx.Extensions; using EcsRx.Groups.Observable; using NSubstitute; using Xunit; namespace EcsRx.Tests.EcsRx.Observables { public class ObservableGroupTests { [Fact] public void should_include_entity_snapshot_on_creation() { var mockCollectionNotifier = Substitute.For<INotifyingEntityCollection>(); var accessorToken = new ObservableGroupToken(new[]{1}, new int[0], 0); var applicableEntity1 = Substitute.For<IEntity>(); var applicableEntity2 = Substitute.For<IEntity>(); var notApplicableEntity1 = Substitute.For<IEntity>(); applicableEntity1.Id.Returns(1); applicableEntity2.Id.Returns(2); notApplicableEntity1.Id.Returns(3); applicableEntity1.HasComponent(Arg.Any<int>()).Returns(true); applicableEntity2.HasComponent(Arg.Any<int>()).Returns(true); notApplicableEntity1.HasComponent(Arg.Any<int>()).Returns(false); var dummyEntitySnapshot = new List<IEntity> { applicableEntity1, applicableEntity2, notApplicableEntity1 }; mockCollectionNotifier.EntityAdded.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityRemoved.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityComponentsAdded.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoving.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoved.Returns(Observable.Empty<ComponentsChangedEvent>()); var observableGroup = new ObservableGroup(accessorToken, dummyEntitySnapshot, new []{mockCollectionNotifier}); Assert.Equal(2, observableGroup.CachedEntities.Count); Assert.Contains(applicableEntity1, observableGroup.CachedEntities); Assert.Contains(applicableEntity2, observableGroup.CachedEntities); } [Fact] public void should_add_entity_and_raise_event_when_applicable_entity_added() { var collectionId = 1; var accessorToken = new ObservableGroupToken(new[] { 1,2 }, new int[0], collectionId); var mockCollection = Substitute.For<IEntityCollection>(); mockCollection.Id.Returns(collectionId); var applicableEntity = Substitute.For<IEntity>(); applicableEntity.Id.Returns(1); applicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.RequiredComponents.Contains(x))).Returns(true); var unapplicableEntity = Substitute.For<IEntity>(); unapplicableEntity.Id.Returns(2); unapplicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.RequiredComponents.Contains(x))).Returns(false); var mockCollectionNotifier = Substitute.For<INotifyingEntityCollection>(); var entityAddedSub = new Subject<CollectionEntityEvent>(); mockCollectionNotifier.EntityAdded.Returns(entityAddedSub); mockCollectionNotifier.EntityRemoved.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityComponentsAdded.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoving.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoved.Returns(Observable.Empty<ComponentsChangedEvent>()); var observableGroup = new ObservableGroup(accessorToken, new IEntity[0], new []{mockCollectionNotifier}); var wasCalled = 0; observableGroup.OnEntityAdded.Subscribe(x => wasCalled++); entityAddedSub.OnNext(new CollectionEntityEvent(unapplicableEntity)); Assert.Empty(observableGroup.CachedEntities); entityAddedSub.OnNext(new CollectionEntityEvent(applicableEntity)); Assert.Equal(1, observableGroup.CachedEntities.Count); Assert.Equal(applicableEntity, observableGroup.CachedEntities[applicableEntity.Id]); Assert.Equal(1, wasCalled); } [Fact] public void should_add_entity_and_raise_event_when_components_match_group() { var collectionId = 1; var accessorToken = new ObservableGroupToken(new[] { 1 }, new []{ 2 }, collectionId); var mockCollection = Substitute.For<IEntityCollection>(); mockCollection.Id.Returns(collectionId); var applicableEntity = Substitute.For<IEntity>(); applicableEntity.Id.Returns(1); var mockCollectionNotifier = Substitute.For<INotifyingEntityCollection>(); var componentRemoved = new Subject<ComponentsChangedEvent>(); mockCollectionNotifier.EntityAdded.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityRemoved.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityComponentsAdded.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoving.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoved.Returns(componentRemoved); var observableGroup = new ObservableGroup(accessorToken, new IEntity[0], new []{mockCollectionNotifier}); var wasCalled = 0; observableGroup.OnEntityAdded.Subscribe(x => wasCalled++); applicableEntity.HasAllComponents(accessorToken.LookupGroup.RequiredComponents).Returns(true); applicableEntity.HasAnyComponents(accessorToken.LookupGroup.ExcludedComponents).Returns(false); componentRemoved.OnNext(new ComponentsChangedEvent(applicableEntity, null)); Assert.Contains(applicableEntity, observableGroup.CachedEntities); Assert.Equal(1, wasCalled); } [Fact] public void should_remove_entity_and_raise_events_when_entity_removed_with_components() { var collectionId = 1; var accessorToken = new ObservableGroupToken(new[] { 1, 2 }, new int[0], collectionId); var mockCollection = Substitute.For<IEntityCollection>(); mockCollection.Id.Returns(collectionId); var applicableEntity = Substitute.For<IEntity>(); applicableEntity.Id.Returns(1); applicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.RequiredComponents.Contains(x))).Returns(true); applicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.ExcludedComponents.Contains(x))).Returns(false); var mockCollectionNotifier = Substitute.For<INotifyingEntityCollection>(); var entityRemoved = new Subject<CollectionEntityEvent>(); var componentRemoving = new Subject<ComponentsChangedEvent>(); mockCollectionNotifier.EntityRemoved.Returns(entityRemoved); mockCollectionNotifier.EntityAdded.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityComponentsAdded.Returns(Observable.Empty<ComponentsChangedEvent>()); mockCollectionNotifier.EntityComponentsRemoving.Returns(componentRemoving); mockCollectionNotifier.EntityComponentsRemoved.Returns(Observable.Empty<ComponentsChangedEvent>()); var observableGroup = new ObservableGroup(accessorToken, new[]{applicableEntity}, new []{mockCollectionNotifier}); var wasRemovingCalled = 0; observableGroup.OnEntityRemoving.Subscribe(x => wasRemovingCalled++); var wasRemovedCalled = 0; observableGroup.OnEntityRemoved.Subscribe(x => wasRemovedCalled++); componentRemoving.OnNext(new ComponentsChangedEvent(applicableEntity, new[]{1})); Assert.Contains(applicableEntity, observableGroup.CachedEntities); Assert.Equal(1, wasRemovingCalled); Assert.Equal(0, wasRemovedCalled); wasRemovingCalled = wasRemovedCalled = 0; entityRemoved.OnNext(new CollectionEntityEvent(applicableEntity)); Assert.DoesNotContain(applicableEntity, observableGroup.CachedEntities); Assert.Equal(0, wasRemovingCalled); Assert.Equal(1, wasRemovedCalled); } [Fact] public void should_remove_entity_and_raise_event_when_no_longer_matches_group() { var collectionId = 1; var accessorToken = new ObservableGroupToken(new[] { 1,2 }, new int[0], collectionId); var mockCollection = Substitute.For<IEntityCollection>(); mockCollection.Id.Returns(collectionId); var applicableEntity = Substitute.For<IEntity>(); applicableEntity.Id.Returns(1); applicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.RequiredComponents.Contains(x))).Returns(true); applicableEntity.HasComponent(Arg.Is<int>(x => accessorToken.LookupGroup.ExcludedComponents.Contains(x))).Returns(false); var mockCollectionNotifier = Substitute.For<INotifyingEntityCollection>(); var componentRemoving = new Subject<ComponentsChangedEvent>(); mockCollectionNotifier.EntityComponentsRemoving.Returns(componentRemoving); var componentRemoved = new Subject<ComponentsChangedEvent>(); mockCollectionNotifier.EntityComponentsRemoved.Returns(componentRemoved); mockCollectionNotifier.EntityAdded.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityRemoved.Returns(Observable.Empty<CollectionEntityEvent>()); mockCollectionNotifier.EntityComponentsAdded.Returns(Observable.Empty<ComponentsChangedEvent>()); var observableGroup = new ObservableGroup(accessorToken, new[]{applicableEntity}, new []{mockCollectionNotifier}); var wasRemovingCalled = 0; observableGroup.OnEntityRemoving.Subscribe(x => wasRemovingCalled++); var wasRemovedCalled = 0; observableGroup.OnEntityRemoved.Subscribe(x => wasRemovedCalled++); applicableEntity.HasAnyComponents(accessorToken.LookupGroup.RequiredComponents).Returns(false); applicableEntity.HasAllComponents(accessorToken.LookupGroup.RequiredComponents).Returns(false); componentRemoving.OnNext(new ComponentsChangedEvent(applicableEntity, new[]{ 1 })); componentRemoved.OnNext(new ComponentsChangedEvent(applicableEntity, new[]{ 1 })); Assert.DoesNotContain(applicableEntity, observableGroup.CachedEntities); Assert.Equal(1, wasRemovingCalled); Assert.Equal(1, wasRemovedCalled); } } }
using System; using System.Threading.Tasks; using E247.Fun; using E247.Fun.Exceptions; using Ploeh.AutoFixture.Xunit2; using Xunit; using Xunit.Extensions; using static E247.Fun.Fun; namespace E247.Fun.UnitTest { public class MaybeTests { [Fact] public void EmptyMaybeHasNoValue() { var actual = Maybe<string>.Empty(); Assert.False(actual.HasValue); Assert.False(actual.Any()); Assert.Throws<EmptyMaybeException>(() => actual.Value); } [Fact] public void MaybeWithNullHasNoValue() { var actual = new Maybe<string>(null); Assert.False(actual.HasValue); Assert.False(actual.Any()); Assert.Throws<EmptyMaybeException>(() => actual.Value); } [Theory, AutoData] public void MaybeWithValueHasValue(string input) { var actual = new Maybe<string>(input); Assert.True(actual.HasValue); Assert.True(actual.Any()); Assert.Equal(input, actual.Value); } [Theory, AutoData] public void CanImplicitlyReturnMaybe(string input) { Func<Maybe<string>> test = () => input; Assert.IsType<Maybe<string>>(test()); } [Theory, AutoData] public void ToMaybeReturnsMaybe(string input) { var actual = input.ToMaybe(); Assert.IsType<Maybe<string>>(actual); } [Theory, AutoData] public void MatchCallsSomeForMaybeWithValue(string input) { var maybeInput = input.ToMaybe(); var result = maybeInput.Match<string, int>( Some: _ => 1, None: () => 0); Assert.Equal(1, result); } [Fact] public void MatchCallsNoneForEmptyMaybe() { var maybe = Maybe<string>.Empty(); var result = maybe.Match( Some: _ => 1, None: () => 0); Assert.Equal(0, result); } [Theory, AutoData] public async Task MatchAsyncCallsSomeForMaybeWithValue(string input) { var maybeInput = input.ToMaybe(); var result = await maybeInput.MatchAsync( Some: _ => Task.FromResult(1), None: () => Task.FromResult(0)); Assert.Equal(1, result); } [Fact] public async Task MatchAsyncCallsNoneForEmptyMaybe() { var maybe = Maybe<string>.Empty(); var result = await maybe.MatchAsync( Some: _ => Task.FromResult(1), None: () => Task.FromResult(0)); Assert.Equal(0, result); } [Theory, AutoData] public async Task MatchAsyncWithSynchronousNoneCallsSomeForMaybeWithValue( string input) { var maybeInput = input.ToMaybe(); var result = await maybeInput.MatchAsync( Some: _ => Task.FromResult(1), None: () => 0); Assert.Equal(1, result); } [Fact] public async Task MatchAsyncWithSynchronousNoneCallsNoneForEmptyMaybe() { var maybe = Maybe<string>.Empty(); var result = await maybe.MatchAsync( Some: _ => Task.FromResult(1), None: () => 0); Assert.Equal(0, result); } [Theory, AutoData] public void MatchCallsActionSomeForMaybeWithValue( string input, string noneSideEffect) { var maybeInput = input.ToMaybe(); var target = "42"; var result = maybeInput.Match( Some: value => { target = value; }, None: () => { target = noneSideEffect; }); Assert.Equal(input, target); } [Theory, AutoData] public void MatchCallsActionNoneForMaybeWithoutValue( string input, string noneSideEffect) { var maybeInput = Maybe<string>.Empty(); var target = "42"; var result = maybeInput.Match( Some: value => { target = value; }, None: () => { target = noneSideEffect; }); Assert.Equal(noneSideEffect, target); } [Theory, AutoData] public async Task MatchAsyncCallsActionSomeForMaybeWithValue( string input, string noneSideEffect) { var maybeInput = input.ToMaybe(); var target = "42"; var result = await maybeInput.MatchAsync( Some: async value => { target = await Task.FromResult(value); }, None: async () => { target = await Task.FromResult(noneSideEffect); }); Assert.Equal(input, target); } [Theory, AutoData] public async Task MatchAsyncCallsActionNoneForMaybeWithoutValue( string input, string noneSideEffect) { var maybeInput = Maybe<string>.Empty(); var target = "42"; var result = await maybeInput.MatchAsync( Some: async value => { target = await Task.FromResult(value); }, None: async () => { target = await Task.FromResult(noneSideEffect); }); Assert.Equal(noneSideEffect, target); } [Theory, AutoData] public void MaybeWithValueIsEqualToValue(string input) { var maybe = input.ToMaybe(); Assert.Equal(input, maybe); } [Theory, AutoData] public void EmptyMaybeIsNotEqualToValue(string input) { var maybe = Maybe<string>.Empty(); Assert.NotEqual(input, maybe); } [Theory, AutoData] public void MaybeWithValueIsNotEqualToDifferentValue( string input, string other) { var maybe = input.ToMaybe(); Assert.NotEqual(input, other); Assert.NotEqual(other, maybe); } [Theory, AutoData] public void MapMapsAFunction(string input) { var maybe = input.ToMaybe(); var actual = maybe .Map(v => v.Length); Assert.Equal(input.Length, actual.Value); } [Fact] public void MapMapsEmptyToEmpty() { var maybe = Maybe<string>.Empty(); var actual = maybe .Map(v => v.Length); Assert.False(actual.HasValue); } [Theory, AutoData] public async Task MapAsyncMapsAFunction(string input) { var maybe = input.ToMaybe(); var actual = await maybe .MapAsync(v => Task.FromResult(v.Length)); Assert.Equal(input.Length, actual.Value); } [Fact] public async Task MapAsyncMapsEmptyToEmpty() { var maybe = Maybe<string>.Empty(); var actual = await maybe .MapAsync(v => Task.FromResult(v.Length)); Assert.False(actual.HasValue); } [Theory, AutoData] public void TeeMapWithNonEmptyMaybe(object input) { var actionCalled = false; Action<object> someAdhocAction = (object str) => { actionCalled = true; }; input .ToMaybe() .TeeMap(someAdhocAction); Assert.True(actionCalled); } [Fact] public void TeeMapWithEmptyMaybe() { var actionCalled = false; Action<object> someAdhocAction = (object str) => { actionCalled = true; }; object nullValue = null; nullValue.ToMaybe() .TeeMap(someAdhocAction); Assert.False(actionCalled); } [Theory, AutoData] public void TeeMapDoesNotChangeMaybe(object input) { var maybeValue = input.ToMaybe(); Action<object> potentiallyHarmfullAction = (object param) => { param = new object(); }; var actual = maybeValue.TeeMap(potentiallyHarmfullAction); Assert.Equal(maybeValue, actual); Assert.Equal(maybeValue.Value, actual.Value); } [Theory, AutoData] public void SelectManyLetsUsUseWeirdSyntax(string input1, string input2) { var actual = from a in input1.ToMaybe() from b in input2.ToMaybe() select $"Actual values: {a} {b}"; Assert.True(actual.HasValue); Assert.Contains(input1, actual.Value); Assert.Contains(input2, actual.Value); } [Theory, AutoData] public void SelectManyLetsUsUseWeirdSyntaxWithEmptyMaybes( string input1, string input2) { var actual = from a in input1.ToMaybe() from b in input2.ToMaybe() from c in Maybe<string>.Empty() select $"Actual values: {a} {b} {c}"; Assert.False(actual.HasValue); } [Theory, AutoData] public async Task AsyncSelectManyWorks( string input1, string input2) { var taskInput1 = Task.FromResult(input1.ToMaybe()); var taskInput2 = Task.FromResult(input2.ToMaybe()); var actual = await from a in taskInput1 from b in taskInput2 select $"Actual values: {a} {b}"; Assert.True(actual.HasValue); Assert.Contains(input1, actual.Value); Assert.Contains(input2, actual.Value); } [Theory, AutoData] public async Task AsyncSelectManyWorksWithNonAsyncsToo( string input1, string input2) { var taskInput1 = Task.FromResult(input1.ToMaybe()); var actual = await from a in taskInput1 from b in input2.ToMaybe() select $"Actual values: {a} {b}"; Assert.True(actual.HasValue); Assert.Contains(input1, actual.Value); Assert.Contains(input2, actual.Value); } [Theory, AutoData] public async Task SomeCrazyQueryComprehensionStuff( string input1, string input2) { var taskInput1 = Task.FromResult(input1.ToMaybe()); var actual = await from a in taskInput1 from b in input2.ToMaybe() let c = a.Length + 1 let d = b.Length where c > d select $"Actual values: {a} {b}"; Assert.True(actual.HasValue); Assert.Contains(input1, actual.Value); Assert.Contains(input2, actual.Value); } [Theory, AutoData] public async Task AsyncTeeMapWithNonEmptyMaybe(object input) { var actionCalled = false; Action<object> someAdhocAction = (object str) => { actionCalled = true; }; var asyncMaybe = Task.FromResult(input.ToMaybe()); var actual = await asyncMaybe.TeeMap(someAdhocAction); Assert.True(actionCalled); Assert.Equal((await asyncMaybe), actual); } [Fact] public async Task AsyncTeeMapWithEmptyMaybe() { var actionCalled = false; Action<object> someAdhocAction = (object str) => { actionCalled = true; }; var asyncMaybe = Task.FromResult(Maybe<string>.Empty()); var actual = await asyncMaybe.TeeMap(someAdhocAction); Assert.False(actionCalled); Assert.Equal((await asyncMaybe), actual); } [Theory, AutoData] public void ApplyIsTheSameAsJustCallingFunctionsWithValues(int input) { var func = Func((int i) => i + 1); var expected = func(input); var maybeFunc = func.ToMaybe(); var actual = maybeFunc.Apply(input.ToMaybe()); Assert.True(actual.HasValue); Assert.Equal(expected, actual); } [Theory, AutoData] public void LiftAndApplyAreCoolAndGood(int i1, int i2) { var func = Func((int i, int j) => i + j + 1); var expected = func(i1, i2); var actual = func.Curry() .Lift(i1.ToMaybe()) .Apply(i2.ToMaybe()); Assert.True(actual.HasValue); Assert.Equal(expected, actual.Value); } [Theory, AutoData] public async Task LiftAndApplyAsyncAreCoolAndGood(int i1, int i2) { var func = Func((int i, int j) => i + j + 1); var expected = func(i1, i2); var input1 = Task.FromResult(i1.ToMaybe()); var input2 = Task.FromResult(i2.ToMaybe()); var actual = await func.Curry() .LiftAsync(input1) .ApplyAsync(input2); Assert.True(actual.HasValue); Assert.Equal(expected, actual.Value); } } }
using LogJoint.Analytics.Correlation.Solver; namespace LogJoint.Analytics.Correlation { public static class SolverFactory { public static ISolver Create() { #if WIN return new Analytics.Correlation.EmbeddedSolver.EmbeddedSolver(); #elif MONOMAC return new Analytics.Correlation.ExternalSolver.CmdLineToolProxy(); #else #error "Unsupported platform" #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Engine.Saving.XMLSaver { abstract class XmlValue<T> : ValueWriterEntry, XmlValueReader { protected const String NAME_ENTRY = "name"; protected String elementName; protected XmlSaver xmlSaver; public XmlValue(XmlSaver xmlSaver, String elementName) { this.xmlSaver = xmlSaver; this.elementName = elementName; } public virtual void writeValue(SaveEntry entry) { XmlWriter xmlWriter = xmlSaver.XmlWriter; xmlWriter.WriteStartElement(elementName); xmlWriter.WriteAttributeString(NAME_ENTRY, entry.Name); if (entry.Value != null) { xmlWriter.WriteString(valueToString((T)entry.Value)); } xmlWriter.WriteEndElement(); } public abstract String valueToString(T value); public virtual void readValue(LoadControl loadControl, XmlReader xmlReader) { loadControl.addValue(xmlReader.GetAttribute(NAME_ENTRY), parseValue(xmlReader), typeof(T)); } public abstract T parseValue(XmlReader xmlReader); public String ElementName { get { return elementName; } } public Type getWriteType() { return typeof(T); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using Blumind.Controls; using Blumind.Controls.MapViews; using Blumind.Core; using Blumind.Model.Documents; using Blumind.Model.MindMaps; namespace Blumind.Core.Exports { abstract class ImageExportEngine : ChartsExportEngine { protected abstract void SaveImage(Image image, string filename); protected override bool ExportChartToFile(Document document, ChartPage chart, string filename) { if (chart == null) throw new ArgumentNullException(); if (string.IsNullOrEmpty(filename)) throw new ArgumentException("filename"); if (!OptionsInitalizated && !GetOptions()) return false; //ChartPage = chart; //chart.EnsureChartLayouted(); Size contentSize = chart.GetContentSize(); if (contentSize.Width <= 0 || contentSize.Height <= 0) return false; Bitmap bmp = new Bitmap(contentSize.Width, contentSize.Height); using (Graphics grf = Graphics.FromImage(bmp)) { PaintHelper.SetHighQualityRender(grf); if (!TransparentBackground) { grf.Clear(chart.BackColor); } var render = new GeneralRender(); var args = new RenderArgs(RenderMode.Export, grf, (MindMap)chart, ChartBox.DefaultChartFont); render.Paint((MindMap)chart, args); } SaveImage(bmp, filename); return true; } } }
namespace ValidCode { using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; [ApiController] public class OrdersController : Controller { private readonly Db db; public OrdersController(Db db) { this.db = db; } [HttpGet("api/orders/{id}")] public async Task<IActionResult> GetOrder([FromRoute]int id) { var match = await this.db.Orders.FirstOrDefaultAsync(x => x.Id == id); if (match == null) { return this.NotFound(); } return this.Ok(match); } } }
using System; using System.Collections.Generic; using System.Text; namespace SingleAgenda.Application.Base { public interface IBusiness { } }
using GalaxyZooTouchTable.Lib; using GalaxyZooTouchTable.Services; using GalaxyZooTouchTable.ViewModels; using System; namespace GalaxyZooTouchTable.Models { public class ClassificationPanelViewModelFactory : IClassificationPanelViewModelFactory { private ILocalDBService _localDBService; private IGraphQLService _graphQLService; public ClassificationPanelViewModelFactory(IGraphQLService graphQLService, ILocalDBService localDBService) { if (graphQLService == null || localDBService == null) { throw new ArgumentNullException("RepoDependency"); } _localDBService = localDBService; _graphQLService = graphQLService; } public ClassificationPanelViewModel Create(UserType type) { TableUser User = AssignUser(type); return new ClassificationPanelViewModel(new PanoptesService(_localDBService), _localDBService, User); } private TableUser AssignUser(UserType type) { switch (type) { case UserType.Purple: return GlobalData.GetInstance().PurpleUser; case UserType.Blue: return GlobalData.GetInstance().BlueUser; case UserType.Green: return GlobalData.GetInstance().GreenUser; case UserType.Aqua: return GlobalData.GetInstance().AquaUser; case UserType.Peach: return GlobalData.GetInstance().PeachUser; case UserType.Pink: return GlobalData.GetInstance().PinkUser; default: return GlobalData.GetInstance().PinkUser; } } } }
namespace Domain.Security { using Domain.Customers.ValueObjects; using Domain.Security.ValueObjects; public abstract class User : IUser { public ExternalUserId ExternalUserId { get; set; } public CustomerId CustomerId { get; set; } } }
using Application.Common.Mappings.Interfaces; using Application.Identity.Entities; using AutoMapper; namespace Application.CQRS.Roles.Models { public class RoleDto : IMapFrom<ApplicationRole> { #region Properties public string RoleId { get; set; } public string Name { get; set; } #endregion #region IMapFrom<ApplicationRole> public void MapUsingProfile(Profile profile) { profile.CreateMap<ApplicationRole, RoleDto>() .ForMember ( x => x.RoleId, opts => opts.MapFrom(x => x.Id) ); } #endregion } }
@model WebMarket.Models.Cliente <br /> <div class="register"> <form method="post" action="@Url.Action("RegistrarCliente","Home")"> <div class="register-top-grid"> <h3>INFORMACION PERSONAL</h3> <div> <span>Nombre<label>*</label></span> <input type="text" name="nombres" value="@Model.Nombres" disabled > </div> <div> <span>Apellidos<label>*</label></span> <input type="text" name="apellidos" value="@Model.Apellidos" disabled> </div> <div> <span>Email <label>*</label></span> <input type="text" name="correo" value="@Model.Correo" disabled> </div> <div> <span>Celular<label>*</label></span> <input type="text" name="celular" value="@Model.Celular" disabled> </div> <div> <span>Dirección<label>*</label></span> <input type="text" name="direccion" value="@Model.Direccion" disabled> </div> <div> <a href="@Url.Action("Paso02","Compra")" class="btn btn-primary higher bold">CONTINUAR</a> </div> </div> <div class="clearfix"> </div> </form> </div>
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DesignPatterns.ObjectPool{ public class Client : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.G)) { GameObject walker = ObjectPool.Instance.PullObject("Walker"); walker.transform.Translate(Vector3.forward * Random.Range(-5.0f, 5.0f)); walker.transform.Translate(Vector3.right * Random.Range(-5.0f, 5.0f)); } if (Input.GetKeyDown(KeyCode.P)) { object[] objs = GameObject.FindObjectsOfType(typeof(GameObject)); foreach (object o in objs) { GameObject obj = (GameObject)o; if (obj.gameObject.GetComponent<Walker>() != null) { ObjectPool.Instance.PoolObject(obj); } } } } } }
@using Data.Models; @model FeedModel @{ ViewBag.Title = Model.Title; } @Model.Html
namespace BusinessLayer { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using BusinessLayer.CrossCuttingConcerns; using Contract; using SimpleInjector; // This class allows registering all types that are defined in the business layer, and are shared across // all applications that use this layer (WCF and Web API). For simplicity, this class is placed inside // this assembly, but this does couple the business layer assembly to the used container. If this is a // concern, create a specific BusinessLayer.Bootstrap project with this class. public static class BusinessLayerBootstrapper { private static Assembly[] contractAssemblies = new[] { typeof(IQuery<>).Assembly }; private static Assembly[] businessLayerAssemblies = new[] { Assembly.GetExecutingAssembly() }; public static void Bootstrap(Container container) { if (container == null) { throw new ArgumentNullException(nameof(container)); } container.RegisterSingleton<IValidator>(new DataAnnotationsValidator(container)); container.Register(typeof(ICommandHandler<>), businessLayerAssemblies); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>)); container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuthorizationCommandHandlerDecorator<>)); container.Register(typeof(IQueryHandler<,>), businessLayerAssemblies); container.RegisterDecorator(typeof(IQueryHandler<,>), typeof(AuthorizationQueryHandlerDecorator<,>)); } public static IEnumerable<Type> GetCommandTypes() => from assembly in contractAssemblies from type in assembly.GetExportedTypes() where type.Name.EndsWith("Command") select type; public static IEnumerable<QueryInfo> GetQueryTypes() => from assembly in contractAssemblies from type in assembly.GetExportedTypes() where QueryInfo.IsQuery(type) select new QueryInfo(type); } [DebuggerDisplay("{QueryType.Name,nq}")] public sealed class QueryInfo { public readonly Type QueryType; public readonly Type ResultType; public QueryInfo(Type queryType) { this.QueryType = queryType; this.ResultType = DetermineResultTypes(queryType).Single(); } public static bool IsQuery(Type type) => DetermineResultTypes(type).Any(); private static IEnumerable<Type> DetermineResultTypes(Type type) => from interfaceType in type.GetInterfaces() where interfaceType.IsGenericType where interfaceType.GetGenericTypeDefinition() == typeof(IQuery<>) select interfaceType.GetGenericArguments()[0]; } }
using Surging.Core.Domain.Entities; namespace Surging.Debug.Test1.Domain.Demo.Entities { public class DemoEntity : Entity<string> { public string Filed1 { get; set; } } }
using System.Collections.Generic; using System.Text.Json.Serialization; namespace SujaySarma.Sdk.WikipediaApi.SerializationObjects { /// <summary> /// Result data for <see cref="WikipediaApi.PageReferenceClient.GetPageReferences(string, decimal)"/>. /// </summary> public class PageReferencesList { /// <summary> /// Revision number (of the original page) /// </summary> [JsonPropertyName("revision")] public string RevisionId { get; set; } /// <summary> /// Time Id /// </summary> [JsonPropertyName("tid")] public string RevisionTimeId { get; set; } /// <summary> /// The types of reference sections available for the page /// </summary> [JsonPropertyName("reference_lists")] public List<PageReferencesListSectionItem> Lists { get; set; } /// <summary> /// The actual reference items. The Key is the <see cref="PageReferencesListSectionItem.Id"/> value. /// </summary> [JsonPropertyName("references_by_id")] public Dictionary<string, PageReferenceItemDetail> Items { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Threading; namespace Localizy { public class NulloLocalizationDataProvider : ILocalizationDataProvider { public string GetText(StringToken key, CultureInfo culture = null) { #if DOTNET54 culture = culture ?? CultureInfo.CurrentUICulture; #else culture = culture ?? Thread.CurrentThread.CurrentUICulture; #endif return key.DefaultValue ?? culture.Name + "_" + key.Key; } public TextAndCulture GetTextWithCulture(StringToken key, CultureInfo culture) { return new TextAndCulture(GetText(key, culture), culture); } public void UpdateText(LocalizationKey key, CultureInfo culture, string value) { } public void Reload(CultureInfo cultureInfo, Func<CultureInfo, ILocaleCache> factory) { } public void Reload() { } public IEnumerable<StringToken> GetAllTokens(CultureInfo culture, Assembly assembly, Func<Type, bool> where) { yield break; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityTK.Audio; namespace OsFPS { /// <summary> /// Weapon sound implementation that handles fire, reload and dry fire sounds. /// </summary> [RequireComponent(typeof(Weapon))] public class WeaponSound : MonoBehaviour { public Weapon weapon { get { if (_weapon == null) _weapon = GetComponent<Weapon>(); return _weapon; } } private Weapon _weapon; [Header("Audio")] public AudioEvent fireAudio; public AudioEvent dryFireAudio; public AudioEvent reloadAudio; public UTKAudioSource source; public void Awake() { this.weapon.weaponFire.onStart += this.OnWeaponFire; this.weapon.weaponFire.onFailStart += this.OnWeaponFireFailStart; this.weapon.weaponFire.onStop += this.OnWeaponFireDone; this.weapon.weaponReload.onStart += this.OnWeaponReload; } protected virtual void OnWeaponFireFailStart() { if (this.weapon.ammoInClip == 0) this.dryFireAudio.Play(this.source); } protected virtual void OnWeaponFire() { this.fireAudio.Play(this.source); } protected virtual void OnWeaponFireDone() { } protected virtual void OnWeaponReload() { this.reloadAudio.Play(this.source); } } }
using Microsoft.Bot.Connector; using PomodoroBot.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PomodoroBot.Command { public class CommandTool { public PomodoroTimerRepository Repository { get; private set; } public ConnectorClient Client { get; private set; } public ChatRequest Request { get; private set; } public PomodoroQueueRepository QueueRepository { get; private set; } public static CommandTool Instance { get; private set; } static CommandTool() { Instance = new CommandTool(); } private CommandTool() { Repository = new PomodoroTimerRepository(); Client = new ConnectorClient(); Request = new ChatRequest(); QueueRepository = new PomodoroQueueRepository(); } } }
using System; namespace DFC.Content.Pkg.Netcore.Data.Contracts { public interface IApiCacheService { int Count { get; } void AddOrUpdate(Uri id, object obj); void Clear(); void StartCache(); void StopCache(); void Remove(Uri id); TModel? Retrieve<TModel>(Uri id) where TModel : class; TModel? Retrieve<TModel>(Type type, Uri id) where TModel : class; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DaxDrill.DaxHelpers { public class DaxFilter { public string TableName; public string ColumnName; // also represents hierarchy name public string Value; public IList<DaxColumn> ColumnNameHierarchy; public string[] ValueHierarchy; public bool IsHierarchy; // also represents the table-qualified column name public string Key { get { return "[" + this.TableName + "].[" + this.ColumnName + "]"; } } // TODO: use HierarchyValue instead of Value which is limited to the 1st value public string MDX { get { return Key + ".&[" + this.Value + "]"; } } public string GetValue(string columnName) { var daxFilter = this; var matchedColumn = daxFilter.ColumnNameHierarchy.Where(x => x.ColumnName == columnName).FirstOrDefault(); return daxFilter.ValueHierarchy[matchedColumn.Index]; } } }
#region PDFsharp Charting - A .NET charting library based on PDFsharp // // Authors: // Niklas Schneider // // Copyright (c) 2005-2017 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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. #endregion using System; using PdfSharp.Drawing; namespace PdfSharp.Charting.Renderers { /// <summary> /// Represents a plot area renderer of stacked columns, i. e. all columns are drawn one on another. /// </summary> internal class ColumnStackedPlotAreaRenderer : ColumnPlotAreaRenderer { /// <summary> /// Initializes a new instance of the ColumnStackedPlotAreaRenderer class with the /// specified renderer parameters. /// </summary> internal ColumnStackedPlotAreaRenderer(RendererParameters parms) : base(parms) { } /// <summary> /// Calculates the position, width and height of each column of all series. /// </summary> protected override void CalcColumns() { ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo; if (cri.seriesRendererInfos.Length == 0) return; double xMin = cri.xAxisRendererInfo.MinimumScale; double xMajorTick = cri.xAxisRendererInfo.MajorTick; int maxPoints = 0; foreach (SeriesRendererInfo sri in cri.seriesRendererInfos) maxPoints = Math.Max(maxPoints, sri._series._seriesElements.Count); double x = xMin + xMajorTick / 2; // Space used by one column. double columnWidth = xMajorTick * 0.75 / 2; XPoint[] points = new XPoint[2]; for (int pointIdx = 0; pointIdx < maxPoints; ++pointIdx) { // Set x to first clustered column for each series. double yMin = 0, yMax = 0, y0 = 0, y1 = 0; double x0 = x - columnWidth; double x1 = x + columnWidth; foreach (SeriesRendererInfo sri in cri.seriesRendererInfos) { if (sri._pointRendererInfos.Length <= pointIdx) break; ColumnRendererInfo column = (ColumnRendererInfo)sri._pointRendererInfos[pointIdx]; if (column.Point != null && !double.IsNaN(column.Point._value)) { double y = column.Point._value; if (y < 0) { y0 = yMin + y; y1 = yMin; yMin += y; } else { y0 = yMax; y1 = yMax + y; yMax += y; } points[0].X = x0; // upper left points[0].Y = y1; points[1].X = x1; // lower right points[1].Y = y0; cri.plotAreaRendererInfo._matrix.TransformPoints(points); column.Rect = new XRect(points[0].X, points[0].Y, points[1].X - points[0].X, points[1].Y - points[0].Y); } } x++; // Next stacked column. } } /// <summary> /// Stacked columns are always inside. /// </summary> protected override bool IsDataInside(double yMin, double yMax, double yValue) { return true; } } }
using RacecourseSystem; 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 WPFRacecourseSystem { /// <summary> /// Interaction logic for RacecourseWindow.xaml /// </summary> public partial class RacecourseWindow : Window { private Racecourse oldRacecourse; public Action<Racecourse> OnAdd; public Action<Racecourse, int> OnUpdate; public RacecourseWindow () { InitializeComponent (); buttonUpdate.IsEnabled = false; } public RacecourseWindow (Racecourse horseFactoryToChange) { InitializeComponent (); oldRacecourse = horseFactoryToChange; ShowOldContestInformation (); } private void ShowOldContestInformation () { textBoxName.Text = oldRacecourse.Name; textBoxCountry.Text = oldRacecourse.Country; textBoxHorseAmount.Text = oldRacecourse.HorseAmount.ToString (); textBoxAdditionalInfo.Text = oldRacecourse.AdditionalInfo; } private Racecourse GetRacecourse () { try { return new Racecourse () { Name = textBoxName.Text, Country = textBoxCountry.Text ?? "Empty", HorseAmount = GetHorseAmount (), AdditionalInfo = textBoxAdditionalInfo.Text ?? "Empty" }; } catch (ArgumentNullException ex) { MessageBox.Show ("Argument null exception: " + ex.Message); return null; } catch (FormatException ex) { MessageBox.Show ("Format exception: " + ex.Message); return null; } catch (Exception ex) { MessageBox.Show (ex.Message); return null; } } private int GetHorseAmount () { int horseAmount; try { horseAmount = int.Parse (textBoxHorseAmount.Text); } catch (Exception) { horseAmount = 0; } return horseAmount; } private bool CheckInformationFields () { if (textBoxName.Text.Length < 1) { MessageBox.Show ("Name is empty."); return false; } if (textBoxAdditionalInfo.Text.Length > 255) { MessageBox.Show ("Additional Information is too long. The maximum size is a 255 characters."); return false; } return true; } private void buttonNew_Click (object sender, RoutedEventArgs e) { if (CheckInformationFields ()) { OnAdd?.Invoke (GetRacecourse ()); MessageBox.Show ("Contest was successfully added to the database."); this.Close (); } } private void buttonUpdate_Click (object sender, RoutedEventArgs e) { if (oldRacecourse != null) { if (CheckInformationFields ()) { Racecourse racecourse = GetRacecourse (); racecourse.Id = oldRacecourse.Id; OnUpdate?.Invoke (racecourse, oldRacecourse.Id); MessageBox.Show ("Contest was successfully updated in the database."); this.Close (); } } } } }
using System.Collections.Generic; namespace AirView.Persistence.Core.EventSourcing.Internal { internal class EventStream<TEvent> : IEventStream<TEvent> { private readonly IEventReader<TEvent> _reader; private readonly int _sliceSize; private readonly ICollection<TEvent> _uncommitedEvents = new List<TEvent>(); public EventStream(object id, IEventReader<TEvent> reader, int sliceSize) { Id = id; _reader = reader; _sliceSize = sliceSize; } public object Id { get; } public IEnumerable<TEvent> UncommitedEvents => _uncommitedEvents; public IAsyncEnumerator<TEvent> GetEnumerator() => GetEnumeratorAt(0); public void Append(TEvent @event) => _uncommitedEvents.Add(@event); public IAsyncEnumerable<TEvent> From(long index) => new AsyncEnumerable<TEvent>(() => GetEnumeratorAt(index)); private IAsyncEnumerator<TEvent> GetEnumeratorAt(long index) => new PagingAsyncEnumerator<TEvent>( (limit, offset, cancellationToken) => _reader.ReadAsync(Id, offset, limit, cancellationToken), _sliceSize, index); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using Xunit; namespace Microsoft.Extensions.Configuration.Xml.Test { public class XmlConfigurationExtensionsTest { [Fact] public void AddXmlFile_ThrowsIfFileDoesNotExistAtPath() { var config = new ConfigurationBuilder().AddXmlFile("NotExistingConfig.xml"); // Arrange // Act and Assert var ex = Assert.Throws<FileNotFoundException>(() => config.Build()); Assert.StartsWith($"The configuration file 'NotExistingConfig.xml' was not found and is not optional. The physical path is '", ex.Message); } } }
namespace OrderingService.Core.Enums { public enum ManipulationOperator { Plus, Subtract } }
namespace LoggerApplication.Models.Appenders { using LoggerApplication.Models.Contracts; using LoggerApplication.Models.Enums; public abstract class Appender : IAppender { private const string dateFormat = "M/dd/yyyy h:mm::ss tt"; public Appender() { this.MessagesAppended = 0; } public Appender(ILayout layout, ErrorLevel level) : this() { this.Layout = layout; this.Level = level; } public ILayout Layout { get; private set; } public ErrorLevel Level { get; private set; } public string DateFormat => dateFormat; public int MessagesAppended { get; set; } public abstract void Append(IError error); public override string ToString() { return $"Appender type: {this.GetType().Name}, " + $"Layout type: {this.Layout.GetType().Name}, Report level: " + $"{this.Level.ToString()}, Messages appended: {this.MessagesAppended}"; } } }
using Blauhaus.Domain.Abstractions.Entities; namespace Blauhaus.Domain.Abstractions.Extensions { public static class EntityExtensions { public static bool IsActive(this IEntity entity) { return entity.EntityState == EntityState.Active; } public static bool IsArchived(this IEntity entity) { return entity.EntityState == EntityState.Archived; } public static bool IsDeleted(this IEntity entity) { return entity.EntityState == EntityState.Deleted; } public static bool IsDraft(this IEntity entity) { return entity.EntityState == EntityState.Draft; } } }
using System; using System.Collections.Generic; using System.Text; #if !NETFX_CORE using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif using Mina.Core.Buffer; namespace Mina.Filter.Codec.TextLine { [TestClass] public class TextLineDecoderTest { [TestMethod] public void TestNormalDecode() { Encoding encoding = Encoding.UTF8; TextLineDecoder decoder = new TextLineDecoder(encoding, LineDelimiter.Windows); ProtocolCodecSession session = new ProtocolCodecSession(); IProtocolDecoderOutput output = session.DecoderOutput; IoBuffer input = IoBuffer.Allocate(16); // Test one decode and one output.put input.PutString("ABC\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("ABC", session.DecoderOutputQueue.Dequeue()); // Test two decode and one output.put input.Clear(); input.PutString("DEF", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("GHI\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("DEFGHI", session.DecoderOutputQueue.Dequeue()); // Test one decode and two output.put input.Clear(); input.PutString("JKL\r\nMNO\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("JKL", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("MNO", session.DecoderOutputQueue.Dequeue()); // Test aborted delimiter (DIRMINA-506) input.Clear(); input.PutString("ABC\r\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("ABC\r", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter decoder = new TextLineDecoder(encoding, new LineDelimiter("\n\n\n")); input.Clear(); input.PutString("PQR\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter which produces two output.put decoder = new TextLineDecoder(encoding, new LineDelimiter("\n\n\n")); input.Clear(); input.PutString("PQR\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\nSTU\n\n\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("STU", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter mixed with partial non-delimiter. decoder = new TextLineDecoder(encoding, new LineDelimiter("\n\n\n")); input.Clear(); input.PutString("PQR\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("X\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\n\nSTU\n\n\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR\nX", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("STU", session.DecoderOutputQueue.Dequeue()); } [TestMethod] public void TestAutoDecode() { Encoding encoding = Encoding.UTF8; TextLineDecoder decoder = new TextLineDecoder(encoding, LineDelimiter.Auto); ProtocolCodecSession session = new ProtocolCodecSession(); IProtocolDecoderOutput output = session.DecoderOutput; IoBuffer input = IoBuffer.Allocate(16); // Test one decode and one output input.PutString("ABC\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("ABC", session.DecoderOutputQueue.Dequeue()); // Test two decode and one output input.Clear(); input.PutString("DEF", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("GHI\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("DEFGHI", session.DecoderOutputQueue.Dequeue()); // Test one decode and two output input.Clear(); input.PutString("JKL\r\nMNO\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("JKL", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("MNO", session.DecoderOutputQueue.Dequeue()); // Test multiple '\n's input.Clear(); input.PutString("\n\n\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(3, session.DecoderOutputQueue.Count); Assert.AreEqual("", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter (\r\r\n) input.Clear(); input.PutString("PQR\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter (\r\r\n) which produces two output input.Clear(); input.PutString("PQR\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\nSTU\r\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("STU", session.DecoderOutputQueue.Dequeue()); // Test splitted long delimiter mixed with partial non-delimiter. input.Clear(); input.PutString("PQR\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("X\r", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear(); input.PutString("\r\nSTU\r\r\n", encoding); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(2, session.DecoderOutputQueue.Count); Assert.AreEqual("PQR\rX", session.DecoderOutputQueue.Dequeue()); Assert.AreEqual("STU", session.DecoderOutputQueue.Dequeue()); input.Clear(); String s = encoding.GetString(new byte[] { 0, 77, 105, 110, 97 }); input.PutString(s, encoding); input.Put(0x0a); input.Flip(); decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual(s, session.DecoderOutputQueue.Dequeue()); } [TestMethod] public void TestOverflow() { Encoding encoding = Encoding.UTF8; TextLineDecoder decoder = new TextLineDecoder(encoding, LineDelimiter.Auto); decoder.MaxLineLength = 3; ProtocolCodecSession session = new ProtocolCodecSession(); IProtocolDecoderOutput output = session.DecoderOutput; IoBuffer input = IoBuffer.Allocate(16); // Make sure the overflow exception is not thrown until // the delimiter is encountered. input.PutString("A", encoding).Flip().Mark(); decoder.Decode(session, input.Reset().Mark(), output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); decoder.Decode(session, input.Reset().Mark(), output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); decoder.Decode(session, input.Reset().Mark(), output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); decoder.Decode(session, input.Reset().Mark(), output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.Clear().PutString("A\r\nB\r\n", encoding).Flip(); try { decoder.Decode(session, input, output); Assert.Fail(); } catch (RecoverableProtocolDecoderException) { // signifies a successful test execution Assert.IsTrue(true); } decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("B", session.DecoderOutputQueue.Dequeue()); //// Make sure OOM is not thrown. GC.Collect(); //long oldFreeMemory = GC.GetTotalMemory(false); input = IoBuffer.Allocate(1048576 * 16).Sweep((byte)' ').Mark(); for (int i = 0; i < 10; i++) { input.Reset(); input.Mark(); decoder.Decode(session, input, output); Assert.AreEqual(0, session.DecoderOutputQueue.Count); // Memory consumption should be minimal. //Assert.IsTrue(GC.GetTotalMemory(false) - oldFreeMemory < 1048576); } input.Clear().PutString("C\r\nD\r\n", encoding).Flip(); try { decoder.Decode(session, input, output); Assert.Fail(); } catch (RecoverableProtocolDecoderException) { // signifies a successful test execution Assert.IsTrue(true); } decoder.Decode(session, input, output); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("D", session.DecoderOutputQueue.Dequeue()); // Memory consumption should be minimal. //Assert.IsTrue(GC.GetTotalMemory(false) - oldFreeMemory < 1048576); } [TestMethod] public void TestSMTPDataBounds() { Encoding encoding = Encoding.ASCII; TextLineDecoder decoder = new TextLineDecoder(encoding, new LineDelimiter("\r\n.\r\n")); ProtocolCodecSession session = new ProtocolCodecSession(); IoBuffer input = IoBuffer.Allocate(16); input.AutoExpand = true; input.PutString("\r\n", encoding).Flip().Mark(); decoder.Decode(session, input.Reset().Mark(), session.DecoderOutput); Assert.AreEqual(0, session.DecoderOutputQueue.Count); input.PutString("Body\r\n.\r\n", encoding); decoder.Decode(session, input.Reset().Mark(), session.DecoderOutput); Assert.AreEqual(1, session.DecoderOutputQueue.Count); Assert.AreEqual("\r\n\r\nBody", session.DecoderOutputQueue.Dequeue()); } } }
// // OutgoingWebResponseContext.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.Net; using System.ServiceModel.Channels; namespace System.ServiceModel.Web { public class OutgoingWebResponseContext { WebHeaderCollection headers; long content_length; string content_type, etag, location, status_desc; DateTime last_modified; HttpStatusCode status_code; bool suppress_body; internal OutgoingWebResponseContext () { } internal void Apply (HttpResponseMessageProperty hp) { if (headers != null) hp.Headers.Add (headers); if (content_length != 0) hp.Headers ["Content-Length"] = content_length.ToString (NumberFormatInfo.InvariantInfo); if (content_type != null) hp.Headers ["Content-Type"] = content_type; if (etag != null) hp.Headers ["ETag"] = etag; if (location != null) hp.Headers ["Location"] = location; if (last_modified != default (DateTime)) hp.Headers ["Last-Modified"] = last_modified.ToString ("R"); if (status_code != default (HttpStatusCode)) hp.StatusCode = status_code; if (status_desc != null) hp.StatusDescription = status_desc; hp.SuppressEntityBody = suppress_body; } public long ContentLength { get { return content_length; } set { content_length = value; } } public string ContentType { get { return content_type; } set { content_type = value; } } public string ETag { get { return etag; } set { etag = value; } } public WebHeaderCollection Headers { get { if (headers == null) headers = new WebHeaderCollection (); return headers; } } public DateTime LastModified { get { return last_modified; } set { last_modified = value; } } public string Location { get { return location; } set { location = value; } } public HttpStatusCode StatusCode { get { return status_code; } set { status_code = value; } } public string StatusDescription { get { return status_desc; } set { status_desc = value; } } public bool SuppressEntityBody { get { return suppress_body; } set { suppress_body = value; } } public void SetStatusAsCreated (Uri locationUri) { StatusCode = HttpStatusCode.Created; Location = locationUri.AbsoluteUri; } public void SetStatusAsNotFound () { StatusCode = HttpStatusCode.NotFound; } public void SetStatusAsNotFound (string description) { StatusCode = HttpStatusCode.NotFound; StatusDescription = description; } } }
using System.IO; namespace DotnetCleanup { internal static class PathUtility { private static readonly char SeparatorChar = Path.DirectorySeparatorChar; public static string GetCleanPath(string path) { return path?.Replace('\\', SeparatorChar) .Replace('/', SeparatorChar) .TrimStart(SeparatorChar); } } }
namespace _02.Data.Models { public class Invoice : BaseEntity { public Invoice(int id, int? parentId) : base(id, parentId) { } public string Description { get; set; } public int PriceCents { get; set; } } }
using DA; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rotativa; using System; using System.Linq; using System.Web.Mvc; using Web.Controllers; namespace Web.UnitTest { [TestClass] public class PagosTest { [TestMethod] public void TablaPagosTest() { DAEntities db = new DAEntities(); var controller = new PagosController(); var result = controller.TablaPagos("",1) as JsonResult; var rm = result.Data as Comun.ResponseModel; Assert.IsTrue(rm.result.TotalRegistros == db.CajaMovimiento.Where(x => x.EstadoId != 4).Count()); } [TestMethod] public void TablaCobranzasTest() { DAEntities db = new DAEntities(); var controller = new PagosController(); var result = controller.TablaCobranzas("",1) as JsonResult; var rm = result.Data as Comun.ResponseModel; Assert.IsTrue(rm.result.TotalRegistros == db.CuentasPorCobrar.Where(x => x.EstadoId.Equals(2)).Count()); } [TestMethod] public void BoletaTest() { var controller = new PagosController(); var result = controller.Boleta(1); Assert.IsTrue(result is ViewAsPdf); } [TestMethod] public void FacturaTest() { var controller = new PagosController(); var result = controller.Factura(1); Assert.IsTrue(result is ViewAsPdf); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ActorTest : MonoBehaviour { EquipsLoader equips_loader; TechsLoader techs_loader; SlottableAnatomy anatomy; ActionComparator validator; UnitActor actor_a; UnitActor actor_b; int test_count = 0; int pass_count = 0; // Use this for initialization void Start () { equips_loader = GetComponent<EquipsLoader>(); techs_loader = GetComponent<TechsLoader>(); actor_a = GameObject.Find("actor_a").GetComponent<UnitActor>(); actor_b = GameObject.Find("actor_b").GetComponent<UnitActor>(); actor_a.assign_item_loader(equips_loader.get_equips()); actor_a.assign_tech_loader(techs_loader.get_techs()); actor_b.assign_item_loader(equips_loader.get_equips()); actor_b.assign_tech_loader(techs_loader.get_techs()); begin_test(); } // Update is called once per frame void Update () { } void begin_test() { validator = new ActionComparator(); actor_a.set_level(30); actor_a.set_six_stats(1, 1, 10, 50, 1, 1); actor_a.stats_recompute_all(); actor_a.equip("bow_long"); actor_a.equip("quiver_slingback"); actor_a.load_multis("arrow_iron", 5); actor_a.confer_tech("marksmanship_bow"); actor_a.confer_tech("marksmanship_double_tap"); actor_b.set_level(1); actor_b.stats.agility = 99; actor_b.stats_recompute_all(); validator.add("marksmanship_double_tap"); validator.enable("attack_melee", false); validator.enable("attack_firearm", false); validator.enable("throw", false); actor_a.deliver_to(actor_b, "marksmanship_double_tap"); test(); end_test(); } void test() { if (validator.equals(actor_a.get_actions())) { pass_count++; } test_count++; } void end_test() { Debug.Log(pass_count + "/" + test_count + " tests passed"); } } public class ActionComparator { Dictionary<string, bool> actions; public ActionComparator() { actions = new Dictionary<string, bool>(); preinit_expectation(); } void preinit_expectation() { actions = new Dictionary<string, bool>(); List<string> gts = new List<string>() { { "move"}, { "wait"}, { "attack_melee"}, { "attack_bow"}, {"attack_firearm" }, {"throw" } }; foreach (string gt in gts) { actions[gt] = true; } } public void add(string s) { actions.Add(s, true); } public void enable(string s, bool val = true) { actions[s] = val; } public bool equals(Dictionary<string, bool> other) { bool is_equal = true; if (actions.Count != other.Count) { List<string> missing_in_others = new List<string>(); List<string> missing_in_self = new List<string>(); foreach (string s in actions.Keys) { if (!other.ContainsKey(s)) { missing_in_others.Add(s); } } foreach (string s in other.Keys) { if (!actions.ContainsKey(s)) { missing_in_self.Add(s); } } if (missing_in_others.Count > 0) { is_equal = false; Debug.Log("Missing in Test: \n" + string.Join("\n", missing_in_others.ToArray())); } if (missing_in_self.Count > 0) { is_equal = false; Debug.Log("Extra entry in Test: \n" + string.Join("\n", missing_in_self.ToArray())); } return is_equal; } else { List<string> mismatches = new List<string>(); foreach (KeyValuePair<string, bool> k in actions) { if (k.Value != other[k.Key]) { List<bool> tuple = new List<bool>() { { other[k.Key] }, { k.Value } }; mismatches.Add(k.Key + " : " + (other[k.Key] ? "T" : "F") + " | " + (k.Value ? "T" : "F")); } } if (mismatches.Count > 0) { is_equal = false; Debug.Log("Mismatch entries (Test | Expected):\n" + string.Join("\n", mismatches.ToArray())); } return is_equal; } } }
namespace StupidNetworking { public class ClientRPCAttribute : RPCAttribute { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using Engine; namespace Parallel_Worlds { public class GameScreen : Screen { #region Fields public static Texture2D boxTexture; public static bool setBoundingBoxes = true; //public static World World; public static float AlphaStep; #endregion #region Constructor and Loading public GameScreen() : base() { TransitionOnTime = TimeSpan.FromSeconds(1.5); TransitionOffTime = TimeSpan.FromSeconds(1.5); } public override void LoadContent() { World.Load(ScreenManager.Content);// (ScreenManager.Game.Content); } #endregion #region Update public override void Update(GameTime gameTime, bool focus, bool covered) { base.Update(gameTime, focus, covered); World.Update(gameTime); if (covered) AlphaStep = Math.Min(AlphaStep + 1f / 32, 1); else AlphaStep = Math.Max(AlphaStep - 1f / 32, 0); } #endregion #region Draw public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; World.Draw(spriteBatch); if (TransitionPosition > 0 || AlphaStep > 0) { float a = MathHelper.Lerp(1f - TransitionAlpha, 1f, AlphaStep / 2); ScreenManager.FadeBackBufferToBlack(a); } } #endregion #region Input public override void HandleInput() { if (InputManager.IsActionTriggered(InputManager.Action.Exit)) { // add a confirmation message box const string message = "Are you sure you want to exit? All unsaved progress will be lost." + "\n\n <Esc> : cancel " + "\n <Enter> : confirm"; MessageBox exitBox = new MessageBox(message, true); exitBox.Accepted += ConfirmExitAccepted; ScreenManager.Push(exitBox); //return; } } /// <summary> /// Event handler for when the user selects Yes /// on the "Are you sure?" message box. /// </summary> void ConfirmExitAccepted(object sender, EventArgs e) { //ExitScreen(); //ScreenManager.Push(new MenuScreen()); LoadingScreen.Load( /*ScreenManager,*/ false, null, new BackgroundScreen(), new MenuScreen()); } #endregion } }
using Sapphire.Host.Core.Interfaces; namespace Sapphire.Host.Core.Base { /// <inheritdoc /> public abstract class DeviceBase : IDevice { /// <inheritdoc /> public abstract void Init(); /// <inheritdoc /> public abstract void Connect(int timeOut = 3000); /// <inheritdoc /> public abstract void Disconnect(bool force = false); /// <inheritdoc /> public abstract void SendCommandFrame(string frame); /// <inheritdoc /> public abstract string GetResponse(); /// <inheritdoc /> public abstract void Dispose(); } }
using SteamBot; using SteamBot.MarketBot.CS.Bot; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Utility { public class Tasking { static NewMarketLogger taskLog = new NewMarketLogger("Tasking"); public static async Task<bool> WaitForFalseOrTimeout(Func<bool> condition) { await Task.Run(async () => { while (condition()) await Task.Delay(80); }); return true; } public static async Task<bool> WaitForFalseOrTimeout(Func<bool> condition, int timeout) { if (timeout <= 3000) { await Task.Delay(timeout); return !condition(); } Console.WriteLine($"Timeout: {timeout}"); var tokenSource2 = new CancellationTokenSource(); CancellationToken ct = tokenSource2.Token; Task waitTask = Task.Run(async () => { try { while (!ct.IsCancellationRequested && condition()) { await Task.Delay(1000, ct); } } catch (Exception) { } }); Task delayTask = Task.Run(async () => { try { await Task.Delay(timeout, ct); } catch (Exception) { } }); Task temp = await Task.WhenAny(waitTask, delayTask); tokenSource2.Cancel(); try { Task.WaitAll(waitTask, delayTask); } catch (Exception e) { taskLog.Info($"{e}"); } finally { tokenSource2.Dispose(); } return temp == waitTask; } public static void Run(Action runnable, CancellationToken ct, string botName = "EXTRA") { taskLog.Info(botName, $"[{runnable.Method}] started"); Task.Run(() => { try { runnable(); } catch (Exception e) { taskLog.Crash($"Message: {e.Message} \n {e.StackTrace}"); } }, ct).ContinueWith(tsk => taskLog.Info(botName, $"[{runnable.Method}] ended")); } public static void Run(Action runnable, string botName = "EXTRA") { taskLog.Info(botName, $"[{runnable.Method}] started"); Task.Run(() => { try { runnable(); } catch (Exception e) { taskLog.Crash($"Message: {e.Message} \n {e.StackTrace}"); } }).ContinueWith(tsk => taskLog.Info(botName, $"[{runnable.Method}] ended")); } } }
using TransitionShellApp.Models; using TransitionShellApp.ViewModels; using TransitionShellApp.Views.Collectionview; using Xamarin.Forms; namespace TransitionShellApp.Views.Listview { public partial class ListViewFromPage : ContentPage { readonly ListViewFromPageViewModel _viewModel; public ListViewFromPage() { InitializeComponent(); BindingContext = _viewModel = new ListViewFromPageViewModel(); } async void OnItemSelected(object sender, SelectedItemChangedEventArgs args) { var item = args.SelectedItem as DogModel; if (item == null) return; // We can set the SelectedGroup both in binding or using the static method // SharedTransitionShell.SetTransitionSelectedGroup(this, item.Id.ToString()); _viewModel.SelectedDog = item; await Navigation.PushAsync(new ListviewToPage(new ListviewToPageViewModel(item))); // Manually deselect item. ItemsListView.SelectedItem = null; } protected override void OnAppearing() { base.OnAppearing(); if (_viewModel.Dogs.Count == 0) _viewModel.LoadDogsCommand.Execute(null); } } }
using Grasshopper.Kernel; using NAudio.Wave; using System; using Rhino.Geometry; using System.Linq; namespace Siren { public class ReadSampleComponent : GH_Component { /// <summary> /// Initializes a new instance of the ReadSampleComponent class. /// </summary> public ReadSampleComponent() : base("ReadSampleComponent", "Nickname", "Description", "Siren", "Oscillators") { } /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddTextParameter("Path", "P", "Path of audio file", GH_ParamAccess.item); } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddParameter(new WaveStreamParameter(), "Wave", "W", "Wave output", GH_ParamAccess.item); } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { string path = ""; if (!DA.GetData(0, ref path)) return; var audioFile = new AudioFileReader(path); //var cachedWave = new SampleProviders.CachedSound(audioFile); //audioFile.Position = 0; //var raw = NAudioUtilities.WaveProviderToWaveStream( // new SampleProviders.CachedSoundSampleProvider(cachedWave), // (int)audioFile.Length, // cachedWave.WaveFormat); //audioFile.Position = 0; //audioFile.Position = 0; //var raw = NAudioUtilities.WaveProviderToWaveStream( // audioFile.ToSampleProvider(), // (int)audioFile.Length, // audioFile.WaveFormat); //audioFile.Position = 0; DA.SetData(0, audioFile); } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon => Properties.Resources.readSample; /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("805913e8-8e7b-4264-9368-87228bc3c850"); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Aprimo.Epi.Extensions.API.Orders { public partial class Order { public Order() { this.DeliveredFiles = new List<string>(); this.Links = new OrderLinks(); } [JsonProperty("_links")] public OrderLinks Links { get; set; } [JsonProperty("orderType")] public string OrderType { get; set; } [JsonProperty("deliveredFiles")] public List<string> DeliveredFiles { get; set; } [JsonProperty("creatorEmail")] public string CreatorEmail { get; set; } [JsonProperty("disableNotification")] public bool DisableNotification { get; set; } [JsonProperty("earliestStartDate")] public object EarliestStartDate { get; set; } [JsonProperty("executionTime")] public DateTimeOffset ExecutionTime { get; set; } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("priority")] public long Priority { get; set; } [JsonProperty("startedOn")] public object StartedOn { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("message")] public object Message { get; set; } [JsonProperty("createdOn")] public DateTimeOffset CreatedOn { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PersonaApi2.Models { public class Maestro { public Persona Persona { get; set; } public int IdPersona { get; set; } public string Folio { get; set; } public string Asignatura { get; set; } public double Salario { get; set; } } }
using FPP.Scripts.Enums; using UnityEngine.Events; using System.Collections.Generic; namespace FPP.Scripts.Patterns { public class RaceEventBus { private static readonly IDictionary<RaceEventType, UnityEvent> Events = new Dictionary<RaceEventType, UnityEvent>(); public static void Subscribe(RaceEventType eventType, UnityAction listener) { UnityEvent thisEvent; if (Events.TryGetValue(eventType, out thisEvent)) { thisEvent.AddListener(listener); } else { thisEvent = new UnityEvent(); thisEvent.AddListener(listener); Events.Add(eventType, thisEvent); } } public static void Unsubscribe(RaceEventType eventType, UnityAction listener) { UnityEvent thisEvent; if (Events.TryGetValue(eventType, out thisEvent)) { thisEvent.RemoveListener(listener); } } public static void Publish(RaceEventType eventType) { UnityEvent thisEvent; if (Events.TryGetValue(eventType, out thisEvent)) { thisEvent.Invoke(); } } } }
using Rnx.Abstractions.Tasks; namespace Rnx.Tasks.Reliak.Minification { public class JsMinTaskDescriptor : TaskDescriptorBase<JsMinTask> { } public class JsMinTask : MinificationTask { protected override string Minify(string input) { var jsMinifier = new WebMarkupMin.Core.CrockfordJsMinifier(); return jsMinifier.Minify(input, false).MinifiedContent; } } }
namespace MeTube.App.Controllers { using SimpleMvc.Framework.Attributes.Methods; using SimpleMvc.Framework.Controllers; using SimpleMvc.Framework.Interfaces; using MeTube.App.Models.BindingModels; using MeTube.Models; using Services.DataProvider.Contracts; using Services.DataProvider; public class TubeController : Controller { private readonly IDataService service; public TubeController() { this.service = new DataService(); } [HttpGet] public IActionResult Upload() { AuthorizeUser(); return View(); } [HttpPost] public IActionResult Upload(TubeBindingModel model) { if (!this.IsValidModel(model)) { return View(); } var youtubeId = model.YoutubeLink.Split("?v=")[1]; var username = this.User.Name; var user = this.service.GetUserByName(username); if (user == null) { return RedirectToAction("/account/login"); } var tube = new Tube() { Title = model.Title, Author = model.Author, Description = model.Description, YoutubeId = youtubeId, User = user, UserId = user.Id }; this.service.CreateTube(tube); return RedirectToAction("/"); } [HttpGet] public IActionResult Details(int id) { AuthorizeUser(); var tube = this.service.GetTubeById(id); this.service.IncreaseVies(tube); this.Model["youtubeId"] = tube.YoutubeId; this.Model["author"] = tube.Author; this.Model["views"] = tube.Views.ToString(); this.Model["description"] = tube.Description; return View(); } private void AuthorizeUser() { if (this.User.IsAuthenticated) { this.Model["displayType"] = "block"; this.Model["notLoginUser"] = "none"; } else { this.Model["notLoginUser"] = "block"; this.Model["displayType"] = "none"; } } } }
namespace Maze { public partial class Level { public static class Side { public const uint North = 1; public const uint East = 2; public const uint South = 4; public const uint West = 8; }; public readonly Vector2 CellCenter = new(-64, 64); public Vector2 CellToWorld( int x, int y ) { return new Vector2( x * -128, y * 128 ); } } }
using ActiveDevelop.MvvmBaseLib.Mvvm; using System; using System.Collections.ObjectModel; using System.Reflection; using Xamarin.Forms; namespace XamFormExp.ViewModel { public class MainListViewModel : MvvmViewModelBase { private ObservableCollection<ImageListItem> myImageListItems; private string[] myPictureNames = { "ActiveDevelopUp.jpg", "JeepRim.jpg", "KlausTafel.jpg", "LoheUp.jpg", "OdoMeter.jpg", "Wedding.jpg"}; public static MainListViewModel GetMainListViewModelDemoData(int elementCount) { var returnList = new MainListViewModel(); returnList.ImageListItems = new ObservableCollection<ImageListItem>(); var imageItem = new ImageListItem(); var currentAss = typeof(MainListViewModel).GetTypeInfo().Assembly; var ressourceNames = currentAss.GetManifestResourceNames(); for (int count = 0; count < elementCount; count++) { } return returnList; } public ObservableCollection<ImageListItem> ImageListItems { get { return myImageListItems; } set { SetProperty(ref myImageListItems, value); } } } public class ImageListItem : MvvmViewModelBase { private ImageSource imageSource; private string myItemText; public ImageSource MyProperty { get { return imageSource; } set { SetProperty(ref imageSource, value); } } public String ItemText { get { return myItemText; } set { SetProperty(ref myItemText, value); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Management.Automation; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace PowerShellTools.Common { [DebuggerDisplay("{Name}, Module {ModuleName}")] [DataContract] public class PowerShellCommand : IPowerShellCommand { public PowerShellCommand() { } public PowerShellCommand(CommandInfo command) { Name = command.Name; ModuleName = command.ModuleName ?? string.Empty; Definition = command.Definition ?? string.Empty; Type = command.CommandType; SupportsCommonParameters = (Type & CommandTypes.Cmdlet) == CommandTypes.Cmdlet | (Type & CommandTypes.Function) == CommandTypes.Function; } [DataMember] public string Name { get; set; } [DataMember] public string ModuleName { get; set; } [DataMember] public string Definition { get; set; } [DataMember] public CommandTypes Type { get; set; } [DataMember] public bool SupportsCommonParameters { get; set; } public override string ToString() { return Name; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using UnityEngine; namespace Microsoft.MixedReality.WebRTC.Unity { /// <summary> /// Abstract base component for a custom video source delivering raw video frames /// directly to the WebRTC implementation. /// </summary> public abstract class CustomVideoSource<T> : VideoSource where T : class, IVideoFrameStorage, new() { /// <summary> /// Peer connection this local video source will add a video track to. /// </summary> [Header("Video track")] [Tooltip("Peer connection this video track is added to.")] public PeerConnection PeerConnection; /// <summary> /// Name of the track. /// </summary> /// <remarks> /// This must comply with the 'msid' attribute rules as defined in /// https://tools.ietf.org/html/draft-ietf-mmusic-msid-05#section-2, which in /// particular constraints the set of allows characters to those allowed for a /// 'token' element as specified in https://tools.ietf.org/html/rfc4566#page-43: /// - Symbols [!#$%'*+-.^_`{|}~] and ampersand &amp; /// - Alphanumerical [A-Za-z0-9] /// </remarks> /// <seealso xref="SdpTokenAttribute.ValidateSdpTokenName"/> [Tooltip("SDP track name.")] [SdpToken(allowEmpty: true)] public string TrackName; /// <summary> /// Automatically add the video track to the peer connection when the Unity component starts. /// </summary> [Tooltip("Automatically add the video track to the peer connection on Start")] public bool AutoAddTrackOnStart = true; /// <summary> /// Video track source providing video frames to the local video track. /// </summary> public ExternalVideoTrackSource Source { get; private set; } /// <summary> /// Video track encapsulated by this component. /// </summary> public LocalVideoTrack Track { get; private set; } /// <summary> /// Frame queue holding the pending frames enqueued by the video source itself, /// which a video renderer needs to read and display. /// </summary> protected VideoFrameQueue<T> _frameQueue; /// <summary> /// Add a new track to the peer connection and start the video track playback. /// </summary> public void StartTrack() { // Ensure the track has a valid name string trackName = TrackName; if (trackName.Length == 0) { // Generate a unique name (GUID) trackName = Guid.NewGuid().ToString(); TrackName = trackName; } SdpTokenAttribute.Validate(trackName, allowEmpty: false); // Create the external source var nativePeer = PeerConnection.Peer; //< TODO - Better abstraction if (typeof(T) == typeof(I420AVideoFrameStorage)) { Source = ExternalVideoTrackSource.CreateFromI420ACallback(OnFrameRequested); } else if (typeof(T) == typeof(Argb32VideoFrameStorage)) { Source = ExternalVideoTrackSource.CreateFromArgb32Callback(OnFrameRequested); } else { throw new NotSupportedException(""); } // Create the local video track if (Source != null) { Track = nativePeer.AddCustomLocalVideoTrack(trackName, Source); if (Track != null) { VideoStreamStarted.Invoke(); } } } /// <summary> /// Stop the video track playback and remove the track from the peer connection. /// </summary> public void StopTrack() { if (Track != null) { var nativePeer = PeerConnection.Peer; nativePeer.RemoveLocalVideoTrack(Track); Track.Dispose(); Track = null; VideoStreamStopped.Invoke(); } if (Source != null) { Source.Dispose(); Source = null; } _frameQueue.Clear(); } protected void Awake() { _frameQueue = new VideoFrameQueue<T>(3); FrameQueue = _frameQueue; PeerConnection.OnInitialized.AddListener(OnPeerInitialized); PeerConnection.OnShutdown.AddListener(OnPeerShutdown); } protected void OnDestroy() { StopTrack(); PeerConnection.OnInitialized.RemoveListener(OnPeerInitialized); PeerConnection.OnShutdown.RemoveListener(OnPeerShutdown); } protected void OnEnable() { if (Track != null) { Track.Enabled = true; } } protected void OnDisable() { if (Track != null) { Track.Enabled = false; } } private void OnPeerInitialized() { if (AutoAddTrackOnStart) { StartTrack(); } } private void OnPeerShutdown() { StopTrack(); } protected abstract void OnFrameRequested(in FrameRequest request); } }
using System; using System.Linq; using System.Linq.Expressions; using DevExpress.ExpressApp.Model; using Xpand.Persistent.Base.General.Controllers; using Xpand.Persistent.Base.Logic.Model; using Xpand.Utils.Helpers; namespace Xpand.ExpressApp.Logic.Security { public class PopulateExecutionContextsController:PopulateController<IContextLogicRule> { string _predefinedValues; protected override void OnActivated() { var modelLogicWrapper = LogicInstallerManager.Instance[(IContextLogicRule)View.CurrentObject].GetModelLogic(); _predefinedValues = string.Join(";", modelLogicWrapper.ExecutionContextsGroup.Select(contexts => contexts.Id)); base.OnActivated(); } protected override string GetPredefinedValues(IModelMember wrapper) { return _predefinedValues; } protected override Expression<Func<IContextLogicRule, object>> GetPropertyName() { return rule => rule.ExecutionContextGroup; } } public class PopulateActionContextsController:PopulateController<IContextLogicRule> { string _predefinedValues; protected override void OnActivated() { var modelLogicWrapper = LogicInstallerManager.Instance[(IContextLogicRule)View.CurrentObject].GetModelLogic(); _predefinedValues = string.Join(";", modelLogicWrapper.ActionExecutionContextGroup.Select(contexts => contexts.Id)); base.OnActivated(); } protected override string GetPredefinedValues(IModelMember wrapper) { return _predefinedValues; } protected override Expression<Func<IContextLogicRule, object>> GetPropertyName() { return rule => rule.ActionExecutionContextGroup; } } public class PopulateFrameContextsController:PopulateController<IContextLogicRule> { string _predefinedValues; protected override void OnActivated() { var modelLogicWrapper = LogicInstallerManager.Instance[(IContextLogicRule)View.CurrentObject].GetModelLogic(); _predefinedValues = string.Join(";", modelLogicWrapper.FrameTemplateContextsGroup.Select(contexts => contexts.Id)); base.OnActivated(); } protected override string GetPredefinedValues(IModelMember wrapper) { return _predefinedValues; } protected override Expression<Func<IContextLogicRule, object>> GetPropertyName() { return rule => rule.FrameTemplateContextGroup; } } public class PopulateViewContextsController:PopulateController<IContextLogicRule> { string _predefinedValues; protected override void OnActivated() { var modelLogicWrapper = LogicInstallerManager.Instance[(IContextLogicRule)View.CurrentObject].GetModelLogic(); _predefinedValues = string.Join(";", modelLogicWrapper.ViewContextsGroup.Select(contexts => contexts.Id)); base.OnActivated(); } protected override string GetPredefinedValues(IModelMember wrapper) { return _predefinedValues; } protected override Expression<Func<IContextLogicRule, object>> GetPropertyName() { return rule => rule.ViewContextGroup; } } public class PopulateViewsController : PopulateController<IContextLogicRule> { protected override System.Collections.Generic.IEnumerable<string> RefreshingProperties() { var propertyName = ((IContextLogicRule) View.CurrentObject).GetPropertyName(rule => rule.TypeInfo); return new []{propertyName}; } protected override string GetPredefinedValues(IModelMember wrapper) { var typeInfo = ((IContextLogicRule) View.CurrentObject).TypeInfo; if (typeInfo!=null) { var objectViews = Application.Model.Views.OfType<IModelObjectView>().Where(modelView => modelView.ModelClass.TypeInfo == typeInfo); return objectViews.Aggregate("", (current, view) => current + (view.Id + ";")).TrimEnd(';'); } return ";"; } protected override Expression<Func<IContextLogicRule, object>> GetPropertyName() { return x => x.View; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace SecureXWebApp.Models { public class Account { [Required] [Display(Name = "Account Number")] public int Id { get; set; } [Required] [Display(Name = "Account Type")] public string AccountType { get; set; } [Required] [Range(0.00, 1000000000.00)] public decimal Funds { get; set; } [Required] [Display(Name = "Customer ID")] public int CustomerId { get; set; } [Required] public string Status { get; set; } = "Pending"; } }
namespace Tensorflow.Framework.Models { public class ScopedTFGraph : Graph { public ScopedTFGraph() : base() { } ~ScopedTFGraph() { base.Dispose(); } } }
using Xamarin.Forms; namespace XForms.Controls { public class NumberEntry : Entry { } }
namespace Adaptive.ReactiveTrader.Client.UI.Connectivity { public sealed partial class ConnectivityStatusView { public ConnectivityStatusView() { InitializeComponent(); } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Bit.Utils.Models.Identity { [ComplexType] public class UserRoleDto { public int Id { get; set; } [Required(ErrorMessage = "User Domain Name is required")] public string? UserId { get; set; } [Required(ErrorMessage = "Role name is required")] public string? RoleName { get; set; } } }
using MongoDB.Bson; using Plus.Core.Tests.Domain; using Plus.Domain.Repositories; namespace Plus.Core.Tests.Repositories { public interface IArticleRepository : IRepository<Article, ObjectId> { } }
using System; public class ModConfiguration : SerializedRawObject { public enum AuthorizationLevel { NOBODY, SUBSCRIBERS, ANYONE } [Serialized] public AuthorizationLevel authPostAlerts = AuthorizationLevel.SUBSCRIBERS; [Serialized] public AuthorizationLevel authSpawnGuests = AuthorizationLevel.SUBSCRIBERS; [Serialized] public string twitchOAuthToken = ""; [Serialized] public string twitchUsername = ""; [Serialized] public string twitchChannelName = ""; public ModConfiguration() { } }
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Text; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder; using Microsoft.Practices.ObjectBuilder2; using Microsoft.Practices.EnterpriseLibrary.Common.Properties; namespace Microsoft.Practices.EnterpriseLibrary.Common.Configuration { public class SystemConfigurationSourceElement : ConfigurationSourceElement { public SystemConfigurationSourceElement() : this(Resources.SystemConfigurationSourceName) { } public SystemConfigurationSourceElement(string name) : base(name, typeof(SystemConfigurationSource)) { } public override IConfigurationSource CreateSource() { IConfigurationSource createdObject = new SystemConfigurationSource(); return createdObject; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkloadViewer.ViewModel { public class SortColMessage { public string ColumnName { get; set; } public ListSortDirection Direction { get; set; } public SortColMessage(string columnName, ListSortDirection direction) { ColumnName = columnName; Direction = direction; } } }
using System.Text.Json.Serialization; namespace Deribit_Scalper_Trainer.DeribitModels { public abstract class BaseReceiveModel<T> { [JsonPropertyName("jsonrpc")] public string JsonRPC { get; set; } [JsonPropertyName("id")] public int Id { get; set; } [JsonPropertyName("result")] public T Result { get; set; } [JsonPropertyName("usIn")] public long UsIn { get; set; } [JsonPropertyName("usOut")] public long UsOut { get; set; } [JsonPropertyName("usDiff")] public long UsDiff { get; set; } [JsonPropertyName("testnet")] public bool IsTestnet { get; set; } } }
using UnityEditor; using UnityEngine; namespace Lasm.UAlive { public static class Images { public static Texture2D ualive_logo; public static Texture2D flow_icon_16; public static Texture2D flow_icon_32; public static Texture2D return_icon_16; public static Texture2D return_icon_32; public static Texture2D variables_16; public static Texture2D variables_32; public static Texture2D override_16; public static Texture2D override_32; public static Texture2D property_16; public static Texture2D property_32; public static Texture2D special_16; public static Texture2D special_32; public static Texture2D class_16; public static Texture2D class_32; public static Texture2D class_variable_32; public static Texture2D parameters_16; public static Texture2D invoke_32; public static Texture2D compilation_16; public static Texture2D settings_16; public static Texture2D search_16; public static Texture2D explorer_16; public static Texture2D void_32; public static Texture2D this_32; public static Texture2D foldout_closed; public static Texture2D foldout_open; public static Texture2D return_event_32; public static Texture2D binary_save_32; public static Texture2D multi_array_32; public static Texture2D value_reroute_32; public static Texture2D flow_reroute_32; private static bool cached; public static void Cache() { if (!cached) { Logos("ualive", out ualive_logo); Icons("flow_16", out flow_icon_16); Icons("flow_32", out flow_icon_32); Icons("return_16", out return_icon_16); Icons("return_32", out return_icon_32); Icons("variables_16", out variables_16); Icons("variables_32", out variables_32); Icons("override_16", out override_16); Icons("override_32", out override_32); Icons("property_16", out property_16); Icons("property_32", out property_32); Icons("special_16", out special_16); Icons("special_32", out special_32); Icons("class_16", out class_16); Icons("class_32", out class_32); Icons("class_variable_32", out class_variable_32); Icons("parameters_16", out parameters_16); Icons("invoke_32", out invoke_32); Icons("compilation_16", out compilation_16); Icons("settings_16", out settings_16); Icons("search_16", out search_16); Icons("explorer_16", out explorer_16); Icons("void_32", out void_32); Icons("this_32", out this_32); Icons("return_event_32", out return_event_32); Icons("binary_save_32", out binary_save_32); Icons("multi_array_32", out multi_array_32); Icons("value_reroute_32", out value_reroute_32); Icons("flow_reroute_32", out flow_reroute_32); cached = true; } } public static void Reset() { cached = false; } private static void Logos(string filename, out Texture2D texture) { var path = UAPaths.Logos + filename + ".png"; texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path); } private static void Icons(string filename, out Texture2D texture) { var path = UAPaths.Icons + filename + ".png"; texture = AssetDatabase.LoadAssetAtPath<Texture2D>(path); } } }
using System.IO; using Core.Security; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTests.FileMangement { [TestClass] public class WhenISaveAString : FileManagerBase { [TestMethod] public void It_should_be_able_to_operate_on_the_data_before_saving() { TestFileManager.Save(() => EncryptionManager.Encrypt(DataIAmSaving, TheKey)); var storedData = File.ReadAllText(FilePath); Assert.IsNotNull(storedData); Assert.IsFalse(storedData.Contains(DataIAmSaving)); } [TestMethod] public void It_should_save_it_in_the_location_I_specify() { TestFileManager.Save(() => DataIAmSaving); var storedData = File.ReadAllText(FilePath); Assert.IsNotNull(storedData); Assert.IsTrue(storedData.Contains(DataIAmSaving)); } } }
using UnityEngine; using System.Collections; public class Pickup : MonoBehaviour { public int id; // 1: Pistol // 2: Shotgun // 3: PlasmaCannon public float ascendHeigt; public float descendHeight; private bool ascend = false; private bool descend = true; void Start () { Destroy(this.gameObject, 20f); } void Update () { Vector3 pos = transform.position; pos.y = pos.y - 5; RaycastHit2D hit = Physics2D.Raycast(pos, Vector3.down, descendHeight+1); if (ascend) { transform.Translate(Vector2.up * Time.deltaTime); } else if (descend) { transform.Translate(Vector2.down * Time.deltaTime); } if (hit) { if (hit.collider.gameObject.layer == 8 && hit.distance >= descendHeight && ascend) { descend = true; ascend = false; } else if (hit.collider.gameObject.layer == 8 && hit.distance <= ascendHeigt && descend) { descend = false; ascend = true; } } } public void destroy() { Destroy(this.gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class Detected : ScoreManager { public Text detectedText; //UI text for detected ratio void Update () { detectedText.text = (Math.Round((FeaturesDetected/FeaturesPresented), 3) * 100).ToString() + "%"; } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ElfLib { public enum SymbolVisibility : byte { Default, Internal, Hidden, Protected, } public class Symbol { internal Pointer internalName; public string Name { get; } public byte Info { get; set; } /// <summary> /// How and if external modules can access this symbol. /// Usually called `st_other` /// </summary> public byte Visibility { get; set; } public short SectionHeaderIndex { get; } public Section Section { get; set; } public long Value { get; set; } public long Size { get; set; } internal Symbol(BinaryReader reader, Section stringTable, List<Section> sections) { internalName = new Pointer(reader.ReadInt32()); Name = stringTable.GetString(internalName); Info = reader.ReadByte(); Visibility = reader.ReadByte(); SectionHeaderIndex = reader.ReadInt16(); try { Section = sections[SectionHeaderIndex]; } catch (ArgumentOutOfRangeException) { Section = null; } Value = reader.ReadInt64(); Size = reader.ReadInt64(); } internal void ToBinaryWriter(BinaryWriter writer) { writer.Write(internalName.AsInt); writer.Write(Info); writer.Write((byte)Visibility); writer.Write(SectionHeaderIndex); writer.Write(Value); writer.Write(Size); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DestroySelf : MonoBehaviour { public void SelfDestruct() { Destroy(gameObject); } public void SelfDestructAfter(float timer) { Destroy(gameObject, timer); } }
using System; using System.Collections.Generic; using System.Text; namespace GiftCardLogParser { public class MoneyOwedToStore { public string Store; public double AmountOwed; } }
using Core; using Core.Service; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; using Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Service.Tests { [TestClass()] public class LocalServiceTests { private CatalogarPatrimonioContext _context; private ILocalService _LocalService; private object listaLocal; [TestInitialize] public void Initialize() { //Arrange var builder = new DbContextOptionsBuilder<CatalogarPatrimonioContext>(); builder.UseInMemoryDatabase("CatalogarPatrimonio"); var options = builder.Options; _context = new CatalogarPatrimonioContext(options); _context.Database.EnsureDeleted(); _context.Database.EnsureCreated(); var Local = new List<Local> { new Local { Id = 1, Nome = "Predipo"}, new Local { Id = 2, Nome = "Casa"}, new Local { Id = 3, Nome = "Empresa"}, }; _context.AddRange(Local); _context.SaveChanges(); _LocalService = new LocalService(_context); } [TestMethod()] public void InserirTest() { // Act _LocalService.Inserir(new Local() { Id = 4, Nome = "Predio" }); // Assert Assert.AreEqual(4, _LocalService.ObterTodos().Count()); var Local = _LocalService.Obter(4); Assert.AreEqual("Casa", Local.Nome); } [TestMethod()] public void EditarTest() { var Local = _LocalService.Obter(3); Local.Nome = "UFS"; _LocalService.Editar(Local); Local = _LocalService.Obter(3); Assert.AreEqual("UFS", Local.Nome); } [TestMethod()] public void RemoverTest() { // Act _LocalService.Remover(2); // Assert Assert.AreEqual(2, _LocalService.ObterTodos().Count()); var Local = _LocalService.Obter(2); Assert.AreEqual(null, Local); } [TestMethod()] public void ObterTodosTest() { // Act var listaLocal = _LocalService.ObterTodos(); // Assert Assert.IsInstanceOfType(listaLocal, typeof(IEnumerable<Local>)); Assert.IsNotNull(listaLocal); Assert.AreEqual(3, listaLocal.Count()); Assert.AreEqual(1, listaLocal.First().Id); Assert.AreEqual("Elétrico", listaLocal.First().Nome); } [TestMethod()] public void ObterTest() { var Local = _LocalService.Obter(1); Assert.IsNotNull(Local); Assert.AreEqual("Casa", Local.Nome); } [TestMethod()] public void ObterPorNomeTest() { var Local = _LocalService.ObterPorNome("Casa"); Assert.IsNotNull(Local); Assert.AreEqual(1, Local.Count()); Assert.AreEqual("Casa", Local.First().Nome); } } }
using System.Collections.Generic; using System.IO; using WodiLib.Ini; using WodiLib.Test.Tools; namespace WodiLib.Test.IO { public static class EditorIniDataTestItemGenerator { #region CreateEditorIniData /** ======================================== * EditorIniオブジェクト作成 * ======================================== */ public static EditorIniData GenerateData0() { return new EditorIniData { StartFlag = 0, LastLoadFile = "MapData/Map000.mps", MainWindowPosition = (0, 0), MainWindowSize = (651, 322), MapChipWindowPosition = (0, 0), MapEventWindowPosition = (273, 230), MapEventWindowSize = (840, 410), MapEventInputWindowPosition = (0,0), CommonEventWindowPosition = (0, 0), CommonEventWindowSize = (800, 640), CommonEventInputWindowPosition = (0, 0), UserDbWindowPosition = (27, 54), ChangeableDbWindowPosition = (27, 54), SystemDbWindowPosition = (27, 54), DatabaseValueNumberDrawType = DatabaseValueNumberDrawType.FromCode("0"), EditTimeDrawType = EditTimeDrawType.On, EditTime=14, NotEditTime=0, IsShowDebugWindow = true, LayerTransparent = LaterTransparentType.FromCode("2"), EventLayerOpacity = EventLayerOpacityType.FromCode("1"), CommandColorType = CommandColorType.FromCode("0"), IsDrawBackgroundImage = true, NotCopyExtList = new ExtensionList(new Extension[] { ".psd", ".sai", ".svg", ".xls", ".db", ".tmp", ".bak", ".db", "dummy_file" }), CommandViewType = 0, BackupType = ProjectBackupType.FromCode("3"), ShortCutKeyList = new EventCommandShortCutKeyList(new[] { EventCommandShortCutKey.One, EventCommandShortCutKey.Two, EventCommandShortCutKey.Three, EventCommandShortCutKey.Four, EventCommandShortCutKey.Five, EventCommandShortCutKey.Six, EventCommandShortCutKey.Seven, EventCommandShortCutKey.Eight, EventCommandShortCutKey.Nine, EventCommandShortCutKey.A, EventCommandShortCutKey.B, EventCommandShortCutKey.C, EventCommandShortCutKey.D, EventCommandShortCutKey.E, EventCommandShortCutKey.F, EventCommandShortCutKey.G, EventCommandShortCutKey.H, EventCommandShortCutKey.I, EventCommandShortCutKey.J, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, EventCommandShortCutKey.One, }), CommandPositionList = new ShortCutPositionList(new ShortCutPosition[] { 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 17, 18, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, }), IsUseExpertCommand = false, }; } #endregion #region OutputTestFile /// <summary>テストディレクトリルート</summary> public static string TestWorkRootDir => $@"{Path.GetTempPath()}WodiLibTest"; /// <summary>テストファイルデータ</summary> public static readonly IEnumerable<(string, byte[])> TestFiles = new List<(string, byte[])> { (@"Dir0\Editor.ini", TestResources.EditorIni0), (@"Dir1\Editor.ini", TestResources.EditorIni1), }; /// <summary> /// テストデータファイルを tmp フォルダに出力する。 /// </summary> public static void OutputFile() { TestWorkRootDir.CreateDirectoryIfNeed(); foreach (var (fileName, bytes) in TestFiles) { var filePath = MakeFileFullPath(fileName); Path.GetDirectoryName(filePath).CreateDirectoryIfNeed(); using (var fs = new FileStream(filePath, FileMode.Create)) { fs.Write(bytes, 0, bytes.Length); } } } /// <summary> /// テストデータファイルを削除する。 /// </summary> public static void DeleteFile() { foreach (var (fileName, _) in TestFiles) { var fileFullPath = MakeFileFullPath(fileName); if (!File.Exists(fileFullPath)) continue; try { File.Delete(fileFullPath); } catch { // 削除に失敗しても何もしない } } } private static string MakeFileFullPath(string fileName) { return $@"{TestWorkRootDir}\{fileName}"; } #endregion } }
namespace Decent.Minecraft.Client.Blocks { public class UnknownBlock : IBlock { } }
using System.Linq; using UnityEditor; using UnityEditor.Localization; using UnityEngine.Localization.Tables; public class ChangeKeyGeneratorExample { public void ChangeKeyGenerator() { var stringTableCollection = LocalizationEditorSettings.GetStringTableCollection("My Game Text"); // Determine the highest Key Id so Unity can continue generating Ids that do not conflict with existing Ids. long maxKeyId = 0; if (stringTableCollection.SharedData.Entries.Count > 0) maxKeyId = stringTableCollection.SharedData.Entries.Max(e => e.Id); stringTableCollection.SharedData.KeyGenerator = new SequentialIDGenerator(maxKeyId + 1); // Mark the asset dirty so that Unity saves the changes EditorUtility.SetDirty(stringTableCollection.SharedData); } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace SoundDevices.IO.WindowsCoreAudio.Internal { [Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMMDeviceCollection { [PreserveSig] int GetCount(out uint pcDevices); [PreserveSig] int Item(uint nDevice, out IMMDevice Device); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Globalization { // Gregorian Calendars use Era Info internal sealed class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) internal string? eraName; // The era name internal string? abbrevEraName; // Abbreviated Era Name internal string? englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, string eraName, string abbrevEraName, string englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) internal sealed class GregorianCalendarHelper { // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear => m_maxYear; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private readonly int m_maxYear; private readonly int m_minYear; private readonly Calendar m_Cal; private readonly EraInfo[] m_EraInfo; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = eraInfo[0].maxEraYear; m_minYear = eraInfo[0].minEraYear; } // EraInfo.yearOffset: The offset to Gregorian year when the era starts. Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset // EraInfo.minEraYear: Min year value in this era. Generally, this value is 1, but this may be affected by the DateTime.MinValue; // EraInfo.maxEraYear: Max year value in this era. (== the year length of the era + 1) private int GetYearOffset(int year, int era, bool throwOnError) { if (year < 0) { if (throwOnError) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } return -1; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } var eras = m_EraInfo; for (int i = 0; i < eras.Length; i++) { EraInfo eraInfo = eras[i]; if (era == eraInfo.era) { if (year >= eraInfo.minEraYear) { if (year <= eraInfo.maxEraYear) { return eraInfo.yearOffset; } else if (!LocalAppContextSwitches.EnforceJapaneseEraYearRanges) { // If we got the year number exceeding the era max year number, this still possible be valid as the date can be created before // introducing new eras after the era we are checking. we'll loop on the eras after the era we have and ensure the year // can exist in one of these eras. otherwise, we'll throw. // Note, we always return the offset associated with the requested era. // // Here is some example: // if we are getting the era number 4 (Heisei) and getting the year number 32. if the era 4 has year range from 1 to 31 // then year 32 exceeded the range of era 4 and we'll try to find out if the years difference (32 - 31 = 1) would lay in // the subsequent eras (e.g era 5 and up) int remainingYears = year - eraInfo.maxEraYear; for (int j = i - 1; j >= 0; j--) { if (remainingYears <= eras[j].maxEraYear) { return eraInfo.yearOffset; } remainingYears -= eras[j].maxEraYear; } } } if (throwOnError) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format( SR.ArgumentOutOfRange_Range, eraInfo.minEraYear, eraInfo.maxEraYear)); } break; // no need to iterate more on eras. } } if (throwOnError) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } return -1; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { return GetYearOffset(year, era, throwOnError: true) + year; } internal bool IsValidYear(int year, int era) { return GetYearOffset(year, era, throwOnError: false) >= 0; } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return absoluteDate; } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return GetAbsoluteDate(year, month, day) * TimeSpan.TicksPerDay; } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", SR.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), SR.Format( SR.ArgumentOutOfRange_Range, -120000, 120000)); } CheckTicksRange(time.Ticks); time.GetDate(out int y, out int m, out int d); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y += i / 12; } else { m = 12 + (i + 1) % 12; y += (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.TimeOfDay.Ticks; Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return new DateTime(ticks); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { CheckTicksRange(time.Ticks); return time.Day; } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return time.DayOfWeek; } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { CheckTicksRange(time.Ticks); return time.DayOfYear; } // Returns the number of days in the month given by the year and // month arguments. // public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return days[month] - days[month - 1]; } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365; } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. foreach (EraInfo eraInfo in m_EraInfo) { if (ticks >= eraInfo.ticks) { return eraInfo.era; } } throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era); } public int[] Eras { get { EraInfo[] eraInfo = m_EraInfo; var eras = new int[eraInfo.Length]; for (int i = 0; i < eraInfo.Length; i++) { eras[i] = eraInfo[i].era; } return eras; } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { CheckTicksRange(time.Ticks); return time.Month; } // Returns the number of months in the specified year and era. // Always return 12. public int GetMonthsInYear(int year, int era) { ValidateYearInEra(year, era); return 12; } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; CheckTicksRange(ticks); foreach (EraInfo eraInfo in m_EraInfo) { if (ticks >= eraInfo.ticks) { return time.Year - eraInfo.yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; foreach (EraInfo eraInfo in m_EraInfo) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= eraInfo.ticks && year > eraInfo.yearOffset) { return year - eraInfo.yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( nameof(day), SR.Format( SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } if (!IsLeapYear(year, era)) { return false; } if (month == 2 && day == 29) { return true; } return false; } // Giving the calendar year and era, ValidateYearInEra will validate the existence of the input year in the input era. // This method will throw if the year or the era is invalid. public void ValidateYearInEra(int year, int era) => GetYearOffset(year, era, throwOnError: true); // Returns the leap month in a calendar year of the specified era. // This method always returns 0 as all calendars using this method don't have leap months. public int GetLeapMonth(int year, int era) { ValidateYearInEra(year, era); return 0; } // Checks whether a given month in the specified era is a leap month. // This method always returns false as all calendars using this method don't have leap months. public bool IsLeapMonth(int year, int month, int era) { ValidateYearInEra(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( nameof(month), SR.Format( SR.ArgumentOutOfRange_Range, 1, 12)); } return false; } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + Calendar.TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return new DateTime(ticks); } public int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } if (year < 100) { int y = year % 100; return (twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y; } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return year; } } }
using Game; using Game.Events; using LisergyServer.Commands; using System; using System.Net; using System.Net.Sockets; using Telepathy; namespace LisergyServer.Core { public abstract class SocketServer { private bool _running = false; protected readonly Server _socketServer; private Message _msg; private CommandExecutor _commandExecutor; protected StrategyGame _game; private int _port; public SocketServer(int port) { _port = port; _commandExecutor = new CommandExecutor(); _commandExecutor.RegisterCommand(new HelpCommand(_commandExecutor)); _socketServer = new Server(); Serialization.LoadSerializers(); _game = SetupGame(); RegisterCommands(_game, _commandExecutor); } public abstract void RegisterCommands(StrategyGame game, CommandExecutor executor); protected abstract ServerPlayer Auth(BaseEvent ev, int connectionID); public abstract void Tick(); public abstract void Disconnect(int connectionID); public abstract ServerType GetServerType(); public abstract StrategyGame SetupGame(); public static Ticker Ticker; private static int TICKS_PER_SECOND = 20; private static int TICK_DELAY_MS = 1000 / TICKS_PER_SECOND; private DateTime _lastTick = DateTime.MinValue; public void Stop() { _socketServer.Stop(); _running = false; } public void RunServer() { _socketServer.Start(_port); try { Ticker = new Ticker(5); Ticker.Run(RunTick); } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Press any key to die"); } } private void RunTick() { _commandExecutor.HandleConsoleCommands(); Tick(); ReadSocketMessages(); } private void ReadSocketMessages() { while (_socketServer.GetNextMessage(out _msg)) { switch (_msg.eventType) { case EventType.Connected: Console.WriteLine("New Connection Received"); break; case EventType.Data: var message = _msg.data; var ev = Serialization.ToEventRaw(message); Game.Log.Debug($"Received {ev}"); var caller = Auth(ev, _msg.connectionId); if (caller != null) { _game.NetworkEvents.RunCallbacks(caller, message); } break; case EventType.Disconnected: Disconnect(_msg.connectionId); break; } } } } }
using System; namespace Jock.Net.TcpBson { /// <summary> /// EventArgs for TcpBsonClient connection denied /// </summary> public class TcpBsonConnectionDeniedEventArgs : EventArgs { internal TcpBsonConnectionDeniedEventArgs(TcpBsonClient client) { this.Client = client; } /// <summary> /// TcpBsonClient instance /// </summary> public TcpBsonClient Client { get; } /// <summary> /// set True if want try reconnection /// </summary> public bool Retry { get; set; } } /// <summary> /// Delegate for TcpBsonClient connection denied /// </summary> /// <param name="e"></param> public delegate void TcpBsonConnectionDeniedEventHandler(TcpBsonConnectionDeniedEventArgs e); }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Baseline; using Baseline.Dates; using Marten.Events.Daemon; namespace Marten.Events.TestSupport { public partial class ProjectionScenario: IEventOperations { private readonly Queue<ScenarioStep> _steps = new(); private readonly DocumentStore _store; public ProjectionScenario(DocumentStore store) { _store = store; } internal IProjectionDaemon Daemon { get; private set; } internal ScenarioStep NextStep => _steps.Any() ? _steps.Peek() : null; internal IDocumentSession Session { get; private set; } /// <summary> /// Disable the scenario from "cleaning" out any existing /// event and projected document data before running the scenario /// </summary> public bool DoNotDeleteExistingData { get; set; } internal Task WaitForNonStaleData() { if (Daemon == null) { return Task.CompletedTask; } return Daemon.WaitForNonStaleData(30.Seconds()); } private ScenarioStep action(Action<IEventOperations> action) { var step = new ScenarioAction(action); _steps.Enqueue(step); return step; } private ScenarioStep assertion(Func<IQuerySession, Task> check) { var step = new ScenarioAssertion(check); _steps.Enqueue(step); return step; } internal async Task Execute() { if (!DoNotDeleteExistingData) { _store.Advanced.Clean.DeleteAllEventData(); foreach (var storageType in _store.Events.Projections.Projections.SelectMany(x => x.Options.StorageTypes)) await _store.Advanced.Clean.DeleteDocumentsByTypeAsync(storageType); } if (_store.Events.Projections.HasAnyAsyncProjections()) { Daemon = _store.BuildProjectionDaemon(); await Daemon.StartAllShards(); } Session = _store.LightweightSession(); try { var exceptions = new List<Exception>(); var number = 0; var descriptions = new List<string>(); while (_steps.Any()) { number++; var step = _steps.Dequeue(); try { await step.Execute(this); descriptions.Add($"{number.ToString().PadLeft(3)}. {step.Description}"); } catch (Exception e) { descriptions.Add($"FAILED: {number.ToString().PadLeft(3)}. {step.Description}"); descriptions.Add(e.ToString()); exceptions.Add(e); } } if (exceptions.Any()) { throw new ProjectionScenarioException(descriptions, exceptions); } } finally { if (Daemon != null) { await Daemon.StopAll(); Daemon.SafeDispose(); } Session?.SafeDispose(); } } } }
using System; namespace BirthdayCelebrations { interface IBirthable { public DateTime Birthdate { get;} } }
using System; using System.Collections.Generic; using wb.Layers; using wb.Slices; namespace wb.App.Commands { public class Find : ICommand { public Find(Args args) { Args = args; } public Args Args { get; } /// <summary> /// Finds all versions of requested layers for specific OS and lists them. /// </summary> void ICommand.Run() { var layerParams = Args.GetLayerParams(); var osParam = Args.GetOsParam(); var list = new List<Slice>(); var dirList = new SliceDirectoryList(Args.SlicesDir); dirList.ForEach(dir => list.AddRange(dir.FindByOs(osParam))); var layers = new LayerList(list).FindLayers(layerParams); foreach (var layer in layers) { Console.WriteLine(layer.Name); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using NuGet.Services.Validation; namespace Validation.PackageSigning.ValidateCertificate { /// <summary> /// The ways an <see cref="EndCertificate"/>'s dependent <see cref="PackageSignature"/> may be affected by /// a change in the certificate's status. /// </summary> public enum SignatureDecision { /// <summary> /// The <see cref="PackageSignature"/> is unaffected by the status change of the <see cref="EndCertificate"/>. /// </summary> Ignore, /// <summary> /// The <see cref="PackageSignature"/> may be affected by the status change of the <see cref="EndCertificate"/>. /// The NuGet client may no longer accept this signature, however, the package does not necessarily need to be /// deleted from the server. This decision will only happen for packages whose status is currently /// <see cref="PackageSignatureStatus.Valid"/>. /// </summary> Warn, /// <summary> /// The <see cref="PackageSignature"/> is affected by the status change of the <see cref="EndCertificate"/>. /// The package should be deleted by an administrator. /// </summary> Reject, } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; using NuScien.Users; using Trivial.Net; using Trivial.Reflection; using Trivial.Security; namespace NuScien.Security { /// <summary> /// The login service provider. /// </summary> public interface ILoginServiceProvider { /// <summary> /// Signs in. /// </summary> /// <param name="tokenRequest">The token request.</param> /// <returns>The login response.</returns> public Task<UserTokenInfo> LoginAsync(TokenRequest<PasswordTokenRequestBody> tokenRequest); /// <summary> /// Signs in. /// </summary> /// <param name="tokenRequest">The token request.</param> /// <returns>The login response.</returns> public Task<UserTokenInfo> LoginAsync(TokenRequest<RefreshTokenRequestBody> tokenRequest); /// <summary> /// Signs in. /// </summary> /// <param name="tokenRequest">The token request.</param> /// <returns>The login response.</returns> public Task<UserTokenInfo> LoginAsync(TokenRequest<CodeTokenRequestBody> tokenRequest); /// <summary> /// Signs in. /// </summary> /// <param name="tokenRequest">The token request.</param> /// <returns>The login response.</returns> public Task<TokenInfo> LoginAsync(TokenRequest<ClientTokenRequestBody> tokenRequest); /// <summary> /// Signs in. /// </summary> /// <param name="accessToken">The access token.</param> /// <returns>The login response.</returns> public Task<UserTokenInfo> AuthAsync(string accessToken); /// <summary> /// Registers or updates. /// </summary> /// <param name="user">The user information.</param> /// <returns>Async task.</returns> public Task Save(UserEntity user); /// <summary> /// Gets the user groups list. /// </summary> /// <param name="user">The user.</param> /// <returns>A user group information list.</returns> public Task<IEnumerable<UserGroupEntity>> ListGroups(UserEntity user); /// <summary> /// Gets the user groups list. /// </summary> /// <param name="q">The name query; null for all.</param> /// <returns>A user group information list.</returns> public Task<IEnumerable<UserGroupEntity>> ListGroups(string q); /// <summary> /// Gets a specific group. /// </summary> /// <param name="id">The identifier.</param> /// <returns>The user info.</returns> public Task<UserEntity> GetUser(string id); /// <summary> /// Gets a specific group. /// </summary> /// <param name="id">The identifier.</param> /// <returns>The group info.</returns> public Task<UserGroupEntity> GetGroup(string id); /// <summary> /// Creates or updates. /// </summary> /// <param name="group">The user group information.</param> /// <returns>Async task.</returns> public Task Save(UserGroupEntity group); } }
namespace DebtPlanner { /// <summary> /// Class DebtAmortizationItem. /// </summary> public class DebtAmortizationItem { /// <summary> /// The debt information /// </summary> public readonly DebtInfo debtInfo; /// <summary> /// Gets the payment. /// </summary> /// <value>The payment.</value> public decimal Payment { get; } private decimal CurrentBalance { get; } private decimal MonthlyRate { get; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name => debtInfo.Name; /// <summary> /// Gets the interest. /// </summary> /// <value>The interest.</value> public decimal Interest => DebtInfo.RoundUp(MonthlyRate * CurrentBalance, 2); /// <summary> /// Gets the applied payment. /// </summary> /// <value>The applied payment.</value> public decimal AppliedPayment => Payment - Interest; /// <summary> /// Gets the remaining balance. /// </summary> /// <value>The remaining balance.</value> public decimal RemainingBalance => CurrentBalance - AppliedPayment; /// <summary> /// Initializes a new instance of the <see cref="DebtAmortizationItem"/> class. /// </summary> /// <param name="debt">The debt.</param> public DebtAmortizationItem(DebtInfo debt) { debtInfo = debt; Payment = debt.CurrentPayment; CurrentBalance = debt.Balance; MonthlyRate = Payment >= CurrentBalance ? 0 : debt.AverageMonthyPr; debtInfo = new DebtInfo(Name, RemainingBalance, debt.Rate, Payment); } /// <inheritdoc /> public override string ToString() => $"{Payment,10:C} | {Interest,8:C} | {AppliedPayment,10:C} | {RemainingBalance,12:C}"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace Paragraph.Data.Models { // Add profile data for application users by adding properties to the ParagraphUser class public class ParagraphUser : IdentityUser { public ICollection<Article> Articles { get; set; } = new HashSet<Article>(); public ICollection<Comment> Comment { get; set; } = new HashSet<Comment>(); public ICollection<Request> RequestsSent { get; set; } = new HashSet<Request>(); public ICollection<Request> RequestsReceived { get; set; } = new HashSet<Request>(); } }
using System; using System.IO; using System.Net; namespace ScrapingFromOurOwn { public static class Scraper { public static String Scrape(String url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; WebResponse response = null; try { response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8); String code = reader.ReadToEnd(); reader.Close(); response.Close(); return code; } catch { return null; } } } }
using CS253ShortestPath.Services; namespace CS253ShortestPath.Droid { public class CsServiceDroid : CsService { private CsServiceDroid() { if (_instance != null) return; _instance = this; _instance.Location = new LocationManagerDroid(); } public static void Init() { _ = new CsServiceDroid(); } } }
namespace DigitallyImported.Controls { using System; using System.Diagnostics; /// <summary> /// Static utility methods /// </summary> public class Utilities { private Utilities() { } /// <summary> /// Splits a string up based on capital letters, i.e. ThisString becomes This String /// </summary> /// <param name="name">The string to split</param> /// <returns></returns> public static string SplitName(string name) { char[] buffer = name.ToCharArray(); foreach (char c in buffer) { if (char.IsUpper(c)) { name = name.Replace(c.ToString(), " " + c.ToString()); } } return name.Trim(); } /// <summary> /// Starts a process based on the file extension of the string passed in /// </summary> /// <param name="processToStart">The name of the process to start</param> public static void StartProcess(string processToStart) { if (processToStart != null && processToStart != string.Empty) { Process.Start(processToStart); } } } }
using SIM.Instances; using SIM.Tool.Base.Plugins; using SIM.Tool.Windows.MainWindowComponents.Buttons; namespace SIM.Tool.Windows.MainWindowComponents { public static class MainWindowButtonFactory { public static IMainWindowButton GetBrowseButton(Instance instance) { if (instance != null && instance.Type == Instance.InstanceType.SitecoreContainer) { return new BrowseSitecoreContainerWebsiteButton(); } return new BrowseHomePageButton(); } } }
namespace tyr.Core.Extensions { public static class CharExtensions { public static bool IsDecimalSign(this char source) { return source == '+' || source == '-'; } } }
using ComparableGenerator; namespace GenerateSourceForNotNullable { [Comparable] internal partial class CompositeObject { [CompareBy] public CompositeChildValue Value { get; set; } } public class CompositeChildValue : ClassObject { } }
using System.Collections.Generic; using UnityEngine; public class ObjectPool<T> where T : MonoBehaviour { #region Variable private readonly List<T> _pools = new List<T>(); // Pool private int _count; // Count of created object private readonly T _prefab; // To instantiate prefab private Transform _parent; #endregion public ObjectPool(T prefab) { _prefab = prefab; } /// <summary> /// Initialized pool /// </summary> /// <param name="count">To Push count</param> /// <param name="container">Parent of spawn transform</param> public void InitPool(Transform container = null,int count = 1) { for (int i = 0; i < count; i++) { T go = Object.Instantiate(_prefab).GetComponent<T>(); // Instance // Set Parent transform if (container != null) { _parent = container; go.transform.SetParent(container); } _pools.Add(go); // Push go.gameObject.SetActive(false); } } /// <summary> /// Create Pooled object /// </summary> /// <param name="position">Spawn Position</param> public void Create(Vector3 position) { // No more pool memory exception if (_count > _pools.Count - 1) { // If all pool object is active if (_pools[0].gameObject.activeSelf) { InitPool(_parent); } else { _count = 0; } } // Spawn _pools[_count].gameObject.SetActive(true); _pools[_count].transform.position = position; _count++; } }
using System; using System.IO; using System.Linq; namespace Day04 { public class Program { public static void Main(string[] args) { var input = File.ReadAllLines("input.txt").Select(RoomParser.GetRoomDescription).ToArray(); PartOne(input); PartTwo(input); } private static void PartOne(RoomDescription[] input) { int sectorIdSum = input.Where(x => x.Validate()).Select(x => x.SectorId).Sum(); Console.WriteLine("Solution part one: {0}", sectorIdSum); } private static void PartTwo(RoomDescription[] input) { var roomWithNorth = input.Where(x => x.Decrypt().Contains("north")).Select(x => x.SectorId).Single(); Console.WriteLine("Solution part two: {0}", roomWithNorth); } } }
using System.Collections.Generic; namespace Cosmos.Business.Extensions.Holiday.Globalization { /// <summary> /// Translation resource map /// </summary> public class TranslationResourceMap { /* * 根据日期查询 * 01-01 公历 01-01 * chinese-01-01 农历 01-01 * muslim-01-01 伊斯兰 01-01 * easter -48 基督教 -48 * * 根据名称查询 * labour 劳动节(对应的日期查询,可以是 05-01) * * 查询的结果是一组带有 LanguageTag 标记的 PureTranslationText */ private readonly Dictionary<string, TranslationResource> _holidayResourceMap; private readonly object _mapLockObj = new object(); /// <summary> /// Create a new instance of <see cref="TranslationResourceMap"/> /// </summary> public TranslationResourceMap() { _holidayResourceMap = new Dictionary<string, TranslationResource>(); } #region Add /// <summary> /// Add /// </summary> /// <param name="key"></param> /// <param name="resource"></param> public void Add(string key, TranslationResource resource) { if (string.IsNullOrWhiteSpace(key)) return; if (resource == null) return; lock (_mapLockObj) { if (_holidayResourceMap.ContainsKey(key)) { _holidayResourceMap[key].Merge(resource); } else { _holidayResourceMap.Add(key, resource); } } } /// <summary> /// Add /// </summary> /// <param name="key"></param> /// <param name="resource"></param> /// <param name="type"></param> public void Add(string key, Dictionary<string, string> resource, ResourceType type) { if (string.IsNullOrWhiteSpace(key)) return; if (resource == null) return; lock (_mapLockObj) { if (_holidayResourceMap.ContainsKey(key)) { _holidayResourceMap[key].AddOrUpdate(resource, type); } else { _holidayResourceMap.Add(key, new TranslationResource(resource, type)); } } } #endregion #region Gets /// <summary> /// Try get /// </summary> /// <param name="key"></param> /// <param name="lang"></param> /// <param name="text"></param> /// <returns></returns> public bool TryGet(string key, string lang, out string text) { text = default; if (string.IsNullOrWhiteSpace(key)) return false; lock (_mapLockObj) { if (!_holidayResourceMap.ContainsKey(key)) return false; return _holidayResourceMap[key].TryGetResource(lang, out text); } } /// <summary> /// Try get /// </summary> /// <param name="key"></param> /// <param name="lang"></param> /// <param name="type"></param> /// <param name="text"></param> /// <returns></returns> public bool TryGet(string key, string lang, ResourceType type, out string text) { text = default; if (string.IsNullOrWhiteSpace(key)) return false; lock (_mapLockObj) { if (!_holidayResourceMap.ContainsKey(key)) return false; return _holidayResourceMap[key].TryGetResource(lang, type, out text); } } #endregion } }
namespace MediatR.Behaviors.ResponseCaching { public interface IRequestCacheKeyProvider<in TRequest> { string GetCacheKey(TRequest request); } }
using ReactiveUI; namespace SpaceHaven_Save_Editor.Data { public class DataProp : ReactiveObject { private int _value; public DataProp() { Name = "def"; } public int Id { get; set; } public string Name { get; set; } public int Value { get => _value; set => this.RaiseAndSetIfChanged(ref _value, value); } public override string ToString() { return Name; } } }
using Gtk; using System; using System.Collections; using System.Linq; using guidemo; using MySql.Data.MySqlClient; using Org.BouncyCastle.Math.EC; namespace gui_demo { class SharpApp : Window { ListStore store; Statusbar statusbar; public SharpApp() : base("上海交大学生管理系统") { //修改背景色 Fixed fix = new Fixed(); BorderWidth = 8; SetDefaultSize(1000, 800); SetPosition(WindowPosition.Center); DeleteEvent += delegate { Application.Quit(); }; NavigationBar navigationBar = new NavigationBar(); navigationBar.AddItem("学生信息", ((sender, args) => { })) .AddItem("学生信息1", ((sender, args) => { })) .AddItem("学生信息2", ((sender, args) => { })) .AddItem("学生信息3", ((sender, args) => { })) .AddItem("学生信息4", ((sender, args) => { })); // 导航栏 Alignment halign = new Alignment(0, 1, 0, 1) {navigationBar.NavBox}; // 显示数据 Alignment alignData = new Alignment(0, 0, 1, 1); VBox vbox = new VBox(true, 8); ScrolledWindow sw = new ScrolledWindow(); sw.SetSizeRequest(1000, 800); sw.ShadowType = ShadowType.EtchedIn; sw.SetPolicy(PolicyType.Automatic, PolicyType.Automatic); vbox.PackStart(sw, true, true, 0); TreeView treeView = new TreeView() {RulesHint = true}; treeView.RowActivated += OnRowActivated; sw.Add(treeView); string cs = @"server=192.168.31.70;userid=root;password=liux1228;database=stu_info"; var con = new MySqlConnection(cs); con.Open(); string sql = "SELECT * FROM stu_info.students"; var cmd = new MySqlCommand(sql, con); MySqlDataReader rdr = cmd.ExecuteReader(); ArrayList actresses = new ArrayList(); while (rdr.Read()) { actresses.Add(new Student( rdr.GetInt32(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetString(3), rdr.GetInt32(4))); } con.Close(); // store = CreateModel(actresses); ListView listView = new ListView(treeView); // 编辑事件应该弹出一个对话框,询问是否确认编辑,确认编辑后可以添加修改数据库的逻辑, // 此处只是编辑,内存上的修改,并没有去更新数据库,可以自行添加 listView.AddColumn("Id", ColumnIndex.Id, ((column, cell, model, iter) => { Student student = (Student) model.GetValue(iter, 0); ((cell as Gtk.CellRendererText)!).Text = student.Id.ToString(); }), false, null) .AddColumn("Name", ColumnIndex.Name, ((column, cell, model, iter) => { Student student = (Student) model.GetValue(iter, 0); ((cell as Gtk.CellRendererText)!).Text = student.Name.ToString(); }), true, ((o, args) => { TreeIter iter; listView.MusicListStore.GetIter(out iter, new Gtk.TreePath(args.Path)); var song = (Student) listView.MusicListStore.GetValue(iter, 0)!; song.Name = args.NewText; })) .AddColumn("Sex", ColumnIndex.Sex, ((column, cell, model, iter) => { Student student = (Student) model.GetValue(iter, 0); ((cell as Gtk.CellRendererText)!).Text = student.Sex.ToString(); }), true, ((o, args) => { TreeIter iter = default; listView.MusicListStore.GetIter(out iter, new Gtk.TreePath(args.Path)); var song = (Student) listView.MusicListStore.GetValue(iter, 0)!; song.Sex = args.NewText; })) .AddColumn("Age", ColumnIndex.Age, ((column, cell, model, iter) => { Student student = (Student) model.GetValue(iter, 0); ((cell as Gtk.CellRendererText)!).Text = student.Age.ToString(); }), true, ((o, args) => { TreeIter iter = default; listView.MusicListStore.GetIter(out iter, new Gtk.TreePath(args.Path)); var song = (Student) listView.MusicListStore.GetValue(iter, 0)!; song.Age = int.Parse(args.NewText); })) .AddColumn("Score", ColumnIndex.Score, ((column, cell, model, iter) => { Student student = (Student) model.GetValue(iter, 0); ((cell as Gtk.CellRendererText)!).Text = student.Score.ToString(); }), true, ((o, args) => { TreeIter iter = default; listView.MusicListStore.GetIter(out iter, new Gtk.TreePath(args.Path)); var song = (Student) listView.MusicListStore.GetValue(iter, 0)!; song.Score = int.Parse(args.NewText); })) .SetItemModel(actresses); alignData.Add(vbox); fix.Put(alignData, 0, 40); fix.Put(halign, 0, 0); Add(fix); ShowAll(); } void OnRowActivated(object sender, RowActivatedArgs args) { // // 弹出一个对话框,执行CRUD // TreeIter iter; // TreeView view = (TreeView) sender; // // if (view.Model.GetIter(out iter, args.Path)) // { // string row = (string) view.Model.GetValue(iter, (int) Column.Name); // row += ", " + (string) view.Model.GetValue(iter, (int) Column.Age); // row += ", " + view.Model.GetValue(iter, (int) Column.Score); // // statusbar.Push(0, row); // } } ListStore CreateModel(ArrayList actresses) { ListStore store = new ListStore(typeof(int), typeof(string), typeof(string), typeof(int), typeof(int)); foreach (Actress act in actresses) { store.AppendValues(act.Index, act.Name, act.Sex, act.Age, act.Score); } return store; } void OnClick(object sender, EventArgs args) { string cs = @"server=localhost;userid=root;password=liux1228;database=stu_info"; var con = new MySqlConnection(cs); con.Open(); string sql = "SELECT * FROM stu_info.students"; var cmd = new MySqlCommand(sql, con); MySqlDataReader rdr = cmd.ExecuteReader(); ArrayList actresses = new ArrayList(); while (rdr.Read()) { actresses.Add(new Actress( rdr.GetInt32(0), rdr.GetString(1), rdr.GetInt32(2), rdr.GetString(3), rdr.GetInt32(4))); } } public static void Main() { Application.Init(); new SharpApp(); Application.Run(); } } public class Actress { public string Name; public string Sex; public int Age; public int Index; public int Score; public Actress(int index, string name, int age, string sex, int score) { Sex = sex; Index = index; Name = name; Age = age; Score = score; } } }
using System; namespace cs_learner { class ExceptionLearner { public string name = "exception"; public void print() { try{ int div = 0; int a = 10 / div; } catch (Exception e) { Console.WriteLine(e); } finally { Console.WriteLine("finally"); } } public static void test(ExceptionLearner obj) { Console.WriteLine(obj.name + ":begin to run testcase."); obj.print(); Console.WriteLine(obj.name + ":end."); } }; }